Skip to content

Matchup — geocatalog.matchup

Cross-source row joins with pluggable spatial and temporal strategies.

Matchup

geocatalog.matchup.matchup(primary, secondary, *, spatial, temporal, join='all', tag=None, crs=None, include_self=False)

Find matching tuples of observations.

Parameters:

Name Type Description Default
primary GeoCatalog | CatalogBundle | Iterable[SourceRow]

Primary observations — a GeoCatalog, a CatalogBundle (its items) or an iterable of SourceRow. Read lazily; each row is processed once, in input order.

required
secondary GeoCatalog | CatalogBundle | Iterable[SourceRow] | Mapping[str, GeoCatalog | CatalogBundle | Iterable[SourceRow]]

One input of the same kinds (pairwise — every member gets the role "secondary") or a mapping of role → input (N-way — each role indexed independently). Secondaries are read in full before the first row is yielded. "primary" is reserved and cannot be a role.

required
spatial SpatialStrategy

Strategy deciding spatial matches (e.g. Intersects(), IouAtLeast(0.2)).

required
temporal TemporalStrategy

Strategy deciding temporal matches (e.g. NearestInTime(dt="6h")). Shipped strategies select candidates by position; a custom strategy that only implements filter must return intervals from the candidates it was given.

required
join Literal['all', 'any']

"all" (default) requires every secondary role to contribute a member; primaries with any empty role are skipped. "any" emits matchups missing some roles — handy for opportunistic fusion.

'all'
tag str | None

Optional user label persisted as query_set, so the set can be selected from matchups.parquet later.

None
crs Any

Working CRS for the join; every footprint is reprojected into it and geometry_intersect is expressed in it. Defaults to the primary catalog's CRS, or EPSG:4326 when the primary is an iterable of SourceRow (whose footprints are lon/lat). Distances such as CentroidWithin.buffer are in its units, so pass a projected CRS (metres) for a distance in metres — or for footprints split at the antimeridian, which a local projection rejoins.

None
include_self bool

Keep tuples that pair a row with itself (same (source, collection, id)), e.g. when matching a catalog against itself. Off by default.

False

Yields:

Type Description
MatchupRow

MatchupRow instances, one per matched tuple, in primary

MatchupRow

input order and then by (source, collection, id) of the secondaries.

MatchupRow

Duplicate tuples are emitted once. Rows whose interval is

MatchupRow

missing (NaT) never match.

Raises:

Type Description
ValueError

