cloudsprite 0.11.0__py3-none-any.whl

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 (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,400 @@
1
+ """Passive lowpass LC ladder extraction from SciPy analog prototypes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass, replace
7
+ from itertools import permutations
8
+ from typing import Literal
9
+
10
+ import numpy as np
11
+ from numpy.typing import NDArray
12
+ from scipy import signal
13
+
14
+ from cloudsprite._exceptions import ValidationError
15
+ from cloudsprite._filter_foster import FosterSection, _even_elliptic_sections
16
+ from cloudsprite._link_budget import _positive
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class FilterSection:
21
+ """One ladder branch, ordered from source to load in LowpassFilter.sections.
22
+
23
+ Connection is series (in the signal path) or shunt (to ground). A single
24
+ non-None L/C is an ordinary element. When both are present, resonator tells
25
+ whether they connect in parallel or series WITHIN that branch. Inductance
26
+ is in H and capacitance in F. Normalized values are the corresponding
27
+ elements at 1 rad/s and 1-ohm source, before frequency/impedance scaling.
28
+ """
29
+
30
+ connection: Literal["series", "shunt"]
31
+ resonator: Literal["parallel", "series"] | None
32
+ inductance_h: float | None
33
+ capacitance_f: float | None
34
+ normalized_inductance: float | None
35
+ normalized_capacitance: float | None
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class LowpassFilter:
40
+ """Ideal doubly terminated passive lowpass with explicit physical terminations.
41
+
42
+ Cutoff is in Hz: Butterworth's -3.0103 dB point, or the -ripple_db passband
43
+ edge for Chebyshev/elliptic. Impedances are positive resistances in ohms;
44
+ the specified response requires BOTH returned source/load resistances.
45
+ For ladders, sections describe every element including finite-zero resonators. g_values
46
+ is (g0=1, g1,...,gn, g[n+1]) for all-pole filters, where the last value is
47
+ load resistance for series-first, load conductance for shunt-first.
48
+ Elliptic filters have no ordinary g table here: g_values is None and their
49
+ normalized elements are in sections or foster_sections. No parasitics, finite Q, component
50
+ rounding or physical-layout design is included. realization is ladder for
51
+ Butterworth/Chebyshev and odd elliptic. Even elliptic uses ideal-transformer
52
+ Foster sections: sections is empty, g_values is None, and foster_sections
53
+ specifies every reactive element and transformer. See FosterSection for
54
+ exact series/parallel interconnection and winding polarity conventions.
55
+ """
56
+
57
+ filter_type: Literal["butterworth", "chebyshev", "elliptic"]
58
+ order: int
59
+ cutoff_hz: float
60
+ ripple_db: float | None
61
+ stopband_attenuation_db: float | None
62
+ source_impedance_ohm: float
63
+ load_impedance_ohm: float
64
+ sections: tuple[FilterSection, ...]
65
+ g_values: tuple[float, ...] | None
66
+ realization: Literal["ladder", "foster-impedance", "foster-admittance"] = "ladder"
67
+ foster_sections: tuple[FosterSection, ...] = ()
68
+
69
+
70
+ # Coefficients are descending powers. Remove roundoff only at the leading edge,
71
+ # where element extraction deliberately cancels the highest power.
72
+ def _trim(p: np.poly1d) -> np.poly1d:
73
+ a = np.asarray(p.c, dtype=float)
74
+ threshold = 1e-9 * max(float(np.max(np.abs(a))), 1e-100)
75
+ while len(a) > 1 and abs(a[0]) < threshold:
76
+ a = a[1:]
77
+ return np.poly1d(a)
78
+
79
+
80
+ def _divide(p: np.poly1d, q: np.poly1d) -> np.poly1d:
81
+ quotient, remainder = np.polydiv(p, q)
82
+ if np.max(np.abs(remainder.c)) > 1e-7 * max(float(np.max(np.abs(p.c))), 1e-100):
83
+ raise ValidationError("LC extraction is numerically ill-conditioned for this prototype.")
84
+ return _trim(quotient)
85
+
86
+
87
+ def _positive_value(value: float) -> float:
88
+ if not math.isfinite(value) or value <= 0:
89
+ raise ValidationError("Prototype does not admit a positive LC extraction in this ordering.")
90
+ return value
91
+
92
+
93
+ def _driving_point(numerator: np.poly1d, denominator: np.poly1d, order: int) -> tuple[np.poly1d, np.poly1d]:
94
+ # Losslessness: F(s)F(-s)=E(s)E(-s)-P(s)P(-s), with S21=P/E.
95
+ # F has order parity, so (-1)^order times this polynomial is F(s)^2.
96
+ # Recover its square root by coefficients, avoiding double-root splitting.
97
+ minus_s = np.poly1d([-1, 0])
98
+ square = (denominator * denominator(minus_s) - numerator * numerator(minus_s)) * (-1) ** order
99
+ reflection = np.zeros(order + 1)
100
+ reflection[0] = math.sqrt(float(square[2 * order]))
101
+ for i in range(1, order + 1):
102
+ reflection[i] = (square[2 * order - i] - sum(reflection[j] * reflection[i - j] for j in range(1, i))) / (
103
+ 2 * reflection[0]
104
+ )
105
+ reflection[1::2] = 0 # analytic parity, suppress coefficient roundoff
106
+ f = np.poly1d(reflection)
107
+ return _trim(denominator + f), _trim(denominator - f)
108
+
109
+
110
+ def _elliptic_sections(
111
+ numerator: np.poly1d, denominator: np.poly1d, zeros: tuple[float, ...]
112
+ ) -> list[tuple[float | None, float | None]]:
113
+ # Shunt-first extraction. Partial C removal places a Y zero at jwz;
114
+ # inversion exposes a Z pole, removed as K*s/(s²+wz²) = parallel LC.
115
+ n, d = numerator, denominator
116
+ elements: list[tuple[float | None, float | None]] = []
117
+ for w in zeros:
118
+ s, factor = 1j * w, np.poly1d([1, 0, w * w])
119
+ c = _positive_value(float((n(s) / d(s) / s).real))
120
+ elements.append((None, c))
121
+ residual = _divide(_trim(n - np.poly1d([c, 0]) * d), factor)
122
+ n, d = d, residual
123
+ k = _positive_value(float((n(s) / (s * d(s))).real))
124
+ elements.append((k / w**2, 1 / k))
125
+ residual = _divide(_trim(n - np.poly1d([k, 0]) * d), factor)
126
+ n, d = d, residual
127
+ c = _positive_value(float(n.c[0] / d.c[0]))
128
+ elements.append((None, c))
129
+ remainder = _trim(n - np.poly1d([c, 0]) * d)
130
+ if remainder.order != 0 or d.order != 0 or not math.isclose(float(remainder.c[0] / d.c[0]), 1, rel_tol=1e-6):
131
+ raise ValidationError("Elliptic extraction did not terminate in the required unit conductance.")
132
+ return elements
133
+
134
+
135
+ def _verify_response(
136
+ sections: tuple[FilterSection, ...],
137
+ source: float,
138
+ load: float,
139
+ numerator: np.poly1d,
140
+ denominator: np.poly1d,
141
+ ) -> None:
142
+ # Independent ABCD reconstruction guards polynomial cancellation at extreme
143
+ # orders/ripples. Use normalized elements to avoid dimensional conditioning.
144
+ w = np.concatenate((np.linspace(0, 1, 101), np.geomspace(1.001, 100, 160)))
145
+ s = 1j * w
146
+ a, b, c, d = (
147
+ np.ones(len(w), complex),
148
+ np.zeros(len(w), complex),
149
+ np.zeros(len(w), complex),
150
+ np.ones(len(w), complex),
151
+ )
152
+ for section in sections:
153
+ inductance, cap = section.normalized_inductance, section.normalized_capacitance
154
+ if section.connection == "series":
155
+ assert inductance is not None
156
+ z = s * inductance if cap is None else s * inductance / (1 + s * s * inductance * cap)
157
+ b, d = a * z + b, c * z + d
158
+ else:
159
+ assert cap is not None
160
+ y = s * cap if inductance is None else s * cap / (1 + s * s * inductance * cap)
161
+ a, c = a + b * y, c + d * y
162
+ r = load / source
163
+ actual = np.abs(2 * math.sqrt(r) / (a * r + b + c * r + d))
164
+ expected = np.abs(numerator(s) / denominator(s))
165
+ if not np.allclose(actual, expected, atol=2e-7, rtol=2e-6):
166
+ raise ValidationError(
167
+ "LC extraction failed response verification; use a lower order or less extreme ripple/attenuation."
168
+ )
169
+
170
+
171
+ def _analog_prototype(
172
+ filter_type: str,
173
+ order: int,
174
+ ripple_db: float | None,
175
+ stopband_attenuation_db: float | None,
176
+ ) -> tuple[NDArray[np.complex128], NDArray[np.complex128], float]:
177
+ if filter_type == "butterworth":
178
+ if ripple_db is not None or stopband_attenuation_db is not None:
179
+ raise ValidationError("Butterworth has no ripple/stopband parameters.")
180
+ z, p, k = signal.buttap(order)
181
+ else:
182
+ if ripple_db is None:
183
+ raise ValidationError("ripple_db is required for Chebyshev/elliptic.")
184
+ _positive(ripple_db=ripple_db)
185
+ if filter_type == "chebyshev":
186
+ if stopband_attenuation_db is not None:
187
+ raise ValidationError("stopband_attenuation_db applies only to elliptic filters.")
188
+ z, p, k = signal.cheb1ap(order, ripple_db)
189
+ else:
190
+ if (
191
+ stopband_attenuation_db is None
192
+ or not math.isfinite(stopband_attenuation_db)
193
+ or stopband_attenuation_db <= ripple_db
194
+ ):
195
+ raise ValidationError("Elliptic stopband_attenuation_db must be finite and exceed ripple_db.")
196
+ z, p, k = signal.ellipap(order, ripple_db, stopband_attenuation_db)
197
+ return np.atleast_1d(z).astype(complex), np.atleast_1d(p).astype(complex), float(k)
198
+
199
+
200
+ def _all_pole_sections(
201
+ n: np.poly1d,
202
+ d: np.poly1d,
203
+ order: int,
204
+ ) -> tuple[list[tuple[float | None, float | None]], float, tuple[float, ...]]:
205
+ elements: list[tuple[float | None, float | None]] = []
206
+ values = []
207
+ for i in range(order):
208
+ if n.order != d.order + 1:
209
+ raise ValidationError("Prototype is ill-conditioned for LC extraction.")
210
+ value = _positive_value(float(n.c[0] / d.c[0]))
211
+ values.append(value)
212
+ elements.append((None, value) if i % 2 == 0 else (value, None))
213
+ remainder = n - np.poly1d([value, 0]) * d
214
+ degree = max(d.order - 1, 0)
215
+ # Lossless extraction has no constant series R/shunt G until
216
+ # the termination. Discard only the analytically canceled terms.
217
+ if np.max(np.abs(remainder.c[: -(degree + 1)]), initial=0) > 1e-6 * np.max(np.abs(n.c)):
218
+ raise ValidationError("Prototype cancellation is numerically ill-conditioned.")
219
+ n, d = d, np.poly1d(remainder.c[-(degree + 1) :])
220
+ if n.order != 0 or d.order != 0:
221
+ raise ValidationError("Prototype did not terminate in a real resistance.")
222
+ # Extraction began with admittance. Account for inversion parity.
223
+ conductance = _positive_value(float(n.c[0] / d.c[0]) if order % 2 == 0 else float(d.c[0] / n.c[0]))
224
+ termination = 1 / conductance
225
+ g_values = (1.0, *values, conductance)
226
+ return elements, termination, g_values
227
+
228
+
229
+ def _normalized_sections(
230
+ filter_type: str,
231
+ order: int,
232
+ zpk: tuple[NDArray[np.complex128], NDArray[np.complex128], float],
233
+ ) -> tuple[list[tuple[float | None, float | None]], float, tuple[float, ...] | None, np.poly1d, np.poly1d]:
234
+ z, p, k = zpk
235
+ num, den = (np.poly1d(v) for v in signal.zpk2tf(z, p, k))
236
+ if not np.all(np.isfinite(num.c)) or not np.all(np.isfinite(den.c)):
237
+ raise ValidationError("Prototype coefficients exceed floating-point range.")
238
+ if filter_type != "butterworth":
239
+ n, d = _driving_point(num, den, order)
240
+ elements: list[tuple[float | None, float | None]] = []
241
+ g_values = None
242
+ if filter_type == "butterworth":
243
+ # SciPy orders the unit-circle poles so g[k] = -2*Re(p[k]);
244
+ # this is 2*sin((2*k-1)*pi/(2*n)), without table lookup or
245
+ # cancellation-prone high-order continued fractions.
246
+ values = [-2 * float(v.real) for v in p]
247
+ elements = [(None, v) if i % 2 == 0 else (v, None) for i, v in enumerate(values)]
248
+ termination = 1.0
249
+ g_values = (1.0, *values, 1.0)
250
+ elif filter_type == "elliptic":
251
+ zeros = sorted((float(v.imag) for v in z if v.imag > 0), reverse=True)
252
+ for ordering in permutations(zeros):
253
+ try:
254
+ elements = _elliptic_sections(n, d, ordering)
255
+ break
256
+ except ValidationError:
257
+ continue
258
+ if not elements:
259
+ raise ValidationError("No positive, numerically stable elliptic ladder extraction found.")
260
+ termination = 1.0
261
+ else:
262
+ elements, termination, g_values = _all_pole_sections(n, d, order)
263
+ return elements, termination, g_values, num, den
264
+
265
+
266
+ def _scale_sections(
267
+ elements: list[tuple[float | None, float | None]],
268
+ first_element: Literal["series", "shunt"],
269
+ source_impedance_ohm: float,
270
+ cutoff_hz: float,
271
+ ) -> tuple[FilterSection, ...]:
272
+ omega = 2 * math.pi * cutoff_hz
273
+ sections = []
274
+ for i, (inductance, cap) in enumerate(elements):
275
+ connection: Literal["series", "shunt"] = (
276
+ first_element if i % 2 == 0 else ("shunt" if first_element == "series" else "series")
277
+ )
278
+ resonator: Literal["parallel", "series"] | None = None
279
+ if inductance is not None and cap is not None:
280
+ resonator = "parallel" if connection == "series" else "series"
281
+ sections.append(
282
+ FilterSection(
283
+ connection,
284
+ resonator,
285
+ None if inductance is None else _positive_value(inductance * source_impedance_ohm / omega),
286
+ None if cap is None else _positive_value(cap / source_impedance_ohm / omega),
287
+ inductance,
288
+ cap,
289
+ )
290
+ )
291
+ return tuple(sections)
292
+
293
+
294
+ def lowpass_filter(
295
+ filter_type: Literal["butterworth", "chebyshev", "elliptic"],
296
+ order: int,
297
+ cutoff_hz: float,
298
+ *,
299
+ ripple_db: float | None = None,
300
+ stopband_attenuation_db: float | None = None,
301
+ source_impedance_ohm: float = 50.0,
302
+ load_impedance_ohm: float | None = None,
303
+ first_element: Literal["series", "shunt"] = "series",
304
+ ) -> LowpassFilter:
305
+ """Synthesize and scale an ideal passive lowpass circuit from a SciPy prototype.
306
+
307
+ Args:
308
+ filter_type: Butterworth, Chebyshev type I, or elliptic.
309
+ order: Integer 1..12, including even elliptic. The bound limits
310
+ polynomial conditioning and finite-zero ordering search. Ill-conditioned
311
+ combinations raise ValidationError rather than returning invalid parts.
312
+ cutoff_hz: Positive cutoff/passband-edge frequency in Hz.
313
+ ripple_db: Positive passband ripple for Chebyshev/elliptic; omit for Butterworth.
314
+ stopband_attenuation_db: Required for elliptic, strictly above ripple_db.
315
+ Omit for other types. Specifies minimum stopband attenuation in dB.
316
+ source_impedance_ohm: Positive real source resistance in ohms.
317
+ load_impedance_ohm: Positive real load resistance, or None to select the
318
+ prototype's required termination. Butterworth and odd-order designs
319
+ require equal terminations; even Chebyshev requires unequal ones.
320
+ Even elliptic uses an equal-termination Foster realization.
321
+ An incompatible explicit load raises ValidationError; impedance
322
+ scaling cannot independently choose both terminations.
323
+ first_element: Series inductor first or the dual shunt capacitor first
324
+ for ladders. For even elliptic, selects foster-impedance (series)
325
+ or its foster-admittance dual (shunt); this is NOT a ladder.
326
+
327
+ Returns:
328
+ LowpassFilter with normalized and scaled values: L=Rsource*Ln/(2*pi*fc),
329
+ C=Cn/(Rsource*2*pi*fc). Uses scipy.signal.buttap/cheb1ap/ellipap,
330
+ lossless reflection-polynomial construction and Cauer element extraction
331
+ (Steer, Microwave and RF Design IV, section 2.6). Elliptic finite zeros
332
+ become shunt series-LC or series parallel-LC resonators, not an all-pole
333
+ ladder approximation. Even elliptic uses a passive LC Foster two-port
334
+ with explicit ideal transformers and equal terminations. Both dual
335
+ forms realize the same power response; their S21 phases differ by pi.
336
+ Inspect realization and foster_sections before building the circuit.
337
+ """
338
+ if isinstance(order, bool) or not isinstance(order, int) or not 1 <= order <= 12:
339
+ raise ValidationError("order must be an integer from 1 through 12.")
340
+ if filter_type not in ("butterworth", "chebyshev", "elliptic") or first_element not in ("series", "shunt"):
341
+ raise ValidationError("Unknown filter_type or first_element.")
342
+ _positive(cutoff_hz=cutoff_hz, source_impedance_ohm=source_impedance_ohm)
343
+ if load_impedance_ohm is not None:
344
+ _positive(load_impedance_ohm=load_impedance_ohm)
345
+ try:
346
+ with np.errstate(over="raise", invalid="raise", divide="raise"):
347
+ zpk = _analog_prototype(filter_type, order, ripple_db, stopband_attenuation_db)
348
+ if filter_type == "elliptic" and order % 2 == 0:
349
+ design = LowpassFilter(
350
+ filter_type,
351
+ order,
352
+ cutoff_hz,
353
+ ripple_db,
354
+ stopband_attenuation_db,
355
+ source_impedance_ohm,
356
+ source_impedance_ohm if load_impedance_ohm is None else load_impedance_ohm,
357
+ (),
358
+ None,
359
+ )
360
+ return _even_elliptic_filter(design, zpk, first_element)
361
+ elements, termination, g_values, num, den = _normalized_sections(filter_type, order, zpk)
362
+ except (FloatingPointError, OverflowError, ZeroDivisionError, np.linalg.LinAlgError) as exc:
363
+ raise ValidationError("Prototype parameters are outside the numerically supported range.") from exc
364
+ if first_element == "series":
365
+ elements = [(cap, inductance) for inductance, cap in elements]
366
+ termination = 1 / termination
367
+ required_load = source_impedance_ohm * termination
368
+ if load_impedance_ohm is not None and not math.isclose(load_impedance_ohm, required_load, rel_tol=1e-7):
369
+ raise ValidationError(
370
+ f"This prototype requires load_impedance_ohm={required_load:.12g}; omit the load to select it automatically."
371
+ )
372
+ result = _scale_sections(elements, first_element, source_impedance_ohm, cutoff_hz)
373
+ _verify_response(result, source_impedance_ohm, required_load, num, den)
374
+ return LowpassFilter(
375
+ filter_type,
376
+ order,
377
+ cutoff_hz,
378
+ ripple_db,
379
+ stopband_attenuation_db,
380
+ source_impedance_ohm,
381
+ required_load,
382
+ result,
383
+ g_values,
384
+ )
385
+
386
+
387
+ def _even_elliptic_filter(
388
+ design: LowpassFilter,
389
+ zpk: tuple[NDArray[np.complex128], NDArray[np.complex128], float],
390
+ first: Literal["series", "shunt"],
391
+ ) -> LowpassFilter:
392
+ if not math.isclose(design.load_impedance_ohm, design.source_impedance_ohm, rel_tol=1e-7):
393
+ raise ValidationError("Even elliptic Foster realization requires equal source/load resistances.")
394
+ sections = _even_elliptic_sections(zpk, design.source_impedance_ohm, design.cutoff_hz, first)
395
+ return replace(
396
+ design,
397
+ load_impedance_ohm=design.source_impedance_ohm,
398
+ realization="foster-impedance" if first == "series" else "foster-admittance",
399
+ foster_sections=sections,
400
+ )
@@ -0,0 +1,134 @@
1
+ """Glob/regex detection and filter expression support."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import re
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+
11
+ def is_glob(s: str) -> bool:
12
+ """Check if a string contains glob characters (* or ?)."""
13
+ return "*" in s or "?" in s
14
+
15
+
16
+ @dataclass
17
+ class GlobPattern:
18
+ """Glob pattern matcher using fnmatch."""
19
+
20
+ pattern: str
21
+
22
+ def matches(self, value: str) -> bool:
23
+ return fnmatch.fnmatch(value, self.pattern)
24
+
25
+
26
+ @dataclass
27
+ class RegexPattern:
28
+ """Regex pattern matcher."""
29
+
30
+ pattern: str
31
+
32
+ def __post_init__(self) -> None:
33
+ self._compiled = re.compile(self.pattern)
34
+
35
+ def matches(self, value: str) -> bool:
36
+ return bool(self._compiled.search(value))
37
+
38
+
39
+ def regex(pattern: str) -> RegexPattern:
40
+ """Create a regex pattern for use in bracket notation.
41
+
42
+ Usage: cs.projects[cs.regex(r"cable-qual-\\d+")]
43
+ """
44
+ return RegexPattern(pattern)
45
+
46
+
47
+ def parse_bracket_arg(arg: Any) -> Any:
48
+ """Parse a bracket argument into a plain string, GlobPattern, or RegexPattern."""
49
+ if isinstance(arg, RegexPattern):
50
+ return arg
51
+ if isinstance(arg, str):
52
+ if is_glob(arg):
53
+ return GlobPattern(arg)
54
+ return arg # plain string = exact match
55
+ return arg # FilterExpression or other (handled by caller)
56
+
57
+
58
+ class FieldProxy:
59
+ """Proxy for building parameter filter expressions — not a normal value type.
60
+
61
+ Usage::
62
+
63
+ cs.params.temp > 25
64
+ cs.params.dut == "cable-A"
65
+
66
+ **Not a normal value type.** Comparison operators (``==``, ``>``, ``<``)
67
+ build :class:`FilterExpression` objects for the query DSL; they do **not**
68
+ return ``bool``. Consequently:
69
+
70
+ * ``x in some_list`` and ``assert a == b`` will not behave as expected
71
+ when ``a`` / ``x`` is a :class:`FieldProxy`.
72
+ * ``__hash__`` is ``None``, so putting a proxy in a ``set`` or ``dict``
73
+ key raises immediately rather than failing silently.
74
+
75
+ This is an intentional, documented trade for the RF-engineer-facing
76
+ ``cs.params.temp > 25`` syntax.
77
+ """
78
+
79
+ # Disable hashing — FieldProxy instances are DSL expression builders, not hashable values.
80
+ # This prevents silent bugs when someone tries to put FieldProxy in a set/dict.
81
+ __hash__ = None # type: ignore[assignment]
82
+
83
+ def __init__(self, field_name: str | None = None):
84
+ self._field = field_name
85
+
86
+ def __getattr__(self, name: str) -> FieldProxy:
87
+ if name.startswith("_"):
88
+ raise AttributeError(name)
89
+ return FieldProxy(name)
90
+
91
+ def __gt__(self, other: Any) -> FilterExpression:
92
+ return FilterExpression(self._field, "gt", other)
93
+
94
+ def __lt__(self, other: Any) -> FilterExpression:
95
+ return FilterExpression(self._field, "lt", other)
96
+
97
+ def __eq__(self, other: Any) -> FilterExpression: # type: ignore[override]
98
+ # Intentional: returns FilterExpression, not bool (object.__eq__ contract).
99
+ # Documented in the class docstring; do not "fix" by returning bool.
100
+ # Narrow ignore only — do not loosen mypy globally for this site.
101
+ return FilterExpression(self._field, "eq", other)
102
+
103
+ def matches(self, pattern: str) -> FilterExpression:
104
+ """Match ``field`` against a regex/glob-style pattern."""
105
+ return FilterExpression(self._field, "matches", pattern)
106
+
107
+
108
+ @dataclass
109
+ class FilterExpression:
110
+ """A filter condition on a parameter field."""
111
+
112
+ field: str | None
113
+ operator: str
114
+ value: Any
115
+
116
+ def evaluate(self, params: dict[str, Any]) -> bool:
117
+ if self.field is None:
118
+ return False
119
+ actual = params.get(self.field)
120
+ if actual is None:
121
+ return False
122
+ if self.operator == "gt":
123
+ return float(actual) > float(self.value)
124
+ if self.operator == "lt":
125
+ return float(actual) < float(self.value)
126
+ if self.operator == "eq":
127
+ return str(actual) == str(self.value)
128
+ if self.operator == "matches":
129
+ return bool(re.search(str(self.value), str(actual)))
130
+ return False
131
+
132
+
133
+ # Singleton for cs.params
134
+ params = FieldProxy()