pytrendy 2.0.0.dev7__tar.gz → 2.0.0.dev9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/PKG-INFO +2 -1
  2. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pyproject.toml +3 -2
  3. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/detect_trends.py +4 -4
  4. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/plot_pytrendy.py +16 -1
  5. pytrendy-2.0.0.dev9/pytrendy/io/prep_signal_params.py +204 -0
  6. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/process_signals.py +9 -7
  7. pytrendy-2.0.0.dev7/pytrendy/io/prep_signal_params.py +0 -44
  8. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/LICENSE +0 -0
  9. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/README.md +0 -0
  10. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/__init__.py +0 -0
  11. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/__init__.py +0 -0
  12. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/data/classes_signals.csv +0 -0
  13. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/data/series_synthetic.csv +0 -0
  14. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/data_loader.py +0 -0
  15. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/prep_index.py +0 -0
  16. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/io/results_pytrendy.py +0 -0
  17. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/__init__.py +0 -0
  18. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_analyse.py +0 -0
  19. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_get.py +0 -0
  20. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/__init__.py +0 -0
  21. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/abrupt_shaving.py +0 -0
  22. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/artifact_cleanup.py +0 -0
  23. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/gradual_expand_contract.py +0 -0
  24. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/segment_grouping.py +0 -0
  25. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/trend_classify.py +0 -0
  26. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/post_processing/segments_refine/update_neighbours.py +0 -0
  27. {pytrendy-2.0.0.dev7 → pytrendy-2.0.0.dev9}/pytrendy/simpledtw.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytrendy
3
- Version: 2.0.0.dev7
3
+ Version: 2.0.0.dev9
4
4
  Summary: Trend Detection in Python. Applicable for real-world industry use cases in time series.
5
5
  License: MIT License
6
6
 
@@ -52,6 +52,7 @@ Requires-Dist: mkdocstrings (>=0.28.3,<1) ; extra == "docs"
52
52
  Requires-Dist: mkdocstrings-python (>=1.16,<2) ; extra == "docs"
53
53
  Requires-Dist: numpy
54
54
  Requires-Dist: pandas
55
+ Requires-Dist: pymdown-extensions (<12.2) ; extra == "docs"
55
56
  Requires-Dist: pytest ; extra == "dev"
56
57
  Requires-Dist: pytest-cov ; extra == "dev"
57
58
  Requires-Dist: pytest-mpl ; extra == "dev"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytrendy"
3
- version = "2.0.0.dev7"
3
+ version = "2.0.0.dev9"
4
4
  description = "Trend Detection in Python. Applicable for real-world industry use cases in time series."