If a secondary role is named "primary", the role mapping is empty, or join is unknown.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/engine.py
def matchup(
    primary: GeoCatalog | CatalogBundle | Iterable[SourceRow],
    secondary: GeoCatalog
    | CatalogBundle
    | Iterable[SourceRow]
    | Mapping[str, GeoCatalog | CatalogBundle | Iterable[SourceRow]],
    *,
    spatial: SpatialStrategy,
    temporal: TemporalStrategy,
    join: Literal["all", "any"] = "all",
    tag: str | None = None,
    crs: Any = None,
    include_self: bool = False,
) -> Iterator[MatchupRow]:
    """Find matching tuples of observations.

    Args:
        primary: Primary observations — a `GeoCatalog`, a
            `CatalogBundle` (its items) or an iterable of `SourceRow`.
            Read lazily; each row is processed once, in input order.
        secondary: One input of the same kinds (pairwise — every
            member gets the role ``"secondary"``) or a mapping of
            role → input (N-way — each role indexed independently).
            Secondaries are read in full before the first row is
            yielded. ``"primary"`` is reserved and cannot be a role.
        spatial: Strategy deciding spatial matches
            (e.g. ``Intersects()``, ``IouAtLeast(0.2)``).
        temporal: Strategy deciding temporal matches
            (e.g. ``NearestInTime(dt="6h")``). Shipped strategies
            select candidates by position; a custom strategy that
            only implements ``filter`` must return intervals from the
            candidates it was given.
        join: ``"all"`` (default) requires every secondary role to
            contribute a member; primaries with any empty role are
            skipped. ``"any"`` emits matchups missing some roles —
            handy for opportunistic fusion.
        tag: Optional user label persisted as ``query_set``, so the
            set can be selected from ``matchups.parquet`` later.
        crs: Working CRS for the join; every footprint is reprojected
            into it and ``geometry_intersect`` is expressed in it.
            Defaults to the primary catalog's CRS, or EPSG:4326 when
            the primary is an iterable of `SourceRow` (whose
            footprints are lon/lat). Distances such as
            ``CentroidWithin.buffer`` are in its units, so pass a
            projected CRS (metres) for a distance in metres — or for
            footprints split at the antimeridian, which a local
            projection rejoins.
        include_self: Keep tuples that pair a row with itself (same
            ``(source, collection, id)``), e.g. when matching a catalog against
            itself. Off by default.

    Yields:
        `MatchupRow` instances, one per matched tuple, in primary
        input order and then by ``(source, collection, id)`` of the secondaries.
        Duplicate tuples are emitted once. Rows whose interval is
        missing (``NaT``) never match.

    Raises:
        ValueError: If a secondary role is named ``"primary"``, the
            role mapping is empty, or ``join`` is unknown.
    """
    import pyproj
    from shapely.strtree import STRtree

    from geocatalog._src.matchup.spatial import CentroidWithin, search_envelope

    if join not in ("all", "any"):
        raise ValueError(f"join must be 'all' or 'any'; got {join!r}")
    secondaries = (
        dict(secondary) if isinstance(secondary, Mapping) else {"secondary": secondary}
    )
    if not secondaries:
        raise ValueError("secondary mapping has no roles")
    if PRIMARY_ROLE in secondaries:
        raise ValueError(
            f"{PRIMARY_ROLE!r} is the primary's role; name the secondary role "
            "something else"
        )

    primary = _unwrap_bundle(primary)
    work_crs = pyproj.CRS.from_user_input(
        crs if crs is not None else _native_crs(primary) or "EPSG:4326"
    )
    if (
        isinstance(spatial, CentroidWithin)
        and isinstance(spatial.buffer, int | float)
        and spatial.buffer > 0
        and work_crs.is_geographic
    ):
        warnings.warn(
            f"CentroidWithin(buffer={spatial.buffer}) is in degrees: the "
            f"working CRS {work_crs.to_string()} is geographic. Pass `crs=` "
            "a projected CRS for a buffer in metres.",
            UserWarning,
            stacklevel=2,
        )

    roles: dict[str, list[_Member]] = {}
    for role, rows in secondaries.items():
        members = _dedup(_members(rows, work_crs))
        roles[role] = sorted(members, key=lambda m: m.key)
    trees = {
        role: STRtree([m.geometry for m in members]) for role, members in roles.items()
    }

    strategy_label = f"{_summary(spatial)} & {_summary(temporal)}"
    tolerance = {
        "spatial": _params(spatial),
        "temporal": _params(temporal),
        "join": join,
        # `to_string()`, not `crs_config_string`: this feeds every
        # persisted `MatchupRow` id, so changing the serialisation would
        # re-key existing bundles and `write_matchups` would append
        # duplicates instead of replacing rows.
        "crs": work_crs.to_string(),
    }
    strategy_key = json.dumps(tolerance, sort_keys=True)

    seen: set[str] = set()
    for p in _members(primary, work_crs):
        survivors: dict[str, list[_Member]] = {}
        envelope = search_envelope(spatial, p.geometry)
        for role, members in roles.items():
            candidates = [
                members[i]
                for i in sorted(int(i) for i in trees[role].query(envelope))
                if include_self or members[i].key != p.key
            ]
            survivors[role] = [
                c
                for c in _select_in_time(temporal, p, candidates)
                if spatial.match(p.geometry, c.geometry)
            ]

        if join == "all" and not all(survivors.values()):
            continue
        # Under "any", an empty role contributes a "no match" slot.
        role_names = list(survivors)
        slots = [survivors[r] or [None] for r in role_names]
        for combo in product(*slots):
            members_out = [p]
            roles_out = [PRIMARY_ROLE]
            for role, member in zip(role_names, combo, strict=True):
                if member is not None:
                    members_out.append(member)
                    roles_out.append(role)
            if len(members_out) == 1:
                continue  # a primary-only "matchup" is meaningless
            keys = [m.key for m in members_out]
            if not include_self and len(set(keys)) < len(keys):
                continue  # one row in two roles
            matchup_id = _matchup_id(strategy_key, roles_out, keys)
            if matchup_id in seen:
                continue
            seen.add(matchup_id)
            reference = _midpoint(p.interval)
            yield MatchupRow(
                matchup_id=matchup_id,
                strategy=strategy_label,
                member_ids=tuple(m.id for m in members_out),
                member_sources=tuple(m.source for m in members_out),
                member_collections=tuple(m.collection for m in members_out),
                member_roles=tuple(roles_out),
                geometry_intersect=_common_intersection(
                    [m.geometry for m in members_out]
                ),
                time_reference=reference.to_pydatetime(),
                time_offset_sec=tuple(
                    (_midpoint(m.interval) - reference).total_seconds()
                    for m in members_out
                ),
                tolerance=tolerance,
                query_set=tag,
            )

