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,451 @@
1
+ """CloudSprite Python SDK — programmatic access to RF and T&M data.
2
+
3
+ Usage (module convenience API)::
4
+
5
+ import cloudsprite as cs
6
+
7
+ cs.connect(api_key="csk_your_key")
8
+ cs.set_org("acme")
9
+ cs.set_team("rf-lab")
10
+
11
+ s21 = cs.projects["cable-qual"].datasets["sweep-25c"].traces["S21"]
12
+ result = s21 * 0.5
13
+ cs.cloudscript(__file__)
14
+ cs.publish(traces=[result], name="filtered-results")
15
+
16
+ Usage (explicit Client — recommended for libraries and multi-tenant scripts)::
17
+
18
+ from cloudsprite import Client
19
+
20
+ with Client(api_key="csk_your_key", org="acme", team="rf-lab") as cs:
21
+ for p in cs.projects:
22
+ print(p.name)
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from contextlib import AbstractContextManager
28
+ from typing import TYPE_CHECKING, Any
29
+
30
+ from cloudsprite import _work_context
31
+ from cloudsprite._antenna import aperture_gain, beamwidth_gain, effective_aperture, polarization_mismatch_loss
32
+ from cloudsprite._context import Client
33
+ from cloudsprite._exceptions import (
34
+ APIError,
35
+ AuthError,
36
+ CloudSpriteError,
37
+ ExportError,
38
+ ExportInputsChangedError,
39
+ ExportPermissionDeniedError,
40
+ ExportTimeoutError,
41
+ NotFoundError,
42
+ QuotaExceededError,
43
+ ValidationError,
44
+ )
45
+ from cloudsprite._filter_foster import FosterSection
46
+ from cloudsprite._filter_synthesis import FilterSection, LowpassFilter, lowpass_filter
47
+ from cloudsprite._filtering import params, regex
48
+ from cloudsprite._impedance_matching import LMatch, MatchingComponent, StubMatch, l_network_match, single_stub_match
49
+ from cloudsprite._link_budget import LinkBudget, free_space_path_loss, link_budget
50
+ from cloudsprite._monte_carlo import ComponentTolerance, MonteCarloSummary, monte_carlo_yield
51
+ from cloudsprite._noise_figure import cascaded_noise_figure
52
+ from cloudsprite._rf_network import cascade_networks, deembed_network, renormalize_network
53
+ from cloudsprite._run_config import run_config
54
+ from cloudsprite._sparameter_metrics import SParameterMetrics, sparameter_metrics
55
+ from cloudsprite._tdr import TdrStep, tdr_step
56
+ from cloudsprite._trace import Trace
57
+ from cloudsprite._version import sdk_version as _sdk_version
58
+
59
+ if TYPE_CHECKING:
60
+ # PEP 562 module attributes are invisible to type checkers: __getattr__ can
61
+ # only be annotated with one return type for every name, so without these
62
+ # declarations `cs.projects` is opaque and the documented marquee chain
63
+ # `cs.projects["x"].datasets["y"]` stays untyped at its first hop — the exact
64
+ # typing gap this block closes. Mirrors the concrete types on Client; the runtime
65
+ # values still come from __getattr__ below.
66
+ from cloudsprite.resources._base import ResourceCollection
67
+ from cloudsprite.resources.datasets import Dataset
68
+ from cloudsprite.resources.figures import FigureCollection
69
+ from cloudsprite.resources.instruments import Instrument
70
+ from cloudsprite.resources.orbs import Orb
71
+ from cloudsprite.resources.parameters import ParameterKey, ParameterTemplate
72
+ from cloudsprite.resources.projects import Project
73
+ from cloudsprite.resources.reports import ReportCollection
74
+ from cloudsprite.resources.shares import ShareLinkCollection
75
+ from cloudsprite.resources.tags import TagCollection
76
+ from cloudsprite.resources.teams import Team
77
+ from cloudsprite.resources.visualizer_templates import VisualizerTemplateCollection
78
+
79
+ teams: ResourceCollection[Team]
80
+ projects: ResourceCollection[Project]
81
+ datasets: ResourceCollection[Dataset]
82
+ figures: FigureCollection
83
+ visualizer_templates: VisualizerTemplateCollection
84
+ reports: ReportCollection
85
+ shares: ShareLinkCollection
86
+ instruments: ResourceCollection[Instrument]
87
+ tags: TagCollection
88
+ orbs: ResourceCollection[Orb]
89
+ parameter_keys: ResourceCollection[ParameterKey]
90
+ parameter_templates: ResourceCollection[ParameterTemplate]
91
+ supported_models: list[Any]
92
+ manufacturers: list[Any]
93
+
94
+ # Single version source: the installed dist metadata (from pyproject.toml).
95
+ __version__ = _sdk_version()
96
+
97
+ __all__ = [
98
+ "FosterSection",
99
+ "FilterSection",
100
+ "LowpassFilter",
101
+ "lowpass_filter",
102
+ "LMatch",
103
+ "MatchingComponent",
104
+ "StubMatch",
105
+ "l_network_match",
106
+ "single_stub_match",
107
+ "ComponentTolerance",
108
+ "MonteCarloSummary",
109
+ "monte_carlo_yield",
110
+ "SParameterMetrics",
111
+ "sparameter_metrics",
112
+ "TdrStep",
113
+ "tdr_step",
114
+ "cascade_networks",
115
+ "renormalize_network",
116
+ "deembed_network",
117
+ "cascaded_noise_figure",
118
+ "LinkBudget",
119
+ "free_space_path_loss",
120
+ "link_budget",
121
+ "effective_aperture",
122
+ "aperture_gain",
123
+ "beamwidth_gain",
124
+ "polarization_mismatch_loss",
125
+ # Primary object
126
+ "Client",
127
+ # Module convenience (default client)
128
+ "connect",
129
+ "set_org",
130
+ "set_team",
131
+ "set_project",
132
+ "publish",
133
+ "cloudscript",
134
+ "sprite",
135
+ "track_script",
136
+ "report_run",
137
+ "run_config",
138
+ "work_context",
139
+ "search",
140
+ "search_traces",
141
+ # Core types / DSL
142
+ "Trace",
143
+ "regex",
144
+ "params",
145
+ # Exceptions (frozen taxonomy)
146
+ "CloudSpriteError",
147
+ "AuthError",
148
+ "NotFoundError",
149
+ "QuotaExceededError",
150
+ "APIError",
151
+ "ValidationError",
152
+ "ExportError",
153
+ "ExportInputsChangedError",
154
+ "ExportPermissionDeniedError",
155
+ "ExportTimeoutError",
156
+ # Version
157
+ "__version__",
158
+ ]
159
+
160
+ # Hierarchy attributes are contractual but excluded from __all__ so star-import
161
+ # does not eagerly touch AuthError/ValidationError paths before connect.
162
+ _HIERARCHY_ATTRS = frozenset(
163
+ {
164
+ "teams",
165
+ "projects",
166
+ "datasets",
167
+ "reports",
168
+ "shares",
169
+ "figures",
170
+ "visualizer_templates",
171
+ "instruments",
172
+ "tags",
173
+ "orbs",
174
+ "parameter_keys",
175
+ "parameter_templates",
176
+ "supported_models",
177
+ "manufacturers",
178
+ }
179
+ )
180
+
181
+ # Process-default client for the thin module facade.
182
+ # importlib.reload(cloudsprite) re-runs this module and creates a fresh default;
183
+ # Client instances already held by user code keep working independently.
184
+ _default_client: Client | None = None
185
+
186
+
187
+ def _require_default() -> Client:
188
+ """Return the process-default Client, creating it if needed."""
189
+ global _default_client
190
+ if _default_client is None:
191
+ _default_client = Client()
192
+ return _default_client
193
+
194
+
195
+ def connect(
196
+ api_key: str | None = None,
197
+ base_url: str | None = None,
198
+ email: str | None = None,
199
+ password: str | None = None,
200
+ allow_insecure: bool = False,
201
+ ) -> None:
202
+ """Connect the process-default client to CloudSprite.
203
+
204
+ Supports two authentication modes:
205
+ - API key (default): cs.connect(api_key="csk_...")
206
+ - Cognito login: cs.connect(email="user@example.com", password="...")
207
+
208
+ Args:
209
+ api_key: API key string (resolves from env/config if not provided).
210
+ base_url: Override the API base URL.
211
+ email: Cognito email for user login.
212
+ password: Cognito password for user login.
213
+ allow_insecure: Allow http:// connections (local dev only).
214
+
215
+ Example:
216
+ >>> cs.connect(api_key="csk_your_key")
217
+ >>> cs.connect(email="engineer@company.com", password="secret")
218
+ """
219
+ _require_default().connect(
220
+ api_key=api_key,
221
+ base_url=base_url,
222
+ email=email,
223
+ password=password,
224
+ allow_insecure=allow_insecure,
225
+ )
226
+
227
+
228
+ def set_org(slug: str) -> None:
229
+ """Set the default org (tenant) for subsequent queries and WebSockets."""
230
+ _require_default().set_org(slug)
231
+
232
+
233
+ def set_team(slug: str) -> None:
234
+ """Set the default team for subsequent queries."""
235
+ _require_default().set_team(slug)
236
+
237
+
238
+ def set_project(slug: str) -> None:
239
+ """Set the default project for subsequent queries."""
240
+ _require_default().set_project(slug)
241
+
242
+
243
+ def cloudscript(
244
+ file_path: str | None = None,
245
+ seed: object = None,
246
+ *,
247
+ install_hooks: bool | None = None,
248
+ upload_source: bool | None = None,
249
+ include_git: bool | None = None,
250
+ include_error: bool | None = None,
251
+ purpose: str | None = None,
252
+ params: dict[str, object] | None = None,
253
+ include_argv: bool | None = None,
254
+ ) -> None:
255
+ """Enable CloudScript lineage tracking and SDK run reporting on the default client.
256
+
257
+ A CloudScript is an ordinary Python file that runs against CloudSprite. Call
258
+ this once at the top of it::
259
+
260
+ cs.cloudscript(__file__)
261
+ cs.cloudscript(__file__, seed=42)
262
+ cs.cloudscript(__file__, install_hooks=True) # atexit + excepthook
263
+ cs.cloudscript(__file__, purpose="re-run S21 sweep after fixture change")
264
+
265
+ ``cs.sprite()`` and ``cs.track_script()`` are legacy aliases of
266
+ ``cs.cloudscript()`` — same callable, no deprecation warning.
267
+
268
+ What leaves the machine when tracking is active (each channel is opt-out
269
+ unless noted):
270
+
271
+ - **CloudScript source** — **opt-in**. Attached as a DataFile on each
272
+ ``publish()`` only after you consent: the first time it would be uploaded
273
+ in a terminal, the SDK asks once ("Upload this script's source ...?
274
+ [y/N]") and saves your answer in ``~/.cloudsprite/config`` under
275
+ ``[privacy]``. Without a saved answer, in CI, notebooks or any session
276
+ without a terminal, nothing is uploaded and a notice explains how to
277
+ enable it. Override per call with ``upload_source=True/False`` or per
278
+ environment with ``CLOUDSPRITE_UPLOAD_SOURCE=1/0``;
279
+ ``CLOUDSPRITE_NO_SOURCE_UPLOAD=1`` forces it off. Scripts run by
280
+ CloudSprite itself (cloud runs, ``CS_RUN_TOKEN`` set) always attach it:
281
+ the source already lives on the server.
282
+ - **Git state** — HEAD sha (+ optional ``-dirty``) in the run report.
283
+ Never remote URL or OS username.
284
+ - **Error text** — exception type + message only on failure (no traceback
285
+ frames or absolute paths).
286
+ - **Run report** — ``POST /api/script-runs/`` with dataset I/O ids, content
287
+ hash, sdk version, seed, status, ``purpose``, ``params``, ``sys.argv[1:]``
288
+ and the active work context (requires ``install_hooks=True`` for
289
+ automatic atexit, or call ``cs.report_run()``). ``params`` and argv are
290
+ redacted for secrets before sending (the API redacts again); environment
291
+ variables are never sent. Opt out of argv with ``include_argv=False`` or
292
+ ``CLOUDSPRITE_NO_ARGV=1``.
293
+
294
+ ``sys.excepthook`` / ``atexit`` are **not** installed by default; pass
295
+ ``install_hooks=True`` to enable them.
296
+
297
+ Blanket: ``CLOUDSPRITE_NO_TELEMETRY=1`` disables source upload, git state,
298
+ and error text.
299
+
300
+ Args:
301
+ file_path: Path to the running CloudScript (typically ``__file__``).
302
+ Omit for interactive/REPL sessions (``script_name=<interactive>``).
303
+ seed: Optional engineer-supplied seed for reproducibility. Stringified
304
+ and truncated to 64 chars. The SDK never invents a seed.
305
+ install_hooks: Install process hooks (default False).
306
+ upload_source: Attach source on publish. Default: your saved consent (see above);
307
+ True/False overrides it.
308
+ include_git: Include git sha in run reports (default True).
309
+ include_error: Include type+message on failure (default True).
310
+ purpose: Why this run is being made, in a few words (max 280 chars).
311
+ params: The run's parameters, a dict; secrets redacted, dropped if over 15 KB.
312
+ include_argv: Include redacted ``sys.argv[1:]`` in the run report (default True).
313
+ """
314
+ _require_default().cloudscript(
315
+ file_path,
316
+ seed=seed,
317
+ install_hooks=install_hooks,
318
+ upload_source=upload_source,
319
+ include_git=include_git,
320
+ include_error=include_error,
321
+ purpose=purpose,
322
+ params=params,
323
+ include_argv=include_argv,
324
+ )
325
+
326
+
327
+ # Legacy names kept as true aliases (same object).
328
+ sprite = cloudscript
329
+ track_script = cloudscript
330
+
331
+
332
+ def work_context(activity: object, attempt: object = None) -> AbstractContextManager[_work_context.WorkContext]:
333
+ """Run a block under an engineering activity (and optionally one of its attempts).
334
+
335
+ Every API request the default client makes inside the block carries the work-context
336
+ header, so datasets published (``cs.publish``) and runs reported there are stamped with
337
+ it. Blocks nest; the context is per thread / asyncio task. ``CLOUDSPRITE_ACTIVITY`` sets
338
+ a process-wide default when no block is active. Server runs inherit it from their run token.
339
+
340
+ Args:
341
+ activity: Activity id (UUID string, ``uuid.UUID``, or an object with ``.id``).
342
+ attempt: Optional attempt id of that activity (same forms).
343
+
344
+ Raises:
345
+ ValidationError: ``activity`` or ``attempt`` is not a UUID.
346
+
347
+ Example:
348
+ >>> with cs.work_context(activity="0b9c1f4e-...", attempt="5a1d2c3b-..."):
349
+ ... cs.publish(traces=[t], name="s21-sweep")
350
+ """
351
+ return _require_default().work_context(activity, attempt)
352
+
353
+
354
+ def report_run(status: str = "succeeded", error: str | None = None) -> dict[str, object] | None:
355
+ """Post the active cloudscript() run report immediately.
356
+
357
+ For notebooks/REPLs where atexit may not fire when expected. Server
358
+ idempotency on ``client_run_id`` dedupes against the atexit hook.
359
+
360
+ Args:
361
+ status: ``\"succeeded\"`` or ``\"failed\"``.
362
+ error: Optional error message when status is failed (truncated to 10 KB).
363
+
364
+ Returns:
365
+ Parsed API response dict, or None if not tracking / degraded / failed soft.
366
+ """
367
+ return _require_default().report_run(status=status, error=error)
368
+
369
+
370
+ def publish(
371
+ traces: list[object],
372
+ name: str,
373
+ description: str = "",
374
+ params: dict[str, object] | None = None,
375
+ project: str | None = None,
376
+ ) -> dict[str, object]:
377
+ """Publish computed traces as a new dataset."""
378
+ return _require_default().publish(
379
+ traces=traces,
380
+ name=name,
381
+ description=description,
382
+ params=params,
383
+ project=project,
384
+ )
385
+
386
+
387
+ def search(query: str, **kwargs: object) -> list[object]:
388
+ """Search across all CloudSprite resources (projects, datasets, notebooks).
389
+
390
+ Args:
391
+ query: Search query string (sent as ``q``).
392
+ **kwargs: Supported: ``limit``. ``type`` and ``project_id`` are not
393
+ accepted by GET /api/search/; they raise ValidationError. Scope
394
+ datasets with ``Project.datasets`` / ``cs.datasets`` and
395
+ ``project_id``, or filter results by ``.type``.
396
+
397
+ Returns:
398
+ List of SearchResult objects with .type, .name, .id, .slug,
399
+ .project_id, .project_slug. .score is None unless the API returns one.
400
+
401
+ Example:
402
+ >>> results = cs.search("cable 25C")
403
+ >>> for r in results:
404
+ ... print(r.type, r.name)
405
+ """
406
+ return list(_require_default().search(query, **kwargs))
407
+
408
+
409
+ def search_traces(**kwargs: object) -> list[dict[str, object]]:
410
+ """Search for traces across all datasets.
411
+
412
+ Args:
413
+ **kwargs: Filters (x_unit, y_unit, project_id, name, etc.).
414
+
415
+ Returns:
416
+ List of trace metadata dicts.
417
+
418
+ Example:
419
+ >>> traces = cs.search_traces(x_unit="Hz", y_unit="dB")
420
+ """
421
+ return list(_require_default().search_traces(**kwargs))
422
+
423
+
424
+ def __getattr__(name: str) -> object:
425
+ """PEP 562: hierarchy attrs + private default-client alias for demos.
426
+
427
+ Hierarchy properties (``teams``, ``projects``, …) delegate to the
428
+ process-default client. Introspection tip: ``hasattr(cs, "projects")``
429
+ may raise ``ValidationError`` when no team is set — use ``type(cs)`` /
430
+ ``vars(cs)`` / membership in ``_HIERARCHY_ATTRS`` instead.
431
+
432
+ ``_ctx`` is a private, deliberately **undocumented** alias to the default
433
+ client, retained only for older scripts that still reach for it
434
+ (``cs._ctx.client``, ``cs._ctx.resolve_project_id``). It is not supported
435
+ API, so it is resolvable but kept out of ``__dir__`` and ``__all__``.
436
+ Library code must not touch it.
437
+ """
438
+ if name == "_ctx":
439
+ return _require_default()
440
+ if name in _HIERARCHY_ATTRS:
441
+ return getattr(_require_default(), name)
442
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
443
+
444
+
445
+ def __dir__() -> list[str]:
446
+ """PEP 562: expose hierarchy attrs for tab-completion without star-import.
447
+
448
+ ``_ctx`` is intentionally absent — it resolves, but advertising it would
449
+ present an unsupported reach-in as part of the surface.
450
+ """
451
+ return sorted(set(globals()) | set(__all__) | _HIERARCHY_ATTRS)
@@ -0,0 +1,83 @@
1
+ """Aperture relations and explicitly approximate beamwidth estimates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ from cloudsprite._exceptions import ValidationError
8
+ from cloudsprite._link_budget import _C, _finite, _positive
9
+
10
+
11
+ def effective_aperture(gain_dbi: float, frequency_hz: float) -> float:
12
+ """Return effective receiving aperture in square metres, G wavelength² / (4 pi).
13
+
14
+ Args:
15
+ gain_dbi: Antenna power gain in dBi (includes radiation efficiency).
16
+ frequency_hz: Positive finite frequency in Hz.
17
+
18
+ Returns:
19
+ Effective area for polarization-matched reception, not physical area.
20
+ """
21
+ _finite(gain_dbi=gain_dbi)
22
+ _positive(frequency_hz=frequency_hz)
23
+ return 10 ** (gain_dbi / 10) * (_C / frequency_hz) ** 2 / (4 * math.pi)
24
+
25
+
26
+ def aperture_gain(aperture_m2: float, frequency_hz: float, efficiency: float = 1.0) -> float:
27
+ """Return antenna gain in dBi from area: G = 4 pi efficiency A / wavelength².
28
+
29
+ Args:
30
+ aperture_m2: Positive finite physical area in square metres; may instead
31
+ be effective area if efficiency=1.
32
+ frequency_hz: Positive finite frequency in Hz.
33
+ efficiency: Aperture efficiency in (0, 1], defaults to ideal unity.
34
+
35
+ Returns:
36
+ Gain in dBi; the inverse of effective_aperture when efficiency=1.
37
+ """
38
+ _positive(aperture_m2=aperture_m2, frequency_hz=frequency_hz, efficiency=efficiency)
39
+ if efficiency > 1:
40
+ raise ValidationError("efficiency must be at most one.")
41
+ return 10 * (
42
+ math.log10(4 * math.pi)
43
+ + math.log10(efficiency)
44
+ + math.log10(aperture_m2)
45
+ + 2 * (math.log10(frequency_hz) - math.log10(_C))
46
+ )
47
+
48
+
49
+ def beamwidth_gain(beamwidth_e_deg: float, beamwidth_h_deg: float, efficiency: float = 1.0) -> float:
50
+ """Estimate gain in dBi using beam solid angle ≈ HPBW_E * HPBW_H (radians²).
51
+
52
+ Args:
53
+ beamwidth_e_deg: E-plane half-power beamwidth, finite in (0, 180] degrees.
54
+ beamwidth_h_deg: H-plane half-power beamwidth, finite in (0, 180] degrees.
55
+ efficiency: Radiation efficiency in (0, 1].
56
+
57
+ Returns:
58
+ Approximate gain 10 log10(efficiency * 4 pi / (theta_E theta_H)).
59
+ This narrow single-main-lobe approximation ignores sidelobes and pattern
60
+ shape; it is not a universal relation or a substitute for pattern integration.
61
+ """
62
+ _positive(beamwidth_e_deg=beamwidth_e_deg, beamwidth_h_deg=beamwidth_h_deg, efficiency=efficiency)
63
+ if max(beamwidth_e_deg, beamwidth_h_deg) > 180 or efficiency > 1:
64
+ raise ValidationError("Beamwidths must be at most 180 degrees and efficiency at most one.")
65
+ return 10 * math.log10(efficiency * 4 * math.pi / (math.radians(beamwidth_e_deg) * math.radians(beamwidth_h_deg)))
66
+
67
+
68
+ def polarization_mismatch_loss(angle_deg: float) -> float:
69
+ """Return loss in dB between linear polarizations separated by angle_deg.
70
+
71
+ Args:
72
+ angle_deg: Finite relative polarization angle in degrees (180° periodic).
73
+
74
+ Returns:
75
+ -20 log10(abs(cos(angle))); 0 dB aligned, about 3.0103 dB at 45°,
76
+ and positive infinity at exactly orthogonal angles. This models two linear
77
+ polarizations only, not circular/elliptical polarization or multipath.
78
+ """
79
+ _finite(angle_deg=angle_deg)
80
+ angle = angle_deg % 180
81
+ if angle == 90:
82
+ return math.inf
83
+ return -20 * math.log10(abs(math.cos(math.radians(angle))))