octtree.py 26.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
"""
OctTree
-------
Constuctors for OctTree classes that can decrease the number of comparisons
for detecting nearby records for example. This is an implementation that uses
Haversine distances for comparisons between records for identification of
neighbours.
"""

10
from dataclasses import dataclass
11
from typing import List, Optional
12
import datetime
13
from .distance_metrics import haversine, destination
14
from .utils import LatitudeError, DateWarning
15
from math import degrees, sqrt
16
from warnings import warn
Joseph Siddons's avatar
Joseph Siddons committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39


class SpaceTimeRecord:
    """
    ICOADS Record class.

    This is a simple instance of an ICOARDS record, it requires position and
    temporal data. It can optionally include a UID and extra data.

    The temporal component was designed to use `datetime` values, however all
    methods will work with numeric datetime information - for example a pentad,
    timestamp, julian day, etc. Note that any uses within an OctTree and
    SpaceTimeRectangle must also have timedelta values replaced with numeric
    ranges in this case.

    Equality is checked only on the required fields + UID if it is specified.

    Parameters
    ----------
    lon : float
        Horizontal coordinate (longitude).
    lat : float
        Vertical coordinate (latitude).
40
    datetime : datetime.datetime
Joseph Siddons's avatar
Joseph Siddons committed
41 42 43 44 45
        Datetime of the record. Can also be a numeric value such as pentad.
        Comparisons between Records with datetime and Records with numeric
        datetime will fail.
    uid : str | None
        Unique Identifier.
46 47
    fix_lon : bool
        Force longitude to -180, 180
Joseph Siddons's avatar
Joseph Siddons committed
48 49 50 51 52 53 54 55 56
    **data
        Additional data passed to the SpaceTimeRecord for use by other functions
        or classes.
    """

    def __init__(
        self,
        lon: float,
        lat: float,
57
        datetime: datetime.datetime,
58
        uid: Optional[str] = None,
59
        fix_lon: bool = True,
Joseph Siddons's avatar
Joseph Siddons committed
60 61 62
        **data,
    ) -> None:
        self.lon = lon
63 64 65 66 67 68 69
        if fix_lon:
            # Move lon to -180, 180
            self.lon = ((self.lon + 540) % 360) - 180
        if lat < -90 or lat > 90:
            raise LatitudeError(
                "Expected latitude value to be between -90 and 90 degrees"
            )
Joseph Siddons's avatar
Joseph Siddons committed
70 71 72 73 74 75 76 77
        self.lat = lat
        self.datetime = datetime
        self.uid = uid
        for var, val in data.items():
            setattr(self, var, val)
        return None

    def __str__(self) -> str:
78 79 80 81
        return (
            f"SpaceTimeRecord(x = {self.lon}, y = {self.lat}, "
            + f"datetime = {self.datetime}, uid = {self.uid})"
        )
Joseph Siddons's avatar
Joseph Siddons committed
82 83

    def __eq__(self, other: object) -> bool:
84 85 86 87
        if not isinstance(other, SpaceTimeRecord):
            return False
        if self.uid and other.uid:
            return self.uid == other.uid
Joseph Siddons's avatar
Joseph Siddons committed
88
        return (
89
            self.lon == other.lon
Joseph Siddons's avatar
Joseph Siddons committed
90 91 92 93 94
            and self.lat == other.lat
            and self.datetime == other.datetime
            and (not (self.uid or other.uid) or self.uid == other.uid)
        )

95 96 97 98 99 100 101 102 103
    def distance(self, other: object) -> float:
        """
        Compute the Haversine distance to another SpaceTimeRecord.
        Only computes spatial distance.
        """
        if not isinstance(other, SpaceTimeRecord):
            raise TypeError("Argument other must be an instance of Record")
        return haversine(self.lon, self.lat, other.lon, other.lat)

Joseph Siddons's avatar
Joseph Siddons committed
104

105
class SpaceTimeRecords(List[SpaceTimeRecord]):
Joseph Siddons's avatar
Joseph Siddons committed
106 107 108
    """List of SpaceTimeRecords"""


