Skip to content

coverage_reservations

coverage_reservations #

Per-user location reservations — spread a crowd across a survey area.

The spatial sibling of ReservationBook: each user leases a place out of a batch, and a place is retired once a capture lands within threshold of it. area_batch draws a batch from a survey area: the places farthest from every capture so far.

DEFAULT_LEASE = timedelta(minutes=30) module-attribute #

How long a handout is held before, absent a covering capture, it recycles.

CoverageBook #

Bases: ImpureState

The persistent book of location leases.

batch holds the un-handed-out survey locations; held maps each user to their [Lease][]. The struct IS the format: changing its shape starts a fresh book (no migration).

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/organize/coverage_reservations.py
class CoverageBook(cg.ImpureState):
    """The persistent book of location leases.

    ``batch`` holds the un-handed-out survey locations; ``held`` maps each user
    to their [Lease][]. The struct IS the format: changing its shape starts a
    fresh book (no migration).
    """

    batch: cg.Array[cg.Location]
    held: cg.Map[cg.UserID, Lease]

    def reserve(
        self,
        user_id: str,
        *,
        distance: Callable[[cg.Location, cg.Location], float],
        at: cg.Location | None = None,
        fulfilled_by: Iterable[cg.Location | cg.MissingType | None] = (),
        threshold: float = 1.0,
        lease: timedelta = DEFAULT_LEASE,
        refill: Iterable[cg.Location] | None = None,
        now: datetime | None = None,
    ) -> cg.Location | None:
        """The location this user holds, leasing one from the batch if none.

        ```python
        @cgserver.intercept(Survey, lambda s: s._metadata._location)
        def next_spot(profile: cgserver.RequestProfile, target: Survey) -> cg.Location | None:
            covered = target.sessions.values().location
            return cgr.scheduling.CoverageBook.open("survey").reserve(
                profile.user_id,
                at=profile.location,
                fulfilled_by=covered,
                distance=cgr.scheduling.distance.location(sigma_m=10.0),
                refill=cgr.scheduling.area_batch(BOUNDARY, covered),
            )
        ```

        Args:
            user_id: The user asking for a location.
            distance: A distance between two ``cg.Location``s — the same metric used
                to select the batch (``cgr.scheduling.distance.location(sigma_m=...)``). It
                both picks the location closest to a requester and decides when a
                capture covers a reservation.
            at: The requester's current location, if known. The batch location
                closest to it is leased; without it, the batch is leased in
                insertion order (FIFO).
            fulfilled_by: Captured locations; a reservation or batch location within
                ``threshold`` of any of these is retired first, so a covered spot is
                never offered. An absent entry (``None`` or ``Missing``) is skipped.
            threshold: A reservation is released once a capture lies within this
                distance of it, in the units ``distance`` returns. Defaults to
                ``1.0``.
            lease: How long a handout is held before, absent a covering capture, the
                location returns to the batch. Defaults to 30 minutes.
            refill: Locations to install as the batch **when it is exhausted**,
                such as ``area_batch(boundary, covered)``. Ignored while the batch
                still has locations to hand out.
            now: The reference time; defaults to ``datetime.now()``. Pass it
                explicitly to make lease expiry deterministic under test.

        Returns:
            The user's reserved location, or ``None`` if the batch is exhausted
            and the user holds nothing.
        """
        now = now if now is not None else datetime.now(UTC)
        captures = [capture for capture in fulfilled_by if isinstance(capture, cg.Location)]
        held = _retire_covered(_held(self), captures, distance=distance, threshold=threshold)
        held, offered = _reclaim_lapsed(held, _batch(self), now=now)
        offered = _uncovered(offered, captures, distance=distance, threshold=threshold)

        if refill is not None and not offered:
            offered = _uncovered(list(refill), captures, distance=distance, threshold=threshold)

        if user_id in held:
            self._record(offered, held)
            return held[user_id][0]

        if not offered:
            self._record(offered, held)
            return None

        index = _closest_index(offered, at, distance=distance) if at is not None else 0
        chosen = offered.pop(index)
        held[user_id] = (chosen, now + lease)
        self._record(offered, held)
        return chosen

    def release(self, user_id: str) -> None:
        """Drop this user's hold, without returning its location to the batch.

        Args:
            user_id: The user giving up their location.
        """
        held = _held(self)
        held.pop(user_id, None)
        self._record(_batch(self), held)

    def _record(self, batch: list[cg.Location], held: _Held) -> None:
        """Write ``batch`` and ``held`` back as this book's fields."""
        self.batch = cg.Array(batch)
        self.held = held_map(
            {
                user_id: Lease(location=location, expires=cg.Time(expires))
                for user_id, (location, expires) in held.items()
            },
        )