5
5
  authors = [
6
6
  { name = "Russell Sammut Bonnici", email = "r.sammutbonnici@gmail.com" },
@@ -62,7 +62,8 @@ docs = [
62
62
  "mkdocs-api-autonav==0.4.0",
63
63
  "mkdocstrings>=0.28.3,<1",
64
64
  "mkdocstrings-python>=1.16,<2",
65
- "mkdocs-jupyterlite==0.4.1"
65
+ "mkdocs-jupyterlite==0.4.1",
66
+ "pymdown-extensions<12.2"
66
67
  ]
67
68
 
68
69
  [project.urls]
@@ -55,7 +55,7 @@ def detect_trends(df: pd.DataFrame,
55
55
  signal_params (dict, optional):
56
56
  Optional parameters to customize the signal-processing constants. Supported keys (independent from `method_params`):
57
57
 
58
- - **window_smooth** (`int`): Savitzky-Golay smoothing window, in points. Defaults to `15`.
58
+ - **window_smooth** (`int`): Savitzky-Golay smoothing window, in points. When omitted it is inferred from the index cadence (193/97/49/15/9/25/9/5 for 15min/30min/hourly/daily/weekly/monthly/quarterly/yearly, and 15 for anything unmapped). An explicit value always wins. The resolved window is clamped to the series length.
59
59
  - **smooth_factor** (`float`): Fraction of `window_smooth` spanned by the derived `window_flat` window. Raising it smooths the flat baseline (fewer flat flags); lowering it responds more locally. Defaults to `0.5`.
60
60
  - **noise_factor** (`float`): Fraction of `window_smooth` spanned by the derived `window_noise` window. Raising it smooths the noise (SNR) estimate (fewer noise flags); lowering it responds more locally. Defaults to `0.5`.
61
61
  - **grouping_distance** (`int`): Maximum gap, in steps, for grouping nearby segments. Defaults to `7`.
@@ -119,9 +119,9 @@ def detect_trends(df: pd.DataFrame,
119
119
  'avoid_noise': method_params.get('avoid_noise', True),
120
120
  }
121
121
 
122
- # Configures signal-processing constants. Unknown keys are accepted and
123
- # forwarded (validation is deliberately out of scope for now).
124
- signal_params = prep_signal_params.prep_signal_params(signal_params)
122
+ # Configures signal-processing constants. The external index lets the smoothing window default to a
123
+ # cadence-aware value; unknown keys are accepted and forwarded (validation is deliberately out of scope for now).
124
+ signal_params = prep_signal_params.prep_signal_params(signal_params, index=external_index)
125
125
 
126
126
  # Core 5-step pipeline
127
127
  df = process_signals(df, value_col, method_params, signal_params, debug)
@@ -2,6 +2,7 @@
2
2
 
3
3
  import pandas as pd
4
4
  import numpy as np
5
+ import matplotlib
5
6
  import matplotlib.pyplot as plt
6
7
  import matplotlib.dates as mdates
7
8
  import matplotlib.patches as mpatches
@@ -44,6 +45,19 @@ def _annotation_color(color):
44
45
  return (r * 0.7, g * 0.7, b * 0.7)
45
46
 
46
47
 
48
+ def _show_plot() -> None:
49
+ """Display the current figure, skipping backends that cannot show a window.
50
+
51
+ Non-interactive backends (e.g. Agg under CI or a headless environment) emit
52
+ a ``UserWarning`` from ``plt.show()``; callers such as ``suppress_show=False``
53
+ still expect the figure to be drawn to its canvas, so only skip the display
54
+ call itself.
55
+ """
56
+ from matplotlib.backends.registry import BackendFilter, backend_registry
57
+ if matplotlib.get_backend().lower() not in backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE):
58
+ plt.show()
59
+
60
+
47
61
  def _safe_adjacent(index, pos, offset):
48
62
  """
49
63
  Safely get an adjacent index value with bounds checking.
@@ -624,5 +638,6 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
624
638
 
625
639
  plt.tight_layout()
626
640
  if not suppress_show:
627
- plt.show()
641
+ _show_plot()
628
642
  return fig
643
+
@@ -0,0 +1,204 @@
1
+ """**Signal-Parameter Preparation**
2
+
3
+ The signal-processing stages share a common set of constants — smoothing and
4
+ rolling windows, grouping distance, and the noise/flat thresholds. ``detect_trends``
5
+ is the single public entry point, so this module is the one place those constants
6
+ are defaulted before the pipeline runs.
7
+
8
+ ``window_smooth`` is granularity-aware: when the caller does not override it, it is
9
+ inferred from the index cadence so a single smoothing window spans a comparable
10
+ stretch of the series at every sampling frequency. The inferred point counts are:
11
+
12
+ | Cadence | P (pts/cycle) | window_smooth (= 2P+1) |
13
+ | ----------- | ------------- | ---------------------- |
14
+ | 15 minutes | 96 | 193 |
15
+ | 30 minutes | 48 | 97 |
16
+ | hourly | 24 | 49 |
17
+ | daily | 7 | 15 |
18
+ | weekly | 4 | 9 |
19
+ | monthly | 12 | 25 |
20
+ | quarterly | 4 | 9 |
21
+ | yearly | — (fallback) | 5 |
22
+ | other | — | 15 |
23
+
24
+ The table entries satisfy ``int(window_smooth × 0.5) = P``, so the default
25
+ ``smooth_factor``/``noise_factor`` (0.5) make ``window_flat``/``window_noise``
26
+ span one seasonal cycle while ``window_smooth`` spans two. Keep new rows on the
27
+ ``2P+1`` ladder.
28
+
29
+ The table is matched pragmatically against :func:`pandas.infer_freq` labels:
30
+ ``T``/``min`` aliases containing 15 or 30, hourly ``H``/``h``, daily ``D``,
31
+ weekly ``W...``, monthly ``M``/``ME``/``MS``,
32
+ quarterly ``Q...`` and yearly ``Y``/``A``/``YE``/``YS``. An explicit user ``window_smooth`` always wins and
33
+ skips inference. The resolved window is finally clamped to the series length
34
+ (decrementing by two to stay odd) with a floor of 3, so Savitzky-Golay always
35
+ receives a valid window.
36
+
37
+ Defaults are merged with any user-supplied ``signal_params`` overrides. The derived
38
+ windows ``window_flat`` and ``window_noise`` are not top-level defaults: unless
39
+ explicitly overridden they derive from ``window_smooth``. Every stage downstream
40
+ assumes :func:`prep_signal_params` returns a fully-populated dict.
41
+ """
42
+
43
+ import warnings
44
+
45
+ import numpy as np
46
+ import pandas as pd
47
+
48
+ _SIGNAL_PARAMS_DEFAULTS = {
49
+ 'window_smooth': 15, # Savitzky-Golay smoothing window, in points.
50
+ 'smooth_factor': 0.5, # Fraction of window_smooth spanned by window_flat: raise to widen it (smoother flat
51
+ # baseline, fewer flags), lower to narrow it (more sensitive); scaled to window_smooth so it stays proportional. Historical name: it scales window_flat, not smoothing; with the 2P+1 table it recovers P.
52
+ 'noise_factor': 0.5, # Fraction of window_smooth spanned by window_noise: raise to widen it (smoother SNR estimate, fewer flags), lower to narrow it (more sensitive); scaled to window_smooth so it stays proportional.
53
+ 'grouping_distance': 7, # Maximum gap, in index steps, for grouping nearby segments.
54
+ 'min_trend_length': 3, # Minimum length, in steps, for an Up/Down segment to be retained.
55
+ 'min_flat_noise_length': 1, # Minimum length, in steps, for a Flat/Noise segment to be retained.
56
+ 'threshold_noise': 2.5, # SNR threshold (dB) below which a region is classified as noise.
57
+ 'threshold_smooth': 0.001, # Derivative threshold as a fraction of the signal IQR, below which motion counts as flat.
58
+ 'threshold_flat': 0.835, # Flat sensitivity as a fraction of the minimum non-zero rolling std.
59
+ }
60
+
61
+ # Inferred smoothing window per cadence label. See the module docstring for the table.
62
+ _WINDOW_BY_CADENCE = {
63
+ '15min': 193,
64
+ '30min': 97,
65
+ 'H': 49,
66
+ 'D': 15,
67
+ 'W': 9,
68
+ 'ME': 25,
69
+ 'QE': 9,
70
+ 'YE': 5,
71
+ }
72
+ _DEFAULT_WINDOW = _SIGNAL_PARAMS_DEFAULTS['window_smooth']
73
+
74
+
75
+ def _clamp_window(window: int, n: int|None) -> int:
76
+ """Shrink ``window`` to the series length, keeping it odd with a floor of 3."""
77
+ if n is None:
78
+ return window
79
+ while window > n:
80
+ window -= 2
81
+ return max(window, 3)
82
+
83
+
84
+ def _as_datetime_index(index):
85
+ """Return a ``DatetimeIndex`` view of ``index`` when it is date-like, else ``None``.
86
+
87
+ Numeric indexes are never coerced: integer/float values would otherwise be read
88
+ as epoch timestamps by :func:`pandas.to_datetime`. Only datetime dtypes and
89
+ genuinely parseable string/object labels are accepted.
90
+ """
91
+ if isinstance(index, pd.Series):
92
+ dtype = index.dtype
93
+ else:
94
+ arr = np.asarray(index)
95
+ if np.issubdtype(arr.dtype, np.datetime64):
96
+ return pd.DatetimeIndex(arr)
97
+ dtype = arr.dtype
98
+
99
+ if pd.api.types.is_datetime64_any_dtype(dtype):
100
+ return pd.DatetimeIndex(index)
101
+ if pd.api.types.is_object_dtype(dtype) or pd.api.types.is_string_dtype(dtype):
102
+ with warnings.catch_warnings():
103
+ warnings.filterwarnings("ignore", message="Could not infer format.*")
104
+ parsed = pd.to_datetime(index, errors='coerce')
105
+ if parsed.notna().all():
106
+ return pd.DatetimeIndex(parsed)
107
+ return None
108
+
109
+
110
+ def _window_from_label(label: str|None) -> int|None:
111
+ """Map a ``pandas.infer_freq`` label to its smoothing window, or ``None`` if unmapped."""
112
+ lab = str(label)
113
+ low = lab.lower()
114
+
115
+ # Sub-hourly: 'T'/'min' aliases (e.g. '15T', '30min'); other spans are unmapped.
116
+ if 'min' in low or low.endswith('t'):
117
+ if '15' in lab:
118
+ return _WINDOW_BY_CADENCE['15min']
119
+ if '30' in lab:
120
+ return _WINDOW_BY_CADENCE['30min']
121
+ return None
122
+ if low == 'h': # hourly ('H'/'h'); '5H' etc. stay unmapped
123
+ return _WINDOW_BY_CADENCE['H']
124
+ if low == 'd': # daily
125
+ return _WINDOW_BY_CADENCE['D']
126
+ if low.startswith('w'): # weekly ('W', 'W-SUN', ...)
127
+ return _WINDOW_BY_CADENCE['W']
128
+ if low.startswith('m'): # monthly ('M'/'ME'/'MS'); 'min' handled above
129
+ return _WINDOW_BY_CADENCE['ME']
130
+ if low.startswith('q'): # quarterly
131
+ return _WINDOW_BY_CADENCE['QE']
132
+ if low.startswith('y') or low.startswith('a'): # yearly ('Y'/'A'/'YE'/'YS')
133
+ return _WINDOW_BY_CADENCE['YE']
134
+ return None
135
+
136
+
137
+ def infer_window_smooth(index, n: int|None=None) -> int:
138
+ """
139
+ Infer a smoothing window from the sampling cadence of an index.
140
+
141
+ Converts ``index`` to a ``DatetimeIndex`` (date-like values only), asks
142
+ :func:`pandas.infer_freq` for its frequency label, and maps that label through
143
+ the cadence table. Anything unmapped — a non-datetime index, an irregular or
144
+ unparseable one, or an exotic frequency such as ``'45T'``/``'5H'``/``'14D'`` —
145
+ falls back to 15. Degenerate inputs (``None``, ragged sequences, or indexes
146
+ ``infer_freq`` rejects) now raise instead of falling back. The result is clamped
147
+ to ``n`` when provided.
148
+
149
+ Args:
150
+ index: External index values (pandas Index/Series, or array-like).
151
+ n (int, optional): Series length used to clamp the inferred window.
152
+
153
+ Returns:
154
+ int: Inferred smoothing window (clamped to ``n`` when given).
155
+ """
156
+ window = _DEFAULT_WINDOW
157
+ dt_index = _as_datetime_index(index)
158
+ if dt_index is not None and len(dt_index) >= 3:
159
+ freq = pd.infer_freq(dt_index)
160
+ label_window = _window_from_label(freq)
161
+ if label_window is not None:
162
+ window = label_window
163
+ return _clamp_window(window, n)
164
+
165
+
166
+ def prep_signal_params(signal_params: dict|None=None, index=None, n: int|None=None) -> dict:
167
+ """
168
+ Merge user-supplied `signal_params` over the defaults and derive window sizes.
169
+
170
+ `window_smooth` is inferred from `index`'s cadence when the user does not
171
+ explicitly set it; an explicit value always wins. The resolved window is then
172
+ clamped to the series length. `window_flat` and `window_noise` are not
173
+ top-level defaults: unless explicitly overridden they derive from the clamped
174
+ `window_smooth`. Every stage downstream assumes this returns a fully-populated
175
+ dict.
176
+
177
+ Args:
178
+ signal_params (dict, optional): User overrides. Unknown keys are forwarded silently.
179
+ index (optional): External index; its cadence infers `window_smooth` when the
180
+ user does not supply one.
181
+ n (int, optional): Series length used to clamp `window_smooth`. Defaults to
182
+ `len(index)` when `index` is given.
183
+
184
+ Returns:
185
+ dict: Fully-populated signal_params with every key the stages read.
186
+ """
187
+ user_params = signal_params or {}
188
+ resolved = {**_SIGNAL_PARAMS_DEFAULTS, **user_params}
189
+
190
+ if n is None and index is not None:
191
+ n = len(index)
192
+
193
+ if 'window_smooth' in user_params:
194
+ # Explicit value wins; still clamp it to a Savitzky-Golay-valid window.
195
+ resolved['window_smooth'] = _clamp_window(resolved['window_smooth'], n)
196
+ elif index is not None:
197
+ resolved['window_smooth'] = infer_window_smooth(index, n)
198
+ else:
199
+ resolved['window_smooth'] = _clamp_window(resolved['window_smooth'], n)
200
+
201
+ # Derive the factor-based windows *after* clamping, and only when the user did not set them explicitly.
202
+ resolved.setdefault('window_flat', int(resolved['window_smooth'] * resolved['smooth_factor']))
203
+ resolved.setdefault('window_noise', int(resolved['window_smooth'] * resolved['noise_factor']))
204
+ return resolved
@@ -216,40 +216,42 @@ def process_signals(df: pd.DataFrame, value_col: str, method_params: dict, signa
216
216
  if debug:
217
217
  import matplotlib.pyplot as plt
218
218
 
219
+ from .io.plot_pytrendy import _show_plot
220
+
219
221
  ax = df[[value_col, 'snr']].plot(figsize=(20,3), secondary_y='snr')
220
222
  ax.right_ax.axhline(y=signal_params['threshold_noise'], color='gray', linestyle='--', linewidth=2)
221
223
  plt.title("Signal-Noise Ratio (SNR)")
222
- plt.show()
224
+ _show_plot()
223
225
 
224
226
  ax = df[[value_col, 'noise_flag']].plot(figsize=(20,3), secondary_y='noise_flag')
225
227
  ax.right_ax.axhline(y=0, color='gray', linestyle='--', linewidth=2)
226
228
  plt.title("Noise Flag")
227
- plt.show()
229
+ _show_plot()
228
230
 
229
231
  ax = df[[value_col, 'smoothed']].plot(figsize=(20,3), secondary_y='smoothed')
230
232
  ax.right_ax.axhline(y=0, color='gray', linestyle='--', linewidth=2)
231
233
  plt.title("Smoothed")
232
- plt.show()
234
+ _show_plot()
233
235
 
234
236
  ax = df[[value_col, 'smoothed_std']].plot(figsize=(20,3), secondary_y='smoothed_std')
235
237
  ax.right_ax.axhline(y=0, color='gray', linestyle='--', linewidth=2)
236
238
  plt.title("Smoothed Std")
237
- plt.show()
239
+ _show_plot()
238
240
 
239
241
  ax = df[[value_col, 'flat_flag']].plot(figsize=(20,3), secondary_y='flat_flag')
240
242
  ax.right_ax.axhline(y=0, color='gray', linestyle='--', linewidth=2)
241
243
  plt.title("Flat Flag")
242
- plt.show()
244
+ _show_plot()
243
245
 
244
246
  ax = df[[value_col, 'smoothed_deriv']].plot(figsize=(20,3), secondary_y='smoothed_deriv')
245
247
  ax.right_ax.axhline(y=derivative_limit, color='gray', linestyle='--', linewidth=2)
246
248
  ax.right_ax.axhline(y=-derivative_limit, color='gray', linestyle=':', linewidth=2)
247
249
  plt.title("Smoothed Derivative")
248
- plt.show()
250
+ _show_plot()
249
251
 
250
252
  ax = df[[value_col, 'trend_flag']].plot(figsize=(20,3), secondary_y='trend_flag')
251
253
  ax.right_ax.axhline(y=0, color='gray', linestyle='--', linewidth=2)
252
254
  plt.title("Trend Flag")
253
- plt.show()
255
+ _show_plot()
254
256
 
255
257
  return df
@@ -1,44 +0,0 @@
1
- """**Signal-Parameter Preparation**
2
-
3
- The signal-processing stages share a common set of constants — smoothing and
4
- rolling windows, grouping distance, and the noise/flat thresholds. ``detect_trends``
5
- is the single public entry point, so this module is the one place those constants
6
- are defaulted before the pipeline runs.
7
-
8
- Defaults are merged with any user-supplied ``signal_params`` overrides. The derived
9
- windows ``window_flat`` and ``window_noise`` are not top-level defaults: unless
10
- explicitly overridden they derive from ``window_smooth``. Every stage downstream
11
- assumes :func:`prep_signal_params` returns a fully-populated dict.
12
- """
13
-
14
- _SIGNAL_PARAMS_DEFAULTS = {
15
- 'window_smooth': 15, # Savitzky-Golay smoothing window, in points.
16
- 'smooth_factor': 0.5, # Fraction of window_smooth spanned by window_flat: raise to widen it (smoother flat baseline, fewer flags), lower to narrow it (more sensitive); scaled to window_smooth so it stays proportional.
17
- 'noise_factor': 0.5, # Fraction of window_smooth spanned by window_noise: raise to widen it (smoother SNR estimate, fewer flags), lower to narrow it (more sensitive); scaled to window_smooth so it stays proportional.
18
- 'grouping_distance': 7, # Maximum gap, in index steps, for grouping nearby segments.
19
- 'min_trend_length': 3, # Minimum length, in steps, for an Up/Down segment to be retained.
20
- 'min_flat_noise_length': 1, # Minimum length, in steps, for a Flat/Noise segment to be retained.
21
- 'threshold_noise': 2.5, # SNR threshold (dB) below which a region is classified as noise.
22
- 'threshold_smooth': 0.001, # Derivative threshold as a fraction of the signal IQR, below which motion counts as flat.
23
- 'threshold_flat': 0.835, # Flat sensitivity as a fraction of the minimum non-zero rolling std.
24
- }
25
-
26
-
27
- def prep_signal_params(signal_params: dict|None=None) -> dict:
28
- """
29
- Merge user-supplied `signal_params` over the defaults and derive window sizes.
30
-
31
- `window_flat` and `window_noise` are not top-level defaults: unless explicitly
32
- overridden they derive from `window_smooth`. Every stage downstream assumes
33
- this returns a fully-populated dict.
34
-
35
- Args:
36
- signal_params (dict, optional): User overrides. Unknown keys are forwarded silently.
37
-
38
- Returns:
39
- dict: Fully-populated signal_params with every key the stages read.
40
- """
41
- resolved = {**_SIGNAL_PARAMS_DEFAULTS, **(signal_params or {})}
42
- resolved.setdefault('window_flat', int(resolved['window_smooth'] * resolved['smooth_factor']))
43
- resolved.setdefault('window_noise', int(resolved['window_smooth'] * resolved['noise_factor']))
44
- return resolved
File without changes
File without changes