Skip to content

weather

weather #

Matching forecast weather to the moments a session might be captured.

nearest_weather(weather, times) #

The weather entry closest in time to each of times.

Parameters:

Name Type Description Default
weather Array[Weather]

The forecast or observed entries to choose from.

required
times Array[datetime]

The moments to find weather for.

required

Returns:

Type Description
Array[Weather]

One entry per query time, in the same order.

Source code in capturegraph-lib/capturegraph/scheduling/forecast/weather.py
def nearest_weather(
    weather: cg.Array[cg.Weather],
    times: cg.Array[datetime],
) -> cg.Array[cg.Weather]:
    """The weather entry closest in time to each of ``times``.

    Args:
        weather: The forecast or observed entries to choose from.
        times: The moments to find weather for.

    Returns:
        One entry per query time, in the same order.
    """
    ordered = sorted(weather, key=lambda entry: entry.time)
    moments = [entry.time for entry in ordered]

    results = []
    for moment in times:
        index = bisect.bisect_left(moments, moment)
        if index == 0:
            nearest = ordered[0]
        elif index == len(ordered):
            nearest = ordered[-1]
        else:
            before, after = ordered[index - 1], ordered[index]
            nearest = before if abs(moment - before.time) <= abs(after.time - moment) else after
        results.append(nearest)

    return cg.Array(results)