release(user_id) #

Drop this user's hold, without returning its location to the batch.

Parameters:

Name Type Description Default
user_id str

The user giving up their location.

required
Source code in capturegraph-recipes/capturegraph_recipes/scheduling/organize/coverage_reservations.py
def release(self, user_id: str) -> None:
    """Drop this user's hold, without returning its location to the batch.

    Args:
        user_id: The user giving up their location.
    """
    held = _held(self)
    held.pop(user_id, None)
    self._record(_batch(self), held)

reserve(user_id, *, distance, at=None, fulfilled_by=(), threshold=1.0, lease=DEFAULT_LEASE, refill=None, now=None) #

The location this user holds, leasing one from the batch if none.

@cgserver.intercept(Survey, lambda s: s._metadata._location)
def next_spot(profile: cgserver.RequestProfile, target: Survey) -> cg.Location | None:
    covered = target.sessions.values().location
    return cgr.scheduling.CoverageBook.open("survey").reserve(
        profile.user_id,
        at=profile.location,
        fulfilled_by=covered,
        distance=cgr.scheduling.distance.location(sigma_m=10.0),
        refill=cgr.scheduling.area_batch(BOUNDARY, covered),
    )

Parameters:

Name Type Description Default
user_id str

The user asking for a location.

required
distance Callable[[Location, Location], float]

A distance between two cg.Locations — the same metric used to select the batch (cgr.scheduling.distance.location(sigma_m=...)). It both picks the location closest to a requester and decides when a capture covers a reservation.

required
at Location | None

The requester's current location, if known. The batch location closest to it is leased; without it, the batch is leased in insertion order (FIFO).

None
fulfilled_by Iterable[Location | MissingType | None]

Captured locations; a reservation or batch location within threshold of any of these is retired first, so a covered spot is never offered. An absent entry (None or Missing) is skipped.

()
threshold float

A reservation is released once a capture lies within this distance of it, in the units distance returns. Defaults to 1.0.

1.0
lease timedelta

How long a handout is held before, absent a covering capture, the location returns to the batch. Defaults to 30 minutes.

DEFAULT_LEASE
refill Iterable[Location] | None

Locations to install as the batch when it is exhausted, such as area_batch(boundary, covered). Ignored while the batch still has locations to hand out.

None
now datetime | None

The reference time; defaults to datetime.now(). Pass it explicitly to make lease expiry deterministic under test.

None

Returns:

Type Description
Location | None

The user's reserved location, or None if the batch is exhausted

Location | None