109
@dataclass
Joseph Siddons's avatar
Joseph Siddons committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
class SpaceTimeRectangle:
    """
    A simple Space Time SpaceTimeRectangle class.

    This constructs a simple Rectangle object.
    The defining coordinates are the centres of the box, and the extents
    are the full width, height, and time extent.

    Whilst the rectangle is assumed to lie on the surface of Earth, this is
    a projection as the rectangle is defined by a longitude/latitude range.

    The temporal components are defined in the same way as the spatial
    components, that is that the `datetime` component (t) is the "centre", and
    the time extent (dt) is the full time range of the box.

    Parameters
    ----------
127 128 129 130 131 132 133 134 135 136 137 138
    west : float
        Western boundary of the Rectangle
    east : float
        Eastern boundary of the Rectangle
    south : float
        Southern boundary of the Rectangle
    north : float
        Northern boundary of the Rectangle
    start : datetime.datetime
        Start datetime of the Rectangle
    end : datetime.datetime
        End datetime of the Rectangle
Joseph Siddons's avatar
Joseph Siddons committed
139 140
    """

141 142 143 144 145 146
    west: float
    east: float
    south: float
    north: float
    start: datetime.datetime
    end: datetime.datetime
147 148

    def __post_init__(self):
149 150 151 152 153
        if self.east > 180 or self.east < -180:
            self.east = ((self.east + 540) % 360) - 180
        if self.west > 180 or self.west < -180:
            self.west = ((self.west + 540) % 360) - 180
        if self.north > 90 or self.south < -90:
154
            raise LatitudeError(
155 156
                "Latitude bounds are out of bounds. "
                + f"{self.north = }, {self.south = }"
157
            )
158 159 160
        if self.end < self.start:
            warn("End date is before start date. Swapping", DateWarning)
            self.start, self.end = self.end, self.start
Joseph Siddons's avatar
Joseph Siddons committed
161

162
    @property
163 164 165
    def lat_range(self) -> float:
        """Latitude range of the Rectangle"""
        return self.north - self.south
166 167

    @property
168 169 170
    def lat(self) -> float:
        """Centre latitude of the Rectangle"""
        return self.south + self.lat_range / 2
171 172

    @property
173 174 175 176
    def lon_range(self) -> float:
        """Longitude range of the Rectangle"""
        if self.east < self.west:
            return self.east - self.west + 360
Joseph Siddons's avatar
Joseph Siddons committed
177

178
        return self.east - self.west
179 180

    @property
181 182 183 184
    def lon(self) -> float:
        """Centre longitude of the Rectangle"""
        lon = self.west + self.lon_range / 2
        return ((lon + 540) % 360) - 180
185 186 187 188 189 190 191

    @property
    def edge_dist(self) -> float:
        """Approximate maximum distance from the centre to an edge"""
        corner_dist = max(
            haversine(self.lon, self.lat, self.east, self.north),
            haversine(self.lon, self.lat, self.east, self.south),
Joseph Siddons's avatar
Joseph Siddons committed
192
        )
193
        if self.north * self.south < 0:
194 195 196 197 198 199
            corner_dist = max(
                corner_dist,
                haversine(self.lon, self.lat, self.east, 0),
            )
        return corner_dist

200 201
    @property
    def time_range(self) -> datetime.timedelta:
202
        """The time extent of the Rectangle"""
203 204 205 206
        return self.end - self.start

    @property
    def centre_datetime(self) -> datetime.datetime:
207
        """The midpoint time of the Rectangle"""
208 209
        return self.start + (self.end - self.start) / 2

210 211 212 213 214 215 216 217 218 219 220 221 222 223
    def _test_east_west(self, lon: float) -> bool:
        if self.lon_range >= 360:
            # Rectangle encircles earth
            return True
        if self.east > self.lon and self.west < self.lon:
            return lon <= self.east and lon >= self.west
        if self.east < self.lon:
            return not (lon > self.east and lon < self.west)
        if self.west > self.lon:
            return not (lon < self.east and lon > self.west)
        return False

    def _test_north_south(self, lat: float) -> bool:
        return lat <= self.north and lat >= self.south
Joseph Siddons's avatar
Joseph Siddons committed
224 225 226

    def contains(self, point: SpaceTimeRecord) -> bool:
        """Test if a point is contained within the SpaceTimeRectangle"""
227 228 229 230
        if point.datetime > self.end or point.datetime < self.start:
            return False
        return self._test_north_south(point.lat) and self._test_east_west(
            point.lon
Joseph Siddons's avatar
Joseph Siddons committed
231 232 233 234
        )

    def intersects(self, other: object) -> bool:
        """Test if another Rectangle object intersects this Rectangle"""
235 236 237 238 239 240 241 242 243 244 245 246 247 248
        if not isinstance(other, SpaceTimeRectangle):
            raise TypeError(
                f"other must be a Rectangle class, got {type(other)}"
            )
        if other.end < self.start or other.start > self.end:
            # Not in the same time range
            return False
        if other.south > self.north:
            # Other is fully north of self
            return False
        if other.north < self.south:
            # Other is fully south of self
            return False
        # Handle east / west edges
