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,99 @@
1
+ """Scalar far-field free-space link calculations in explicit SI/dB units."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+
8
+ from cloudsprite._exceptions import ValidationError
9
+
10
+ _C = 299792458.0
11
+
12
+
13
+ def _finite(**values: float) -> None:
14
+ for name, value in values.items():
15
+ if not math.isfinite(value):
16
+ raise ValidationError(f"{name} must be finite.")
17
+
18
+
19
+ def _positive(**values: float) -> None:
20
+ _finite(**values)
21
+ for name, value in values.items():
22
+ if value <= 0:
23
+ raise ValidationError(f"{name} must be positive.")
24
+
25
+
26
+ def free_space_path_loss(frequency_hz: float, distance_m: float) -> float:
27
+ """Return Friis free-space path loss in dB: 20 log10(4 pi distance / wavelength).
28
+
29
+ Args:
30
+ frequency_hz: Positive finite frequency in hertz.
31
+ distance_m: Positive finite separation in metres.
32
+
33
+ Returns:
34
+ Isotropic path loss in dB. Assumes unobstructed far-field propagation;
35
+ antenna size is unknown, so the caller must ensure the far-field condition.
36
+ At 1 GHz and 1 km, loss is approximately 92.45 dB.
37
+ """
38
+ _positive(frequency_hz=frequency_hz, distance_m=distance_m)
39
+ return 20 * (math.log10(4 * math.pi / _C) + math.log10(frequency_hz) + math.log10(distance_m))
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class LinkBudget:
44
+ """Link results: path_loss_db, eirp_dbm, received_power_dbm and fade_margin_db.
45
+
46
+ Fade margin is received power minus sensitivity; positive means available
47
+ headroom. EIRP includes transmit feed loss, before propagation losses.
48
+ """
49
+
50
+ path_loss_db: float
51
+ eirp_dbm: float
52
+ received_power_dbm: float
53
+ fade_margin_db: float
54
+
55
+
56
+ def link_budget(
57
+ transmit_power_dbm: float,
58
+ transmit_gain_dbi: float,
59
+ receive_gain_dbi: float,
60
+ frequency_hz: float,
61
+ distance_m: float,
62
+ receiver_sensitivity_dbm: float,
63
+ *,
64
+ transmit_loss_db: float = 0.0,
65
+ receive_loss_db: float = 0.0,
66
+ additional_loss_db: float = 0.0,
67
+ ) -> LinkBudget:
68
+ """Calculate EIRP, received power and fade margin for a free-space link.
69
+
70
+ Args:
71
+ transmit_power_dbm: Transmitter output power in dBm.
72
+ transmit_gain_dbi: Transmit antenna gain towards the receiver, in dBi.
73
+ receive_gain_dbi: Receive antenna gain towards the transmitter, in dBi.
74
+ frequency_hz: Positive finite carrier frequency in Hz.
75
+ distance_m: Positive finite antenna separation in metres (far field).
76
+ receiver_sensitivity_dbm: Receiver threshold at the chosen operating mode.
77
+ transmit_loss_db: Nonnegative transmit feed loss in dB.
78
+ receive_loss_db: Nonnegative receive feed loss in dB.
79
+ additional_loss_db: Nonnegative extra path/polarization loss in dB.
80
+
81
+ Returns:
82
+ LinkBudget in dB/dBm. Assumes aligned polarization unless included in
83
+ additional_loss_db. Does not predict fading statistics or availability.
84
+ """
85
+ _finite(
86
+ transmit_power_dbm=transmit_power_dbm,
87
+ transmit_gain_dbi=transmit_gain_dbi,
88
+ receive_gain_dbi=receive_gain_dbi,
89
+ receiver_sensitivity_dbm=receiver_sensitivity_dbm,
90
+ transmit_loss_db=transmit_loss_db,
91
+ receive_loss_db=receive_loss_db,
92
+ additional_loss_db=additional_loss_db,
93
+ )
94
+ if min(transmit_loss_db, receive_loss_db, additional_loss_db) < 0:
95
+ raise ValidationError("Losses must be nonnegative.")
96
+ loss = free_space_path_loss(frequency_hz, distance_m)
97
+ eirp = transmit_power_dbm + transmit_gain_dbi - transmit_loss_db
98
+ received = eirp - loss + receive_gain_dbi - receive_loss_db - additional_loss_db
99
+ return LinkBudget(loss, eirp, received, received - receiver_sensitivity_dbm)
@@ -0,0 +1,53 @@
1
+ """Structured logging for CloudSprite SDK.
2
+
3
+ Provides audit-grade logging of security-relevant and state-changing operations.
4
+ Users can configure the log level via standard Python logging:
5
+
6
+ import logging
7
+ logging.getLogger("cloudsprite").setLevel(logging.DEBUG)
8
+
9
+ By default, the SDK logs at WARNING level (minimal noise). Set to INFO for
10
+ operational visibility or DEBUG for full request tracing.
11
+
12
+ SOC 2 CC7.2: All security-relevant events are logged at INFO level.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+
19
+ # Single logger for the entire SDK — users configure via logging.getLogger("cloudsprite")
20
+ logger = logging.getLogger("cloudsprite")
21
+
22
+ # Default: no output unless user configures logging
23
+ # This follows the library best practice of not adding handlers
24
+ # (the application owner decides where logs go)
25
+ logger.addHandler(logging.NullHandler())
26
+
27
+
28
+ def log_auth_event(event: str, **kwargs: object) -> None:
29
+ """Log an authentication event (connect, refresh, failure)."""
30
+ logger.info("auth.%s %s", event, _format_kwargs(kwargs))
31
+
32
+
33
+ def log_mutation(resource: str, operation: str, resource_id: str = "", **kwargs: object) -> None:
34
+ """Log a state-changing operation (create, update, delete, upload)."""
35
+ logger.info(
36
+ "mutation.%s.%s resource_id=%s %s",
37
+ resource,
38
+ operation,
39
+ resource_id,
40
+ _format_kwargs(kwargs),
41
+ )
42
+
43
+
44
+ def log_ws_event(event: str, **kwargs: object) -> None:
45
+ """Log a WebSocket lifecycle event (connect, send, receive, timeout)."""
46
+ logger.info("ws.%s %s", event, _format_kwargs(kwargs))
47
+
48
+
49
+ def _format_kwargs(kwargs: dict[str, object]) -> str:
50
+ """Format kwargs as key=value pairs for structured logging."""
51
+ if not kwargs:
52
+ return ""
53
+ return " ".join(f"{k}={v}" for k, v in kwargs.items() if v is not None)
@@ -0,0 +1,49 @@
1
+ """Single-ended to mixed-mode conversions on scikit-rf networks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import numpy as np
8
+
9
+ from cloudsprite._exceptions import ValidationError
10
+ from cloudsprite._rf_network import NetworkInput, _network
11
+
12
+ if TYPE_CHECKING:
13
+ from skrf import Network
14
+
15
+
16
+ def single_ended_to_sdd11(network: NetworkInput, positive_port: int = 0, negative_port: int = 1) -> Network:
17
+ """Differential-to-differential reflection of one single-ended port pair.
18
+
19
+ ``SDD11 = 0.5 * (S_pp - S_pn - S_np + S_nn)`` (Bockelman; matches scikit-rf
20
+ ``se2gmm`` for the pair). Ports are zero-based, matching ``SParameterMetrics``.
21
+
22
+ Args:
23
+ network: Two-or-more-port scikit-rf Network or local Touchstone path.
24
+ positive_port: Zero-based port forming the positive leg of the pair.
25
+ negative_port: Zero-based port forming the negative leg of the pair.
26
+
27
+ Returns:
28
+ New one-port Network on the same frequencies whose reference impedance is
29
+ the sum of the pair's (real) reference impedances (100 ohm for 50/50).
30
+ Input is unchanged. Requires ``pip install cloudsprite[rf]``.
31
+
32
+ Raises:
33
+ ValidationError: Fewer than two ports, bad port indices, or unequal
34
+ reference impedances across the pair.
35
+ """
36
+ import skrf
37
+
38
+ n = _network(network)
39
+ p, m = positive_port, negative_port
40
+ if n.nports < 2:
41
+ raise ValidationError("SDD11 conversion needs at least a two-port network.")
42
+ if p == m or not (0 <= p < n.nports and 0 <= m < n.nports):
43
+ raise ValidationError(f"Port pair ({p}, {m}) must be two distinct zero-based ports of a {n.nports}-port.")
44
+ z0 = np.real(np.asarray(n.z0)[:, [p, m]])
45
+ if not np.allclose(z0[:, 0], z0[:, 1]):
46
+ raise ValidationError("Differential pair ports must share one reference impedance.")
47
+ s = n.s
48
+ sdd11 = 0.5 * (s[:, p, p] - s[:, p, m] - s[:, m, p] + s[:, m, m])
49
+ return skrf.Network(frequency=n.frequency, s=sdd11.reshape(-1, 1, 1), z0=2.0 * z0[:, 0])
@@ -0,0 +1,193 @@
1
+ """Independent component-tolerance sampling with compact response statistics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import dataclass
8
+ from typing import Literal
9
+
10
+ import numpy as np
11
+ from numpy.typing import ArrayLike, NDArray
12
+
13
+ from cloudsprite._exceptions import ValidationError
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ComponentTolerance:
18
+ """Relative tolerance: fraction=0.05 means 5% of abs(nominal).
19
+
20
+ Uniform samples span nominal +/- fraction*abs(nominal). For Gaussian
21
+ samples that quantity is ONE standard deviation, not a hard bound or a
22
+ three-sigma limit. Gaussian samples are unbounded and are not clipped;
23
+ the caller's response must handle the resulting component domain. A
24
+ zero nominal or zero fraction remains constant. Components are independent.
25
+ """
26
+
27
+ fraction: float
28
+ distribution: Literal["uniform", "gaussian"] = "uniform"
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MonteCarloSummary:
33
+ """Statistics in the caller's response units, with no raw sample array.
34
+
35
+ Mean, std and p5/p50/p95 have the response shape (0-D arrays for a scalar).
36
+ Std is the sample standard deviation (ddof=1); percentiles use numpy's
37
+ linear interpolation. Arrays are independent of caller data. Sample count
38
+ counts complete trials. Passed/failed and yield_fraction are None without
39
+ a spec; otherwise each trial passes only when EVERY response element is
40
+ within the inclusive bounds. Yield is a fraction in [0,1], not a percent.
41
+ This models independent tolerances, not correlated process variation or
42
+ a confidence interval on manufacturing yield.
43
+ """
44
+
45
+ sample_count: int
46
+ mean: NDArray[np.float64]
47
+ std: NDArray[np.float64]
48
+ p5: NDArray[np.float64]
49
+ p50: NDArray[np.float64]
50
+ p95: NDArray[np.float64]
51
+ passed: int | None
52
+ failed: int | None
53
+ yield_fraction: float | None
54
+
55
+
56
+ def _response_array(value: ArrayLike, name: str) -> NDArray[np.float64]:
57
+ try:
58
+ raw = np.asarray(value)
59
+ if np.iscomplexobj(raw) or raw.dtype.kind not in "fiu":
60
+ raise ValueError
61
+ result = np.array(raw, dtype=np.float64, copy=True)
62
+ if result.size == 0 or not np.all(np.isfinite(result)):
63
+ raise ValueError
64
+ return result
65
+ except (ValueError, TypeError) as exc:
66
+ raise ValidationError(f"{name} must contain finite real numeric values.") from exc
67
+
68
+
69
+ def _component_inputs(
70
+ nominal: Mapping[str, float],
71
+ tolerances: Mapping[str, ComponentTolerance],
72
+ ) -> tuple[list[str], NDArray[np.float64], list[ComponentTolerance]]:
73
+ if any(not isinstance(name, str) or not name for name in nominal):
74
+ raise ValidationError("Use nonempty string component names.")
75
+ names = sorted(nominal)
76
+ if any(not isinstance(name, str) or not name for name in names) or set(tolerances) - set(names):
77
+ raise ValidationError("Use nonempty string component names and tolerances for known components.")
78
+ values = _response_array([nominal[name] for name in names], "nominal")
79
+ if values.ndim != 1:
80
+ raise ValidationError("Each nominal component must be a real scalar.")
81
+ specs: list[ComponentTolerance] = []
82
+ for name, value in zip(names, values):
83
+ spec = tolerances.get(name, ComponentTolerance(0))
84
+ if (
85
+ not isinstance(spec, ComponentTolerance)
86
+ or not math.isfinite(spec.fraction)
87
+ or spec.fraction < 0
88
+ or spec.distribution not in ("uniform", "gaussian")
89
+ or not math.isfinite(abs(float(value)) * spec.fraction)
90
+ ):
91
+ raise ValidationError("Tolerance fractions must be finite and nonnegative; distribution uniform/gaussian.")
92
+ specs.append(spec)
93
+ return names, values, specs
94
+
95
+
96
+ def _summarize(
97
+ samples: NDArray[np.float64],
98
+ lower: NDArray[np.float64] | None,
99
+ upper: NDArray[np.float64] | None,
100
+ ) -> MonteCarloSummary:
101
+ sample_count = len(samples)
102
+ mean, std = np.asarray(samples.mean(axis=0)), np.asarray(samples.std(axis=0, ddof=1))
103
+ if not np.all(np.isfinite(mean)) or not np.all(np.isfinite(std)):
104
+ raise ValidationError("Response statistics exceed floating-point range.")
105
+ p5, p50, p95 = np.percentile(samples, [5, 50, 95], axis=0)
106
+ passed = None
107
+ if lower is not None or upper is not None:
108
+ mask = np.ones(samples.shape, dtype=bool)
109
+ if lower is not None:
110
+ mask &= samples >= lower
111
+ if upper is not None:
112
+ mask &= samples <= upper
113
+ passed = int(np.all(mask.reshape(sample_count, -1), axis=1).sum())
114
+ return MonteCarloSummary(
115
+ sample_count,
116
+ mean,
117
+ std,
118
+ np.asarray(p5),
119
+ np.asarray(p50),
120
+ np.asarray(p95),
121
+ passed,
122
+ None if passed is None else sample_count - passed,
123
+ None if passed is None else passed / sample_count,
124
+ )
125
+
126
+
127
+ def monte_carlo_yield(
128
+ response: Callable[[dict[str, float]], ArrayLike],
129
+ nominal: Mapping[str, float],
130
+ tolerances: Mapping[str, ComponentTolerance],
131
+ *,
132
+ sample_count: int = 1000,
133
+ seed: int | None = None,
134
+ lower_limit: ArrayLike | None = None,
135
+ upper_limit: ArrayLike | None = None,
136
+ ) -> MonteCarloSummary:
137
+ """Sample a caller-supplied response and summarize its tolerance/yield distribution.
138
+
139
+ Args:
140
+ response: Called once per trial with a fresh component dict. Must return
141
+ a finite real scalar or nonempty array of the same shape each time.
142
+ Exceptions propagate unchanged; samples are never silently dropped.
143
+ nominal: Nonempty mapping of component names to finite real values.
144
+ tolerances: Per-component relative tolerances. Missing names stay fixed;
145
+ unknown names are rejected. Gaussian fraction denotes one sigma.
146
+ sample_count: Integer >=2, default 1000. Memory is O(count*response size)
147
+ for exact percentiles; callers should choose compact responses.
148
+ seed: Nonnegative integer for an isolated numpy default_rng, or None.
149
+ Global numpy RNG state and input mappings are not modified.
150
+ lower_limit: Optional inclusive scalar or response-broadcastable lower bound.
151
+ upper_limit: Optional inclusive scalar or response-broadcastable upper bound.
152
+
153
+ Returns:
154
+ MonteCarloSummary, with elementwise statistics and whole-trial yield.
155
+ For raw samples in a standalone CloudScript, use a local default_rng,
156
+ build component dicts with the same tolerance convention, and collect
157
+ ``np.array([response(parts) for parts in trials])`` in the script. This
158
+ helper deliberately has no raw-output mode or publishing side effects.
159
+ """
160
+ if isinstance(sample_count, bool) or not isinstance(sample_count, int) or sample_count < 2:
161
+ raise ValidationError("sample_count must be an integer >=2.")
162
+ if seed is not None and (isinstance(seed, bool) or not isinstance(seed, int) or seed < 0):
163
+ raise ValidationError("seed must be a nonnegative integer or None.")
164
+ if not callable(response) or not nominal:
165
+ raise ValidationError("Provide a response callable and nonempty nominal mapping.")
166
+ names, values, specs = _component_inputs(nominal, tolerances)
167
+ lower = None if lower_limit is None else _response_array(lower_limit, "lower_limit")
168
+ upper = None if upper_limit is None else _response_array(upper_limit, "upper_limit")
169
+ rng = np.random.default_rng(seed)
170
+ samples: NDArray[np.float64] | None = None
171
+ for i in range(sample_count):
172
+ parts = {}
173
+ for name, value, spec in zip(names, values, specs):
174
+ offset = rng.uniform(-1, 1) if spec.distribution == "uniform" else rng.normal()
175
+ sampled = float(value + abs(value) * spec.fraction * offset)
176
+ if not math.isfinite(sampled):
177
+ raise ValidationError(f"Sampled component {name} exceeds floating-point range.")
178
+ parts[name] = sampled
179
+ result = _response_array(response(parts), f"response at trial {i}")
180
+ if samples is None:
181
+ try:
182
+ lower = None if lower is None else np.broadcast_to(lower, result.shape)
183
+ upper = None if upper is None else np.broadcast_to(upper, result.shape)
184
+ except ValueError as exc:
185
+ raise ValidationError("Spec limits must broadcast to the response shape.") from exc
186
+ if lower is not None and upper is not None and np.any(lower > upper):
187
+ raise ValidationError("lower_limit must not exceed upper_limit.")
188
+ samples = np.empty((sample_count, *result.shape), dtype=np.float64)
189
+ if result.shape != samples.shape[1:]:
190
+ raise ValidationError(f"Response shape changed at trial {i}.")
191
+ samples[i] = result
192
+ assert samples is not None
193
+ return _summarize(samples, lower, upper)
@@ -0,0 +1,44 @@
1
+ """Classical matched-stage Friis noise figure."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Sequence
7
+
8
+ from cloudsprite._exceptions import ValidationError
9
+
10
+
11
+ def cascaded_noise_figure(stages: Sequence[tuple[float, float]]) -> float:
12
+ """Return cascaded noise figure in dB using the classical Friis equation.
13
+
14
+ Args:
15
+ stages: Nonempty sequence of (available power gain_dB, noise_figure_dB)
16
+ pairs in source-to-load order. Values must be finite, NF nonnegative.
17
+ Gains may be negative for passive loss. Assumes matched linear stages
18
+ with noise figures referenced to the same standard temperature (290 K);
19
+ does not model mixer image bands or impedance mismatch.
20
+
21
+ Returns:
22
+ System noise figure in dB: F1 + (F2-1)/G1 + ... in linear units.
23
+ For example, [(10, 3), (10, 6)] gives approximately 3.605 dB.
24
+
25
+ Raises:
26
+ ValidationError: Empty stages, invalid values, or unrepresentable result.
27
+ """
28
+ if not stages:
29
+ raise ValidationError("Provide at least one noise stage.")
30
+ gain_db = 0.0
31
+ contributions = [1.0]
32
+ try:
33
+ for gain, nf in stages:
34
+ if not math.isfinite(gain) or not math.isfinite(nf) or nf < 0:
35
+ raise ValidationError("Stage gains must be finite and noise figures finite and nonnegative.")
36
+ if nf != 0:
37
+ contributions.append(math.expm1(nf * math.log(10) / 10) * 10 ** (-gain_db / 10))
38
+ gain_db += gain
39
+ result = 10 * math.log10(math.fsum(contributions))
40
+ except (OverflowError, ValueError) as exc:
41
+ raise ValidationError("Noise cascade exceeds floating-point range.") from exc
42
+ if not math.isfinite(result):
43
+ raise ValidationError("Noise cascade exceeds floating-point range.")
44
+ return result
@@ -0,0 +1,130 @@
1
+ """Auto-paginating iterator — transparent to user.
2
+
3
+ Understands two envelopes: ``{"results", "next"}`` and django-ninja's
4
+ ``{"items", "count"}`` (paged by ``offset``).
5
+
6
+ Two entry points:
7
+ - `auto_paginate(client, path)` — returns a list (eager, used for bracket exact/pattern matching)
8
+ - `auto_paginate_iter(client, path)` — yields items one at a time (lazy, used for iteration)
9
+
10
+ Guards against runaway pagination: a hard page cap and a cursor-repeat detector
11
+ stop if the server returns a self-referential ``next`` (or more pages than any
12
+ reasonable list endpoint should produce).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import TYPE_CHECKING, Any, Iterator
18
+ from urllib.parse import parse_qs, urlencode, urlparse
19
+
20
+ if TYPE_CHECKING:
21
+ from cloudsprite._client import HTTPClient
22
+
23
+ # Hard ceiling so a buggy server cannot pin the client in an infinite loop.
24
+ # 10k pages × typical page size is already multi-million rows; raise only if a
25
+ # real collection legitimately exceeds that (unlikely for this API).
26
+ MAX_PAGES = 10_000
27
+
28
+
29
+ class PaginationError(RuntimeError):
30
+ """Raised when pagination cannot make progress (cycle or page cap)."""
31
+
32
+
33
+ def _cursor_key(path: str, params: dict[str, Any]) -> str:
34
+ """Stable identity for a request path+query so we can detect cycles."""
35
+ if not params:
36
+ return path
37
+ # Sort keys so equivalent param dicts compare equal.
38
+ query = urlencode(sorted((str(k), str(v)) for k, v in params.items()))
39
+ return f"{path}?{query}"
40
+
41
+
42
+ def auto_paginate_iter(
43
+ client: HTTPClient,
44
+ path: str,
45
+ params: dict[str, Any] | None = None,
46
+ headers: dict[str, str] | None = None,
47
+ ) -> Iterator[dict[str, Any]]:
48
+ """Fetch pages lazily and yield items one at a time.
49
+
50
+ Raises:
51
+ PaginationError: If ``next`` repeats a prior cursor, or more than
52
+ :data:`MAX_PAGES` pages are returned.
53
+ """
54
+ current_path = path
55
+ current_params: dict[str, Any] = dict(params) if params else {}
56
+ seen: set[str] = set()
57
+ pages = 0
58
+
59
+ while True:
60
+ key = _cursor_key(current_path, current_params)
61
+ if key in seen:
62
+ raise PaginationError(
63
+ f"Pagination cycle detected: server returned a next cursor that "
64
+ f"was already fetched ({key!r}). Refusing to loop forever."
65
+ )
66
+ seen.add(key)
67
+ pages += 1
68
+ if pages > MAX_PAGES:
69
+ raise PaginationError(
70
+ f"Pagination exceeded {MAX_PAGES} pages for {path!r}. "
71
+ "Refusing to continue — check the server's next cursor."
72
+ )
73
+
74
+ data = client.get(current_path, params=current_params or None, headers=headers)
75
+
76
+ if isinstance(data, list):
77
+ for item in data:
78
+ if isinstance(item, dict):
79
+ yield item
80
+ return
81
+
82
+ if not isinstance(data, dict):
83
+ return
84
+
85
+ results = data.get("results")
86
+ if results is None and isinstance(data.get("items"), list):
87
+ # django-ninja LimitOffsetPagination envelope: {"items": [...], "count": N}.
88
+ # No ``next``; advance ``offset`` by the page length until ``count`` is reached.
89
+ page = [item for item in data["items"] if isinstance(item, dict)]
90
+ yield from page
91
+ count = data.get("count")
92
+ offset = int(current_params.get("offset") or 0) + len(data["items"])
93
+ if not data["items"] or not isinstance(count, int) or offset >= count:
94
+ return
95
+ current_params = {**current_params, "offset": offset}
96
+ continue
97
+
98
+ if isinstance(results, list):
99
+ for item in results:
100
+ if isinstance(item, dict):
101
+ yield item
102
+
103
+ next_url = data.get("next")
104
+ if not next_url:
105
+ return
106
+
107
+ next_url_s = str(next_url)
108
+ if next_url_s.startswith("http"):
109
+ parsed = urlparse(next_url_s)
110
+ current_path = parsed.path
111
+ current_params = {k: v[0] for k, v in parse_qs(parsed.query).items()}
112
+ else:
113
+ # Relative next may already include a query string.
114
+ if "?" in next_url_s:
115
+ path_part, query_part = next_url_s.split("?", 1)
116
+ current_path = path_part
117
+ current_params = {k: v[0] for k, v in parse_qs(query_part).items()}
118
+ else:
119
+ current_path = next_url_s
120
+ current_params = {}
121
+
122
+
123
+ def auto_paginate(
124
+ client: HTTPClient,
125
+ path: str,
126
+ params: dict[str, Any] | None = None,
127
+ headers: dict[str, str] | None = None,
128
+ ) -> list[dict[str, Any]]:
129
+ """Fetch all pages and return combined results list (eager)."""
130
+ return list(auto_paginate_iter(client, path, params, headers))
@@ -0,0 +1,75 @@
1
+ """Parse CSV and Touchstone files into numpy arrays."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+
12
+ def parse_trace_data(content: bytes, file_name: str) -> tuple[np.ndarray, np.ndarray]:
13
+ """Parse file content into (x, y) numpy arrays based on file extension."""
14
+ ext = Path(file_name).suffix.lower()
15
+
16
+ if ext == ".csv":
17
+ return _parse_csv(content)
18
+ if ext in (".s1p", ".s2p", ".s3p", ".s4p", ".snp") or (ext.startswith(".s") and ext.endswith("p")):
19
+ return _parse_touchstone(content, file_name)
20
+
21
+ raise ValueError(f"Unsupported file format: {ext}. Supported: .csv, .s1p, .s2p, .s3p, .s4p")
22
+
23
+
24
+ def _parse_csv(content: bytes) -> tuple[np.ndarray, np.ndarray]:
25
+ """Parse CSV with first column as x, second as y."""
26
+ text = content.decode("utf-8")
27
+ reader = csv.reader(io.StringIO(text))
28
+ rows = list(reader)
29
+
30
+ start = 0
31
+ try:
32
+ float(rows[0][0])
33
+ except (ValueError, IndexError):
34
+ start = 1
35
+
36
+ x_vals = []
37
+ y_vals = []
38
+ for row in rows[start:]:
39
+ if len(row) >= 2:
40
+ x_vals.append(float(row[0]))
41
+ y_vals.append(float(row[1]))
42
+
43
+ return np.array(x_vals), np.array(y_vals)
44
+
45
+
46
+ def _parse_touchstone(content: bytes, file_name: str) -> tuple[np.ndarray, np.ndarray]:
47
+ """Parse Touchstone files using scikit-rf. Returns first S-parameter (S11 or S21).
48
+
49
+ Requires the optional ``rf`` extra: ``pip install cloudsprite[rf]``.
50
+ """
51
+ import os
52
+ import tempfile
53
+
54
+ try:
55
+ import skrf
56
+ except ImportError as exc:
57
+ raise ImportError(
58
+ "scikit-rf is required to parse Touchstone files. " "Install it with: pip install cloudsprite[rf]"
59
+ ) from exc
60
+
61
+ with tempfile.NamedTemporaryFile(suffix=Path(file_name).suffix, delete=False) as f:
62
+ f.write(content)
63
+ f.flush()
64
+ temp_path = f.name
65
+
66
+ try:
67
+ network = skrf.Network(temp_path)
68
+ x = network.f
69
+ y = network.s_db[:, 0, 0]
70
+ return x, y
71
+ finally:
72
+ try:
73
+ os.unlink(temp_path)
74
+ except OSError:
75
+ pass # best-effort cleanup