and the user holds nothing.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/organize/coverage_reservations.py
def reserve(
    self,
    user_id: str,
    *,
    distance: Callable[[cg.Location, cg.Location], float],
    at: cg.Location | None = None,
    fulfilled_by: Iterable[cg.Location | cg.MissingType | None] = (),
    threshold: float = 1.0,
    lease: timedelta = DEFAULT_LEASE,
    refill: Iterable[cg.Location] | None = None,
    now: datetime | None = None,
) -> cg.Location | None:
    """The location this user holds, leasing one from the batch if none.

    ```python
    @cgserver.intercept(Survey, lambda s: s._metadata._location)
    def next_spot(profile: cgserver.RequestProfile, target: Survey) -> cg.Location | None:
        covered = target.sessions.values().location
        return cgr.scheduling.CoverageBook.open("survey").reserve(
            profile.user_id,
            at=profile.location,
            fulfilled_by=covered,
            distance=cgr.scheduling.distance.location(sigma_m=10.0),
            refill=cgr.scheduling.area_batch(BOUNDARY, covered),
        )
    ```

    Args:
        user_id: The user asking for a location.
        distance: A distance between two ``cg.Location``s — the same metric used
            to select the batch (``cgr.scheduling.distance.location(sigma_m=...)``). It
            both picks the location closest to a requester and decides when a
            capture covers a reservation.
        at: The requester's current location, if known. The batch location
            closest to it is leased; without it, the batch is leased in
            insertion order (FIFO).
        fulfilled_by: Captured locations; a reservation or batch location within
            ``threshold`` of any of these is retired first, so a covered spot is
            never offered. An absent entry (``None`` or ``Missing``) is skipped.
        threshold: A reservation is released once a capture lies within this
            distance of it, in the units ``distance`` returns. Defaults to
            ``1.0``.
        lease: How long a handout is held before, absent a covering capture, the
            location returns to the batch. Defaults to 30 minutes.
        refill: Locations to install as the batch **when it is exhausted**,
            such as ``area_batch(boundary, covered)``. Ignored while the batch
            still has locations to hand out.
        now: The reference time; defaults to ``datetime.now()``. Pass it
            explicitly to make lease expiry deterministic under test.

    Returns:
        The user's reserved location, or ``None`` if the batch is exhausted
        and the user holds nothing.
    """
    now = now if now is not None else datetime.now(UTC)
    captures = [capture for capture in fulfilled_by if isinstance(capture, cg.Location)]
    held = _retire_covered(_held(self), captures, distance=distance, threshold=threshold)
    held, offered = _reclaim_lapsed(held, _batch(self), now=now)
    offered = _uncovered(offered, captures, distance=distance, threshold=threshold)

    if refill is not None and not offered:
        offered = _uncovered(list(refill), captures, distance=distance, threshold=threshold)

    if user_id in held:
        self._record(offered, held)
        return held[user_id][0]

    if not offered:
        self._record(offered, held)
        return None

    index = _closest_index(offered, at, distance=distance) if at is not None else 0
    chosen = offered.pop(index)
    held[user_id] = (chosen, now + lease)
    self._record(offered, held)
    return chosen

Lease #

Bases: Struct

One user's held location and when the hold expires.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/organize/coverage_reservations.py
class Lease(cg.Struct):
    """One user's held location and when the hold expires."""

    location: cg.Location
    expires: cg.Time

area_batch(area, covered, batch=8, spacing_m=2.0) #

batch places inside area, each far from covered and from each other.

Memoized on its arguments, so a reservation interceptor can pass it as refill= on every request and draw anew only when a capture lands.

Parameters:

Name Type Description Default
area Array[Location]

The survey boundary, a polygon of at least three places.

required
covered Array[Location]

The places already captured; absent entries are skipped.

required
batch int

How many places to pick.

8
spacing_m float

The grid spacing inside area, in metres.

2.0

Returns:

Type Description
Array[Location]

The picked places; their order is the grid's.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/organize/coverage_reservations.py
@cg.pure_function("scheduling.area_batch/1")
def area_batch(
    area: cg.Array[cg.Location],
    covered: cg.Array[cg.Location],
    batch: int = 8,
    spacing_m: float = 2.0,
) -> cg.Array[cg.Location]:
    """``batch`` places inside ``area``, each far from ``covered`` and from each other.

    Memoized on its arguments, so a reservation interceptor can pass it as
    ``refill=`` on every request and draw anew only when a capture lands.

    Args:
        area: The survey boundary, a polygon of at least three places.
        covered: The places already captured; absent entries are skipped.
        batch: How many places to pick.
        spacing_m: The grid spacing inside ``area``, in metres.

    Returns:
        The picked places; their order is the grid's.
    """
    return select_sessions(
        potential_sessions=locations_area(area, resolution_meters=spacing_m),
        previous_sessions=cg.Array([where for where in covered if isinstance(where, cg.Location)]),
        distance_fn=location_distance(sigma_m=1.0),
        energy_fn=lambda separation: -separation,
        energy_mode="max",
        selections=batch,
    )