249 250 251 252 253 254 255 256
        return (
            self._test_east_west(other.west)
            or self._test_east_west(other.east)
            # Fully contained within other
            or (
                other._test_east_west(self.west)
                and other._test_east_west(self.east)
            )
Joseph Siddons's avatar
Joseph Siddons committed
257 258 259 260 261 262
        )

    def nearby(
        self,
        point: SpaceTimeRecord,
        dist: float,
263
        t_dist: datetime.timedelta,
Joseph Siddons's avatar
Joseph Siddons committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    ) -> bool:
        """
        Check if point is nearby the Rectangle

        Determines if a SpaceTimeRecord that falls on the surface of Earth is
        nearby to the rectangle in space and time. This calculation uses the
        Haversine distance metric.

        Distance from rectangle to point is challenging on the surface of a
        sphere, this calculation will return false positives as a check based
        on the distance from the centre of the rectangle to the corners, or
        to its Eastern edge (if the rectangle crosses the equator) is used in
        combination with the input distance.

        The primary use-case of this method is for querying an OctTree for
        nearby Records.

        Parameters
        ----------
        point : SpaceTimeRecord
        dist : float,
285
        t_dist : datetime.timedelta
Joseph Siddons's avatar
Joseph Siddons committed
286 287 288 289 290

        Returns
        -------
        bool : True if the point is <= dist + max(dist(centre, corners))
        """
291
        if (
292 293
            point.datetime - t_dist > self.end
            or point.datetime + t_dist < self.start
294 295
        ):
            return False
Joseph Siddons's avatar
Joseph Siddons committed
296 297 298
        # QUESTION: Is this sufficient? Possibly it is overkill
        return (
            haversine(self.lon, self.lat, point.lon, point.lat)
299
            <= dist + self.edge_dist
300 301 302 303
        )


class SpaceTimeEllipse:
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    """
    A simple Ellipse Class for an ellipse on the surface of a sphere.

    Parameters
    ----------
    lon : float
        Horizontal centre of the ellipse
    lat : float
        Vertical centre of the ellipse
    a : float
        Length of the semi-major axis
    b : float
        Length of the semi-minor axis
    theta : float
        Angle of the semi-major axis from horizontal anti-clockwise in radians
319 320 321 322
    start : datetime.datetime
        Start date of the Ellipse
    end : datetime.datetime
        Send date of the Ellipse
323
    """
324 325 326 327 328

    def __init__(
        self,
        lon: float,
        lat: float,
329 330 331
        a: float,
        b: float,
        theta: float,
332 333
        start: datetime.datetime,
        end: datetime.datetime,
334 335 336 337
    ) -> None:
        self.a = a
        self.b = b
        self.lon = lon
338 339
        if self.lon > 180:
            self.lon = ((self.lon + 540) % 360) - 180
340
        self.lat = lat
341 342 343 344 345 346
        self.start = start
        self.end = end

        if self.end < self.start:
            warn("End date is before start date. Swapping")
            self.start, self.end = self.end, self.start
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        # theta is anti-clockwise angle from horizontal in radians
        self.theta = theta
        # bearing is angle clockwise from north in degrees
        self.bearing = (90 - degrees(self.theta)) % 360

        a2 = self.a * self.a
        b2 = self.b * self.b

        self.c = sqrt(a2 - b2)
        self.p1_lon, self.p1_lat = destination(
            self.lon,
            self.lat,
            self.bearing,
            self.c,
        )
        self.p2_lon, self.p2_lat = destination(
            self.lon,
            self.lat,
365
            (self.bearing - 180) % 360,
366 367 368 369 370
            self.c,
        )

    def contains(self, point: SpaceTimeRecord) -> bool:
        """Test if a point is contained within the Ellipse"""
371 372
        if point.datetime > self.end or point.datetime < self.start:
            return False
373
        return (
374 375 376
            haversine(self.p1_lon, self.p1_lat, point.lon, point.lat)
            + haversine(self.p2_lon, self.p2_lat, point.lon, point.lat)
        ) <= 2 * self.a
377 378 379

    def nearby_rect(self, rect: SpaceTimeRectangle) -> bool:
        """Test if a rectangle is near to the Ellipse"""
380
        if rect.start > self.end or rect.end < self.start:
