|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2023 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +""" |
| 5 | +Benchmarks for the PeriodicFeatureExtractor class. |
| 6 | +
|
| 7 | +This module contains benchmarks that are comparing |
| 8 | +the performance of a numpy implementation with a python |
| 9 | +implementation. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import asyncio |
| 15 | +import logging |
| 16 | +from datetime import datetime, timedelta, timezone |
| 17 | +from functools import partial |
| 18 | +from timeit import timeit |
| 19 | +from typing import List |
| 20 | + |
| 21 | +import numpy as np |
| 22 | +from frequenz.channels import Broadcast |
| 23 | +from numpy.random import default_rng |
| 24 | +from numpy.typing import NDArray |
| 25 | + |
| 26 | +from frequenz.sdk.timeseries import MovingWindow, PeriodicFeatureExtractor, Sample |
| 27 | + |
| 28 | + |
| 29 | +async def init_feature_extractor(period: int) -> PeriodicFeatureExtractor: |
| 30 | + """Initialize the PeriodicFeatureExtractor class.""" |
| 31 | + # We only need the moving window to initialize the PeriodicFeatureExtractor class. |
| 32 | + lm_chan = Broadcast[Sample]("lm_net_power") |
| 33 | + moving_window = MovingWindow( |
| 34 | + timedelta(seconds=1), lm_chan.new_receiver(), timedelta(seconds=1) |
| 35 | + ) |
| 36 | + |
| 37 | + await lm_chan.new_sender().send(Sample(datetime.now(tz=timezone.utc), 0)) |
| 38 | + |
| 39 | + # Initialize the PeriodicFeatureExtractor class with a period of period seconds. |
| 40 | + # This works since the sampling period is set to 1 second. |
| 41 | + return PeriodicFeatureExtractor(moving_window, timedelta(seconds=period)) |
| 42 | + |
| 43 | + |
| 44 | +def _calculate_avg_window( |
| 45 | + feature_extractor: PeriodicFeatureExtractor, |
| 46 | + window: NDArray[np.float_], |
| 47 | + window_size: int, |
| 48 | +) -> NDArray[np.float_]: |
| 49 | + """ |
| 50 | + Reshapes the window and calculates the average. |
| 51 | +
|
| 52 | + This method calculates the average of a window by averaging over all |
| 53 | + windows fully inside the passed numpy array having the period |
| 54 | + `self.period`. |
| 55 | +
|
| 56 | + Args: |
| 57 | + feature_extractor: The instance of the PeriodicFeatureExtractor to use. |
| 58 | + window: The window to calculate the average over. |
| 59 | + window_size: The size of the window to calculate the average over. |
| 60 | + weights: The weights to use for the average calculation. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + The averaged window. |
| 64 | + """ |
| 65 | + reshaped = feature_extractor._reshape_np_array( # pylint: disable=protected-access |
| 66 | + window, window_size |
| 67 | + ) |
| 68 | + # ignoring the type because np.average returns Any |
| 69 | + return np.average(reshaped[:, :window_size], axis=0) # type: ignore[no-any-return] |
| 70 | + |
| 71 | + |
| 72 | +def _calculate_avg_window_py( |
| 73 | + feature_extractor: PeriodicFeatureExtractor, |
| 74 | + window: NDArray[np.float_], |
| 75 | + window_size: int, |
| 76 | + weights: List[float] | None = None, |
| 77 | +) -> NDArray[np.float_]: |
| 78 | + """ |
| 79 | + Plain python version of the average calculator. |
| 80 | +
|
| 81 | + This method avoids copying in any case but is 15 to 600 slower then the |
| 82 | + numpy version. |
| 83 | +
|
| 84 | + This method is only used in these benchmarks. |
| 85 | +
|
| 86 | + Args: |
| 87 | + feature_extractor: The instance of the PeriodicFeatureExtractor to use. |
| 88 | + window: The window to calculate the average over. |
| 89 | + window_size: The size of the window to calculate the average over. |
| 90 | + weights: The weights to use for the average calculation. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + The averaged window. |
| 94 | + """ |
| 95 | + |
| 96 | + def _num_windows( |
| 97 | + window: NDArray[np.float_] | MovingWindow, window_size: int, period: int |
| 98 | + ) -> int: |
| 99 | + """ |
| 100 | + Get the number of windows that are fully contained in the MovingWindow. |
| 101 | +
|
| 102 | + This method calculates how often a given window, defined by it size, is |
| 103 | + fully contained in the MovingWindow at its current state or any numpy |
| 104 | + ndarray given the period between two window neighbors. |
| 105 | +
|
| 106 | + Args: |
| 107 | + window: The buffer that is used for the average calculation. |
| 108 | + window_size: The size of the window in samples. |
| 109 | +
|
| 110 | + Returns: |
| 111 | + The number of windows that are fully contained in the MovingWindow. |
| 112 | + """ |
| 113 | + num_windows = len(window) // period |
| 114 | + if len(window) - num_windows * period >= window_size: |
| 115 | + num_windows += 1 |
| 116 | + |
| 117 | + return num_windows |
| 118 | + |
| 119 | + period = feature_extractor._period # pylint: disable=protected-access |
| 120 | + |
| 121 | + num_windows = _num_windows( |
| 122 | + window, |
| 123 | + window_size, |
| 124 | + period, |
| 125 | + ) |
| 126 | + |
| 127 | + res = np.empty(window_size) |
| 128 | + |
| 129 | + for i in range(window_size): |
| 130 | + assert num_windows * period - len(window) <= period |
| 131 | + summe = 0 |
| 132 | + for j in range(num_windows): |
| 133 | + if weights is None: |
| 134 | + summe += window[i + (j * period)] |
| 135 | + else: |
| 136 | + summe += weights[j] * window[i + (j * period)] |
| 137 | + |
| 138 | + if not weights: |
| 139 | + res[i] = summe / num_windows |
| 140 | + else: |
| 141 | + res[i] = summe / np.sum(weights) |
| 142 | + |
| 143 | + return res |
| 144 | + |
| 145 | + |
| 146 | +def run_benchmark( |
| 147 | + array: NDArray[np.float_], |
| 148 | + window_size: int, |
| 149 | + feature_extractor: PeriodicFeatureExtractor, |
| 150 | +) -> None: |
| 151 | + """Run the benchmark for the given ndarray and window size.""" |
| 152 | + |
| 153 | + def run_avg_np( |
| 154 | + array: NDArray[np.float_], |
| 155 | + window_size: int, |
| 156 | + feature_extractor: PeriodicFeatureExtractor, |
| 157 | + ) -> None: |
| 158 | + """ |
| 159 | + Run the FeatureExtractor. |
| 160 | +
|
| 161 | + The return value is discarded such that it can be used by timit. |
| 162 | +
|
| 163 | + Args: |
| 164 | + a: The array containing all data. |
| 165 | + window_size: The size of the window. |
| 166 | + feature_extractor: An instance of the PeriodicFeatureExtractor. |
| 167 | + """ |
| 168 | + _calculate_avg_window(feature_extractor, array, window_size) |
| 169 | + |
| 170 | + def run_avg_py( |
| 171 | + array: NDArray[np.float_], |
| 172 | + window_size: int, |
| 173 | + feature_extractor: PeriodicFeatureExtractor, |
| 174 | + ) -> None: |
| 175 | + """ |
| 176 | + Run the FeatureExtractor. |
| 177 | +
|
| 178 | + The return value is discarded such that it can be used by timit. |
| 179 | +
|
| 180 | + Args: |
| 181 | + a: The array containing all data. |
| 182 | + window_size: The size of the window. |
| 183 | + feature_extractor: An instance of the PeriodicFeatureExtractor. |
| 184 | + """ |
| 185 | + _calculate_avg_window_py(feature_extractor, array, window_size) |
| 186 | + |
| 187 | + time_np = timeit( |
| 188 | + partial(run_avg_np, array, window_size, feature_extractor), number=10 |
| 189 | + ) |
| 190 | + time_py = timeit( |
| 191 | + partial(run_avg_py, array, window_size, feature_extractor), number=10 |
| 192 | + ) |
| 193 | + print(time_np) |
| 194 | + print(time_py) |
| 195 | + print(f"Numpy is {time_py / time_np} times faster!") |
| 196 | + |
| 197 | + |
| 198 | +DAY_S = 24 * 60 * 60 |
| 199 | + |
| 200 | + |
| 201 | +async def main() -> None: |
| 202 | + """ |
| 203 | + Run the benchmarks. |
| 204 | +
|
| 205 | + The benchmark are comparing the numpy |
| 206 | + implementation with the python implementation. |
| 207 | + """ |
| 208 | + # initialize random number generator |
| 209 | + rng = default_rng() |
| 210 | + |
| 211 | + # create a random ndarray with 29 days -5 seconds of data |
| 212 | + days_29_s = 29 * DAY_S |
| 213 | + feature_extractor = await init_feature_extractor(10) |
| 214 | + data = rng.standard_normal(days_29_s) |
| 215 | + run_benchmark(data, 4, feature_extractor) |
| 216 | + |
| 217 | + days_29_s = 29 * DAY_S + 3 |
| 218 | + data = rng.standard_normal(days_29_s) |
| 219 | + run_benchmark(data, 4, feature_extractor) |
| 220 | + |
| 221 | + # create a random ndarray with 29 days +5 seconds of data |
| 222 | + data = rng.standard_normal(29 * DAY_S + 5) |
| 223 | + |
| 224 | + feature_extractor = await init_feature_extractor(7 * DAY_S) |
| 225 | + # TEST one day window and 6 days distance. COPY (Case 3) |
| 226 | + run_benchmark(data, DAY_S, feature_extractor) |
| 227 | + # benchmark one day window and 6 days distance. NO COPY (Case 1) |
| 228 | + run_benchmark(data[: 28 * DAY_S], DAY_S, feature_extractor) |
| 229 | + |
| 230 | + |
| 231 | +logging.basicConfig(level=logging.DEBUG) |
| 232 | +asyncio.run(main()) |
0 commit comments