geocatalog.matchup.MatchupRow dataclass

A single matched tuple, persisted to matchups.parquet.

Attributes:

Name Type Description
matchup_id str

Content hash (32 hex characters) of the strategy parameters and the members' (role, source, id); the same inputs and strategies always give the same id.

strategy str

Human-readable label naming the spatial and temporal strategies used ("IouAtLeast(threshold=0.2) & NearestInTime(dt='6h')").

member_ids tuple[str, ...]

Parallel arrays with member_sources and member_roles. member_ids[0] is always the primary.

member_sources tuple[str, ...]

Source of each member — SourceRow.source, or a catalog row's source column ("catalog" when it has none).

member_roles tuple[str, ...]

Role tags — "primary", "secondary", or user-defined names for N-way matchups.

geometry_intersect BaseGeometry

Common footprint of the members, in the matchup's working CRS (tolerance["crs"]).

time_reference datetime

Reference instant the offsets are measured from — the primary's interval midpoint, UTC-aware.

time_offset_sec tuple[float, ...]

Parallel to member_ids; offset of each member's interval midpoint from time_reference.

tolerance Mapping[str, Any]

Strategy parameters as plain JSON values — {"spatial": {"type": ..., ...}, "temporal": {"type": ..., "<field>_sec": ...}, "join": ..., "crs": ...}; durations are seconds, distances are in units of crs.

member_collections tuple[str, ...]

Parallel to member_ids; each member's collection (SourceRow.collection, or a catalog row's collection column, "" when it has none). Together with member_sources and member_ids it identifies the bundle item a member refers to. Empty for rows written before it was recorded.

query_set str | None

Optional user label, persisted as the query_set column in matchups.parquet so a named set can be selected later (bundle.matchups_df filtered on query_set). Mirrors the tag argument of matchup().

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/engine.py
@dataclasses.dataclass(frozen=True)
class MatchupRow:
    """A single matched tuple, persisted to ``matchups.parquet``.

    Attributes:
        matchup_id: Content hash (32 hex characters) of the strategy
            parameters and the members' ``(role, source, id)``; the
            same inputs and strategies always give the same id.
        strategy: Human-readable label naming the spatial and
            temporal strategies used
            (``"IouAtLeast(threshold=0.2) & NearestInTime(dt='6h')"``).
        member_ids: Parallel arrays with ``member_sources`` and
            ``member_roles``. ``member_ids[0]`` is always the primary.
        member_sources: Source of each member — ``SourceRow.source``,
            or a catalog row's ``source`` column (``"catalog"`` when
            it has none).
        member_roles: Role tags — ``"primary"``, ``"secondary"``, or
            user-defined names for N-way matchups.
        geometry_intersect: Common footprint of the members, in the
            matchup's working CRS (``tolerance["crs"]``).
        time_reference: Reference instant the offsets are measured
            from — the primary's interval midpoint, UTC-aware.
        time_offset_sec: Parallel to ``member_ids``; offset of each
            member's interval midpoint from ``time_reference``.
        tolerance: Strategy parameters as plain JSON values —
            ``{"spatial": {"type": ..., ...}, "temporal": {"type": ...,
            "<field>_sec": ...}, "join": ..., "crs": ...}``; durations
            are seconds, distances are in units of ``crs``.
        member_collections: Parallel to ``member_ids``; each member's
            collection (``SourceRow.collection``, or a catalog row's
            ``collection`` column, ``""`` when it has none). Together
            with ``member_sources`` and ``member_ids`` it identifies the
            bundle item a member refers to. Empty for rows written
            before it was recorded.
        query_set: Optional user label, persisted as the
            ``query_set`` column in ``matchups.parquet`` so a named
            set can be selected later (``bundle.matchups_df`` filtered
            on ``query_set``). Mirrors the ``tag`` argument of
            `matchup()`.
    """

    matchup_id: str
    strategy: str
    member_ids: tuple[str, ...]
    member_sources: tuple[str, ...]
    member_roles: tuple[str, ...]
    geometry_intersect: shapely.geometry.base.BaseGeometry
    time_reference: datetime
    time_offset_sec: tuple[float, ...]
    tolerance: Mapping[str, Any] = dataclasses.field(default_factory=dict)
    query_set: str | None = None
    member_collections: tuple[str, ...] = ()