381 382 383 384
            return False
        # TODO: Check corners, and 0 lat
        return (
            haversine(self.p1_lon, self.p1_lat, rect.lon, rect.lat)
385
            <= rect.edge_dist + self.a
386
            and haversine(self.p2_lon, self.p2_lat, rect.lon, rect.lat)
387
            <= rect.edge_dist + self.a
Joseph Siddons's avatar
Joseph Siddons committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        )


class OctTree:
    """
    A Simple OctTree class for PyCOADS.

    Acts as a space-time OctTree on the surface of Earth, allowing for querying
    nearby points faster than searching a full DataFrame. As SpaceTimeRecords
    are added to the OctTree, the OctTree divides into 8 children as the
    capacity is reached. Additional SpaceTimeRecords are then added to the
    children where they fall within the child OctTree's boundary.

    SpaceTimeRecords already part of the OctTree before divided are not
    distributed to the children OctTrees.

    Whilst the OctTree has a temporal component, and was designed to utilise
    datetime / timedelta objects, numeric values and ranges can be used. This
    usage must be consistent for the boundary and all SpaceTimeRecords that
    are part of the OctTree. This allows for usage of pentad, timestamp,
    Julian day, etc. as datetime values.

    Parameters
    ----------
    boundary : SpaceTimeRectangle
        The bounding SpaceTimeRectangle of the QuadTree
    capacity : int
        The capacity of each cell, if max_depth is set then a cell at the
        maximum depth may contain more points than the capacity.
    depth : int
        The current depth of the cell. Initialises to zero if unset.
    max_depth : int | None
        The maximum depth of the QuadTree. If set, this can override the
        capacity for cells at the maximum depth.
    """

    def __init__(
        self,
        boundary: SpaceTimeRectangle,
        capacity: int = 5,
        depth: int = 0,
429
        max_depth: Optional[int] = None,
Joseph Siddons's avatar
Joseph Siddons committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    ) -> None:
        self.boundary = boundary
        self.capacity = capacity
        self.depth = depth
        self.max_depth = max_depth
        self.points = SpaceTimeRecords()
        self.divided: bool = False
        return None

    def __str__(self) -> str:
        indent = "    " * self.depth
        out = f"{indent}OctTree:\n"
        out += f"{indent}- boundary: {self.boundary}\n"
        out += f"{indent}- capacity: {self.capacity}\n"
        out += f"{indent}- depth: {self.depth}\n"
        if self.max_depth:
            out += f"{indent}- max_depth: {self.max_depth}\n"
        if self.points:
            out += f"{indent}- contents:\n"
            out += f"{indent}- number of elements: {len(self.points)}\n"
            for p in self.points:
                out += f"{indent}  * {p}\n"
        if self.divided:
            out += f"{indent}- with children:\n"
            out += f"{self.northwestback}"
            out += f"{self.northeastback}"
            out += f"{self.southwestback}"
            out += f"{self.southeastback}"
            out += f"{self.northwestfwd}"
            out += f"{self.northeastfwd}"
            out += f"{self.southwestfwd}"
            out += f"{self.southeastfwd}"
        return out

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    def len(self, _current_len: int = 0) -> int:
        """Get the number of points in the OctTree"""
        _current_len += len(self.points)
        print(_current_len)
        if not self.divided:
            return _current_len

        _current_len = self.northeastback.len(_current_len)
        _current_len = self.northwestback.len(_current_len)
        _current_len = self.southeastback.len(_current_len)
        _current_len = self.southwestback.len(_current_len)
        _current_len = self.northeastfwd.len(_current_len)
        _current_len = self.northwestfwd.len(_current_len)
        _current_len = self.southeastfwd.len(_current_len)
        _current_len = self.southwestfwd.len(_current_len)

        return _current_len

