Skip to content

rate

rate #

Rate — how often events happened, per minute, stacked by group.

FLOOR = 0.001 module-attribute #

The rate, per minute, below which a stretch of timeline counts as quiet and is not drawn.

STEP = timedelta(minutes=2) module-attribute #

The width of one bin of a timeline.

Rate #

Bases: Component

Events per minute — each event spread as a Gaussian of sigma — stacked by group.

Across the whole span (fold=None) only the stretches where something happened are drawn, each run from and back to zero, on a time axis read in the reader's own zone. With fold="day" every day is laid over one: the rate by local time of day. Either way the reader drags to pan and scrolls to zoom along time.

instants = photos.exif().instant
cgui.Rate(instants, groups=participants, fold="day")
cgui.Rate(instants, groups=participants)
Source code in capturegraph-ui/capturegraph_ui/charts/rate.py
class Rate(Component):
    """Events per minute — each event spread as a Gaussian of ``sigma`` — stacked by group.

    Across the whole span (``fold=None``) only the stretches where something
    happened are drawn, each run from and back to zero, on a time axis read in
    the reader's own zone. With ``fold="day"`` every day is laid over one: the
    rate by local time of day. Either way the reader drags to pan and scrolls to
    zoom along time.

    ```python
    instants = photos.exif().instant
    cgui.Rate(instants, groups=participants, fold="day")
    cgui.Rate(instants, groups=participants)
    ```
    """

    instants: cg.Array | list[object]
    groups: cg.Array | list[object] | None = None
    sigma: timedelta = timedelta(minutes=10)
    fold: Literal["day"] | None = None

    def __post_init__(self) -> None:
        """Check the props, then that ``groups`` lines up with ``instants`` and holds instants.

        Raises:
            ValueError: If ``groups`` is of another length, or ``instants`` holds anything
                but instants.
        """
        super().__post_init__()
        if self.absent:
            return
        if self.groups is not None and len(self.groups) != len(self.instants):
            raise ValueError(
                f"Rate.groups names one group per instant, got {len(self.groups)} "
                f"for {len(self.instants)}"
            )
        encoded = encode(self.instants)
        if encoded.kind != "instant" and any(value is not None for value in encoded.values):
            raise ValueError("Rate.instants holds instants: datetimes or cg.Time values")

    def html(self, render: Render) -> str:
        """The stacked rate as one Vega-Lite area chart, zoomable along time."""
        events = self._events()
        if not events:
            return ""
        spec = self._by_time_of_day(events) if self.fold == "day" else self._timeline(events)
        return embed(render, spec)

    def _events(self) -> list[tuple[float, str | None]]:
        """Each recorded instant, in epoch milliseconds, with its group's name."""
        moments = encode(self.instants).values
        names = [None] * len(moments) if self.groups is None else [_name(g) for g in self.groups]
        return [
            (moment, name)
            for moment, name in zip(moments, names, strict=True)
            if moment is not None
        ]

    def _timeline(self, events: list[tuple[float, str | None]]) -> dict[str, cg.JSONValue]:
        """The rate across the whole span, binned and smoothed here, quiet stretches left out."""
        step = STEP / timedelta(milliseconds=1)
        reach = 4 * (self.sigma / timedelta(milliseconds=1))
        first = int((min(moment for moment, _ in events) - reach) // step)
        count = int((max(moment for moment, _ in events) + reach) // step) - first + 1
        kernel = _gaussian(self.sigma / STEP)
        rows: list[cg.JSONValue] = []
        for name in _names(events):
            bins = np.bincount(
                [int(moment // step) - first for moment, group in events if group == name],
                minlength=count,
            ).astype(np.float64)
            rate = np.convolve(bins, kernel, mode="same") / (STEP / timedelta(minutes=1))
            loud = rate >= FLOOR
            drawn = loud | np.roll(loud, 1) | np.roll(loud, -1)
            rows += [
                {
                    "time": (first + index) * step,
                    "group": name,
                    "rate": round(float(rate[index]), 4),
                }
                for index in np.flatnonzero(drawn)
            ]
        return _area(rows, {"field": "time", "type": "temporal", "title": "Time"}, self.groups)

    def _by_time_of_day(self, events: list[tuple[float, str | None]]) -> dict[str, cg.JSONValue]:
        """The rate by local time of day, every day laid over one, smoothed in the browser."""
        spec = _area(
            [{"time": moment, "group": name} for moment, name in events],
            {
                "field": "hour",
                "type": "quantitative",
                "title": "Time of day (h)",
                "scale": {"domain": [0, 24]},
                "axis": {"values": list(range(0, 25, 3))},
            },
            self.groups,
        )
        spec["transform"] = [
            {
                "calculate": "hours(datum.time) + minutes(datum.time) / 60",
                "as": "hour",
            },
            {
                "density": "hour",
                "groupby": ["group"],
                "bandwidth": self.sigma / timedelta(hours=1),
                "extent": [0, 24],
                "steps": 24 * 30,
                "counts": True,
                "as": ["hour", "per_hour"],
            },
            {"calculate": "datum.per_hour / 60", "as": "rate"},
        ]
        return spec

__post_init__() #

Check the props, then that groups lines up with instants and holds instants.

Raises:

Type Description
ValueError

If groups is of another length, or instants holds anything but instants.

Source code in capturegraph-ui/capturegraph_ui/charts/rate.py
def __post_init__(self) -> None:
    """Check the props, then that ``groups`` lines up with ``instants`` and holds instants.

    Raises:
        ValueError: If ``groups`` is of another length, or ``instants`` holds anything
            but instants.
    """
    super().__post_init__()
    if self.absent:
        return
    if self.groups is not None and len(self.groups) != len(self.instants):
        raise ValueError(
            f"Rate.groups names one group per instant, got {len(self.groups)} "
            f"for {len(self.instants)}"
        )
    encoded = encode(self.instants)
    if encoded.kind != "instant" and any(value is not None for value in encoded.values):
        raise ValueError("Rate.instants holds instants: datetimes or cg.Time values")

html(render) #

The stacked rate as one Vega-Lite area chart, zoomable along time.

Source code in capturegraph-ui/capturegraph_ui/charts/rate.py
def html(self, render: Render) -> str:
    """The stacked rate as one Vega-Lite area chart, zoomable along time."""
    events = self._events()
    if not events:
        return ""
    spec = self._by_time_of_day(events) if self.fold == "day" else self._timeline(events)
    return embed(render, spec)