Spatial strategies

geocatalog.matchup.SpatialStrategy

Bases: Protocol

A predicate over two footprints.

The engine calls match(primary, secondary) for each candidate pair after the STRtree pre-filter narrows by envelope overlap.

The pre-filter searches the primary footprint itself. A strategy that can accept secondaries outside it (a buffered test, say) defines envelope(primary) returning the region to search; the engine uses it when present (see search_envelope).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/spatial.py
@runtime_checkable
class SpatialStrategy(Protocol):
    """A predicate over two footprints.

    The engine calls ``match(primary, secondary)`` for each candidate
    pair after the STRtree pre-filter narrows by envelope overlap.

    The pre-filter searches the primary footprint itself. A strategy
    that can accept secondaries *outside* it (a buffered test, say)
    defines ``envelope(primary)`` returning the region to search; the
    engine uses it when present (see `search_envelope`).
    """

    def match(
        self,
        primary: shapely.geometry.base.BaseGeometry,
        secondary: shapely.geometry.base.BaseGeometry,
    ) -> bool: ...

geocatalog.matchup.Intersects dataclass

Non-zero geometric intersection (the cheapest predicate).

Matches any pair whose footprints share at least one point. Use when the matchup definition is "any overlap counts" — a common choice for opportunistic fusion where partial coverage is still useful.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/spatial.py
@dataclasses.dataclass(frozen=True)
class Intersects:
    """Non-zero geometric intersection (the cheapest predicate).

    Matches any pair whose footprints share at least one point.
    Use when the matchup definition is "any overlap counts" — a
    common choice for opportunistic fusion where partial coverage
    is still useful.
    """

    def match(
        self,
        primary: shapely.geometry.base.BaseGeometry,
        secondary: shapely.geometry.base.BaseGeometry,
    ) -> bool:
        return primary.intersects(secondary)

geocatalog.matchup.IouAtLeast dataclass

Intersection-over-union ≥ threshold.

Stricter than plain intersection — useful when you want the secondary to substantially overlap the primary (e.g. for training-data quality gates where a sliver-overlap is noise).

Parameters:

Name Type Description Default
threshold float

Minimum IoU in [0, 1].

required
Notes

IoU on raw geographic CRS coordinates is degree-area, which is fine as a ratio (numerator and denominator scale the same way) but loses meaning if you compare across latitudes. For equal-area comparisons project both inputs to a meter CRS first.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/spatial.py
@dataclasses.dataclass(frozen=True)
class IouAtLeast:
    """Intersection-over-union ≥ ``threshold``.

    Stricter than plain intersection — useful when you want the
    secondary to *substantially* overlap the primary (e.g. for
    training-data quality gates where a sliver-overlap is noise).

    Args:
        threshold: Minimum IoU in ``[0, 1]``.

    Notes:
        IoU on raw geographic CRS coordinates is degree-area, which
        is fine as a ratio (numerator and denominator scale the same
        way) but loses meaning if you compare across latitudes. For
        equal-area comparisons project both inputs to a meter CRS
        first.
    """

    threshold: float

    def __post_init__(self) -> None:
        if not 0.0 <= self.threshold <= 1.0:
            raise ValueError(
                f"IouAtLeast.threshold must be in [0, 1]; got {self.threshold!r}"
            )

    def match(
        self,
        primary: shapely.geometry.base.BaseGeometry,
        secondary: shapely.geometry.base.BaseGeometry,
    ) -> bool:
        intersection = primary.intersection(secondary)
        if intersection.is_empty:
            return False
        union = primary.union(secondary)
        if union.area == 0.0:
            # Degenerate: both are zero-area (e.g. two points or
            # crossing LineStrings). Area-based IoU is undefined
            # for these — treat them as "matching" only if the
            # geometries are equal, otherwise fail rather than
            # silently ignoring the threshold.
            return primary.equals(secondary)
        return (intersection.area / union.area) >= self.threshold