Joseph Siddons's avatar
Joseph Siddons committed
482 483 484 485
    def divide(self):
        """Divide the QuadTree"""
        self.northwestfwd = OctTree(
            SpaceTimeRectangle(
486 487 488 489 490 491
                self.boundary.west,
                self.boundary.lon,
                self.boundary.lat,
                self.boundary.north,
                self.boundary.centre_datetime,
                self.boundary.end,
Joseph Siddons's avatar
Joseph Siddons committed
492 493 494 495 496 497 498
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.northeastfwd = OctTree(
            SpaceTimeRectangle(
499 500 501 502 503 504
                self.boundary.lon,
                self.boundary.east,
                self.boundary.lat,
                self.boundary.north,
                self.boundary.centre_datetime,
                self.boundary.end,
Joseph Siddons's avatar
Joseph Siddons committed
505 506 507 508 509 510 511
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.southwestfwd = OctTree(
            SpaceTimeRectangle(
512 513 514 515 516 517
                self.boundary.west,
                self.boundary.lon,
                self.boundary.south,
                self.boundary.lat,
                self.boundary.centre_datetime,
                self.boundary.end,
Joseph Siddons's avatar
Joseph Siddons committed
518 519 520 521 522 523 524
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.southeastfwd = OctTree(
            SpaceTimeRectangle(
525 526 527 528 529 530
                self.boundary.lon,
                self.boundary.east,
                self.boundary.south,
                self.boundary.lat,
                self.boundary.centre_datetime,
                self.boundary.end,
Joseph Siddons's avatar
Joseph Siddons committed
531 532 533 534 535 536 537
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.northwestback = OctTree(
            SpaceTimeRectangle(
538 539 540 541 542 543
                self.boundary.west,
                self.boundary.lon,
                self.boundary.lat,
                self.boundary.north,
                self.boundary.start,
                self.boundary.centre_datetime,
Joseph Siddons's avatar
Joseph Siddons committed
544 545 546 547 548 549 550
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.northeastback = OctTree(
            SpaceTimeRectangle(
551 552 553 554 555 556
                self.boundary.lon,
                self.boundary.east,
                self.boundary.lat,
                self.boundary.north,
                self.boundary.start,
                self.boundary.centre_datetime,
Joseph Siddons's avatar
Joseph Siddons committed
557 558 559 560 561 562 563
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.southwestback = OctTree(
            SpaceTimeRectangle(
564 565 566 567 568 569
                self.boundary.west,
                self.boundary.lon,
                self.boundary.south,
                self.boundary.lat,
                self.boundary.start,
                self.boundary.centre_datetime,
Joseph Siddons's avatar
Joseph Siddons committed
570 571 572 573 574 575 576
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.southeastback = OctTree(
            SpaceTimeRectangle(
577 578 579 580 581 582
                self.boundary.lon,
                self.boundary.east,
                self.boundary.south,
                self.boundary.lat,
                self.boundary.start,
                self.boundary.centre_datetime,
Joseph Siddons's avatar
Joseph Siddons committed
583 584 585 586 587 588 589
            ),
            capacity=self.capacity,
            depth=self.depth + 1,
            max_depth=self.max_depth,
        )
        self.divided = True

590
    def insert(self, point: SpaceTimeRecord) -> bool:  # noqa: C901
Joseph Siddons's avatar
Joseph Siddons committed
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
        """
        Insert a SpaceTimeRecord into the QuadTree.

        Note that the SpaceTimeRecord can have numeric datetime values if that
        is consistent with the OctTree.
        """
        if not self.boundary.contains(point):
            return False
        elif self.max_depth and self.depth == self.max_depth:
            self.points.append(point)
            return True
        elif len(self.points) < self.capacity:
            self.points.append(point)
            return True
        else:
            if not self.divided:
                self.divide()
            if self.northwestback.insert(point):
                return True
            elif self.northeastback.insert(point):
                return True
            elif self.southwestback.insert(point):
                return True
            elif self.southeastback.insert(point):
                return True
            elif self.northwestfwd.insert(point):
                return True
            elif self.northeastfwd.insert(point):
                return True
            elif self.southwestfwd.insert(point):
                return True
            elif self.southeastfwd.insert(point):
                return True
            return False

626
    def remove(self, point: SpaceTimeRecord) -> bool:  # noqa: C901
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
        """
        Remove a SpaceTimeRecord from the OctTree if it is in the OctTree.

        Returns True if the SpaceTimeRecord is removed.
        """
        if not self.boundary.contains(point):
            return False

        if point in self.points:
            self.points.remove(point)
            return True

        if not self.divided:
            return False

        if self.northwestback.remove(point):
            return True
        elif self.northeastback.remove(point):
            return True
        elif self.southwestback.remove(point):
            return True
        elif self.southeastback.remove(point):
            return True
        elif self.northwestfwd.remove(point):
            return True
        elif self.northeastfwd.remove(point):
            return True
        elif self.southwestfwd.remove(point):
            return True
        elif self.southeastfwd.remove(point):
            return True

        return False

Joseph Siddons's avatar
Joseph Siddons committed
661 662 663
    def query(
        self,
        rect: SpaceTimeRectangle,
664
        points: Optional[SpaceTimeRecords] = None,
Joseph Siddons's avatar
Joseph Siddons committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    ) -> SpaceTimeRecords:
        """Get points that fall in a SpaceTimeRectangle"""
        if not points:
            points = SpaceTimeRecords()
        if not self.boundary.intersects(rect):
            return points

        for point in self.points:
            if rect.contains(point):
                points.append(point)

        if self.divided:
            points = self.northwestfwd.query(rect, points)
            points = self.northeastfwd.query(rect, points)
            points = self.southwestfwd.query(rect, points)
            points = self.southeastfwd.query(rect, points)
            points = self.northwestback.query(rect, points)
            points = self.northeastback.query(rect, points)
            points = self.southwestback.query(rect, points)
            points = self.southeastback.query(rect, points)

        return points

688 689 690
    def query_ellipse(
        self,
        ellipse: SpaceTimeEllipse,
691
        points: Optional[SpaceTimeRecords] = None,
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    ) -> SpaceTimeRecords:
        """Get points that fall in an ellipse."""
        if not points:
            points = SpaceTimeRecords()
        if not ellipse.nearby_rect(self.boundary):
            return points

        for point in self.points:
            if ellipse.contains(point):
                points.append(point)

        if self.divided:
            points = self.northwestfwd.query_ellipse(ellipse, points)
            points = self.northeastfwd.query_ellipse(ellipse, points)
            points = self.southwestfwd.query_ellipse(ellipse, points)
            points = self.southeastfwd.query_ellipse(ellipse, points)
            points = self.northwestback.query_ellipse(ellipse, points)
            points = self.northeastback.query_ellipse(ellipse, points)
            points = self.southwestback.query_ellipse(ellipse, points)
            points = self.southeastback.query_ellipse(ellipse, points)

        return points

Joseph Siddons's avatar
Joseph Siddons committed
715 716 717 718
    def nearby_points(
        self,
        point: SpaceTimeRecord,
        dist: float,
719
        t_dist: datetime.timedelta,
720
        points: Optional[SpaceTimeRecords] = None,
Joseph Siddons's avatar
Joseph Siddons committed
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    ) -> SpaceTimeRecords:
        """
        Get all points that are nearby another point.

        Query the OctTree to find all SpaceTimeRecords within the OctTree that
        are nearby to the query SpaceTimeRecord. This search should be faster
        than searching through all records, since only OctTree children whose
        boundaries are close to the query SpaceTimeRecord are evaluated.

        Parameters
        ----------
        point : SpaceTimeRecord
            The query point.
        dist : float
            The distance for comparison. Note that Haversine distance is used
            as the distance metric as the query SpaceTimeRecord and OctTree are
            assumed to lie on the surface of Earth.
738
        t_dist : datetime.timedelta
Joseph Siddons's avatar
Joseph Siddons committed
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
            Max time gap between SpaceTimeRecords within the OctTree and the
            query SpaceTimeRecord. Can be numeric if the OctTree boundaries,
            SpaceTimeRecords, and query SpaceTimeRecord have numeric datetime
            values and ranges.
        points : SpaceTimeRecords | None
            List of SpaceTimeRecords already found. Most use cases will be to
            not set this value, since it's main use is for passing onto the
            children OctTrees.

        Returns
        -------
        SpaceTimeRecords : A list of SpaceTimeRecords whose distance to the
        query SpaceTimeRecord is <= dist, and the datetimes of the
        SpaceTimeRecords fall within the datetime range of the query
        SpaceTimeRecord.
        """
        if not points:
            points = SpaceTimeRecords()
        if not self.boundary.nearby(point, dist, t_dist):
            return points

        for test_point in self.points:
            if (
                haversine(point.lon, point.lat, test_point.lon, test_point.lat)
                <= dist
                and test_point.datetime <= point.datetime + t_dist
                and test_point.datetime >= point.datetime - t_dist
            ):
                points.append(test_point)

        if self.divided:
            points = self.northwestback.nearby_points(
                point, dist, t_dist, points
            )
            points = self.northeastback.nearby_points(
                point, dist, t_dist, points
            )
            points = self.southwestback.nearby_points(
                point, dist, t_dist, points
            )
            points = self.southeastback.nearby_points(
                point, dist, t_dist, points
            )
            points = self.northwestfwd.nearby_points(
                point, dist, t_dist, points
            )
            points = self.northeastfwd.nearby_points(
                point, dist, t_dist, points
            )
            points = self.southwestfwd.nearby_points(
                point, dist, t_dist, points
            )
            points = self.southeastfwd.nearby_points(
                point, dist, t_dist, points
            )

        return points