geocatalog.matchup.CentroidWithin dataclass

Secondary centroid falls within a buffered primary footprint.

Useful when matching against point-like secondaries (in-situ stations, drifters) where a buffered-polygon test is more forgiving than strict polygon containment.

Parameters:

Name Type Description Default
buffer float | str

Distance (in the geometry's CRS units) by which the primary footprint is enlarged before the point-in-polygon test. 0.0 = strict centroid-in-polygon; larger values tolerate near-misses. String-with-units forms (e.g. "5km") are reserved for a future revision — for now use floats and reproject upfront if needed.

required
Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/spatial.py
@dataclasses.dataclass(frozen=True)
class CentroidWithin:
    """Secondary centroid falls within a buffered primary footprint.

    Useful when matching against point-like secondaries (in-situ
    stations, drifters) where a buffered-polygon test is more
    forgiving than strict polygon containment.

    Args:
        buffer: Distance (in the geometry's CRS units) by which the
            primary footprint is enlarged before the point-in-polygon
            test. ``0.0`` = strict centroid-in-polygon; larger values
            tolerate near-misses. String-with-units forms
            (e.g. ``"5km"``) are reserved for a future revision —
            for now use floats and reproject upfront if needed.
    """

    buffer: float | str

    def match(
        self,
        primary: shapely.geometry.base.BaseGeometry,
        secondary: shapely.geometry.base.BaseGeometry,
    ) -> bool:
        return self.envelope(primary).contains(secondary.centroid)

    def envelope(
        self, primary: shapely.geometry.base.BaseGeometry
    ) -> shapely.geometry.base.BaseGeometry:
        """The buffered primary: every centroid ``match`` can accept lies in it."""
        if isinstance(self.buffer, str):
            raise NotImplementedError(
                "String-with-units buffer (e.g. '5km') is not yet "
                "supported. Pass a float in CRS units, or reproject "
                "the inputs into a meter-based CRS upfront."
            )
        return primary.buffer(self.buffer) if self.buffer > 0 else primary

envelope(primary)

The buffered primary: every centroid match can accept lies in it.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/spatial.py
def envelope(
    self, primary: shapely.geometry.base.BaseGeometry
) -> shapely.geometry.base.BaseGeometry:
    """The buffered primary: every centroid ``match`` can accept lies in it."""
    if isinstance(self.buffer, str):
        raise NotImplementedError(
            "String-with-units buffer (e.g. '5km') is not yet "
            "supported. Pass a float in CRS units, or reproject "
            "the inputs into a meter-based CRS upfront."
        )
    return primary.buffer(self.buffer) if self.buffer > 0 else primary

geocatalog.matchup.Contains dataclass

Secondary footprint is fully contained in the primary.

The strictest spatial predicate — use when you need the secondary to be a true subset of the primary's footprint (e.g. a station tile inside an L2 swath).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/spatial.py
@dataclasses.dataclass(frozen=True)
class Contains:
    """Secondary footprint is fully contained in the primary.

    The strictest spatial predicate — use when you need the
    secondary to be a true subset of the primary's footprint
    (e.g. a station tile inside an L2 swath).
    """

    def match(
        self,
        primary: shapely.geometry.base.BaseGeometry,
        secondary: shapely.geometry.base.BaseGeometry,
    ) -> bool:
        return primary.contains(secondary)

Temporal strategies

geocatalog.matchup.TemporalStrategy

Bases: Protocol

Selector over candidate intervals.

Concrete strategies are either predicates (Synchronous, WithinWindow — emit every candidate that satisfies the condition) or selectors (NearestInTime — emit at most the single best). The engine treats both uniformly via filter.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
@runtime_checkable
class TemporalStrategy(Protocol):
    """Selector over candidate intervals.

    Concrete strategies are either *predicates* (Synchronous,
    WithinWindow — emit every candidate that satisfies the
    condition) or *selectors* (NearestInTime — emit at most the
    single best). The engine treats both uniformly via ``filter``.
    """

    def filter(
        self,
        primary: pd.Interval,
        candidates: pd.IntervalIndex,
    ) -> pd.IntervalIndex:
        """Return the subset of candidates that match the primary."""
        ...

filter(primary, candidates)

Return the subset of candidates that match the primary.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
def filter(
    self,
    primary: pd.Interval,
    candidates: pd.IntervalIndex,
) -> pd.IntervalIndex:
    """Return the subset of candidates that match the primary."""
    ...

geocatalog.matchup.NearestInTime dataclass

Pick the secondary nearest in time within dt.

"Nearest" is measured between interval midpoints. If the nearest is still further than dt away, the result is empty.

Parameters:

Name Type Description Default
dt timedelta | str

Maximum allowed time offset, e.g. timedelta(hours=6) or "6h" (parsed via pd.Timedelta).

required
Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
@dataclasses.dataclass(frozen=True)
class NearestInTime:
    """Pick the secondary nearest in time within ``dt``.

    "Nearest" is measured between interval midpoints. If the
    nearest is still further than ``dt`` away, the result is empty.

    Args:
        dt: Maximum allowed time offset, e.g. ``timedelta(hours=6)``
            or ``"6h"`` (parsed via `pd.Timedelta`).
    """

    dt: timedelta | str

    def filter(
        self,
        primary: pd.Interval,
        candidates: pd.IntervalIndex,
    ) -> pd.IntervalIndex:
        return _by_positions(candidates, self.select(primary, candidates))

    def select(self, primary: pd.Interval, candidates: pd.IntervalIndex) -> list[int]:
        """Position of the nearest candidate within ``dt``; ties → first."""
        dt_limit = _to_timedelta(self.dt)
        primary_mid = _midpoint(primary)
        best: tuple[pd.Timedelta, int] | None = None
        for i, iv in _present(candidates):
            delta = abs(_midpoint(iv) - primary_mid)
            # Strict `<` keeps the first of equally near candidates; the
            # engine orders candidates stably, so the choice is
            # deterministic.
            if delta <= dt_limit and (best is None or delta < best[0]):
                best = (delta, i)
        return [] if best is None else [best[1]]

select(primary, candidates)

Position of the nearest candidate within dt; ties → first.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
def select(self, primary: pd.Interval, candidates: pd.IntervalIndex) -> list[int]:
    """Position of the nearest candidate within ``dt``; ties → first."""
    dt_limit = _to_timedelta(self.dt)
    primary_mid = _midpoint(primary)
    best: tuple[pd.Timedelta, int] | None = None
    for i, iv in _present(candidates):
        delta = abs(_midpoint(iv) - primary_mid)
        # Strict `<` keeps the first of equally near candidates; the
        # engine orders candidates stably, so the choice is
        # deterministic.
        if delta <= dt_limit and (best is None or delta < best[0]):
            best = (delta, i)
    return [] if best is None else [best[1]]

geocatalog.matchup.WithinWindow dataclass

Candidates whose midpoint falls in [primary.mid + start, primary.mid + end].

Useful for "give me everything within ±12 h of each primary". start is typically negative (look back); end positive (look forward).

Parameters:

Name Type Description Default
start timedelta | str

Offset from the primary midpoint. Negative looks back.

required
end timedelta | str

Offset from the primary midpoint. Positive looks forward.

required
Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
@dataclasses.dataclass(frozen=True)
class WithinWindow:
    """Candidates whose midpoint falls in ``[primary.mid + start, primary.mid + end]``.

    Useful for "give me everything within ±12 h of each primary".
    ``start`` is typically negative (look back); ``end`` positive
    (look forward).

    Args:
        start: Offset from the primary midpoint. Negative looks back.
        end: Offset from the primary midpoint. Positive looks forward.
    """

    start: timedelta | str
    end: timedelta | str

    def filter(
        self,
        primary: pd.Interval,
        candidates: pd.IntervalIndex,
    ) -> pd.IntervalIndex:
        return _by_positions(candidates, self.select(primary, candidates))

    def select(self, primary: pd.Interval, candidates: pd.IntervalIndex) -> list[int]:
        """Positions of the candidates whose midpoint is in the window."""
        primary_mid = _midpoint(primary)
        lower = primary_mid + _to_timedelta(self.start)
        upper = primary_mid + _to_timedelta(self.end)
        return [i for i, iv in _present(candidates) if lower <= _midpoint(iv) <= upper]

select(primary, candidates)

Positions of the candidates whose midpoint is in the window.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
def select(self, primary: pd.Interval, candidates: pd.IntervalIndex) -> list[int]:
    """Positions of the candidates whose midpoint is in the window."""
    primary_mid = _midpoint(primary)
    lower = primary_mid + _to_timedelta(self.start)
    upper = primary_mid + _to_timedelta(self.end)
    return [i for i, iv in _present(candidates) if lower <= _midpoint(iv) <= upper]

geocatalog.matchup.Synchronous dataclass

Candidates whose intervals overlap the primary's, within tolerance.

Equivalent to WithinWindow(start=-tolerance, end=+tolerance) applied to interval overlap (not midpoints) — useful for matching observations that should genuinely co-occur in time (e.g. simultaneous flyovers).

Parameters:

Name Type Description Default
tolerance timedelta | str

Slack on either side of the primary interval. "0s" (default) enforces strict overlap.

'0s'
Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
@dataclasses.dataclass(frozen=True)
class Synchronous:
    """Candidates whose intervals overlap the primary's, within tolerance.

    Equivalent to `WithinWindow(start=-tolerance, end=+tolerance)`
    applied to interval overlap (not midpoints) — useful for
    matching observations that should genuinely co-occur in time
    (e.g. simultaneous flyovers).

    Args:
        tolerance: Slack on either side of the primary interval.
            ``"0s"`` (default) enforces strict overlap.
    """

    tolerance: timedelta | str = "0s"

    def filter(
        self,
        primary: pd.Interval,
        candidates: pd.IntervalIndex,
    ) -> pd.IntervalIndex:
        return _by_positions(candidates, self.select(primary, candidates))

    def select(self, primary: pd.Interval, candidates: pd.IntervalIndex) -> list[int]:
        """Positions of the candidates overlapping the widened primary."""
        import pandas as pd

        from geocatalog._src.utils.timeutil import to_utc_ts

        tol = _to_timedelta(self.tolerance)
        primary_left = to_utc_ts(pd.Timestamp(primary.left)) - tol
        primary_right = to_utc_ts(pd.Timestamp(primary.right)) + tol
        positions = []
        for i, iv in _present(candidates):
            cand_left = to_utc_ts(pd.Timestamp(iv.left))
            cand_right = to_utc_ts(pd.Timestamp(iv.right))
            # Intervals overlap iff each starts before the other ends.
            if cand_left <= primary_right and cand_right >= primary_left:
                positions.append(i)
        return positions

select(primary, candidates)

Positions of the candidates overlapping the widened primary.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/matchup/temporal.py
def select(self, primary: pd.Interval, candidates: pd.IntervalIndex) -> list[int]:
    """Positions of the candidates overlapping the widened primary."""
    import pandas as pd

    from geocatalog._src.utils.timeutil import to_utc_ts

    tol = _to_timedelta(self.tolerance)
    primary_left = to_utc_ts(pd.Timestamp(primary.left)) - tol
    primary_right = to_utc_ts(pd.Timestamp(primary.right)) + tol
    positions = []
    for i, iv in _present(candidates):
        cand_left = to_utc_ts(pd.Timestamp(iv.left))
        cand_right = to_utc_ts(pd.Timestamp(iv.right))
        # Intervals overlap iff each starts before the other ends.
        if cand_left <= primary_right and cand_right >= primary_left:
            positions.append(i)
    return positions