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,162 @@
1
+ """cs.publish() — create datasets with traces, parameter inheritance, and lineage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextvars
6
+ import csv
7
+ import io
8
+ import json
9
+ import logging
10
+ import warnings
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from cloudsprite import _work_context
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ if TYPE_CHECKING:
18
+ from cloudsprite._client import HTTPClient
19
+ from cloudsprite._lineage import LineageTracker
20
+ from cloudsprite._trace import Trace
21
+
22
+
23
+ def compute_inherited_params(input_params_list: list[dict[str, Any]]) -> dict[str, Any]:
24
+ """Compute inherited parameters: identical values collapse, differing become lists."""
25
+ if not input_params_list:
26
+ return {}
27
+ all_keys: set[str] = set()
28
+ for p in input_params_list:
29
+ all_keys.update(p.keys())
30
+
31
+ result: dict[str, Any] = {}
32
+ for key in sorted(all_keys):
33
+ values = [p.get(key) for p in input_params_list if key in p]
34
+ unique = list(dict.fromkeys(values))
35
+ result[key] = unique[0] if len(unique) == 1 else unique
36
+
37
+ return result
38
+
39
+
40
+ def _trace_to_csv_bytes(trace: Trace) -> bytes:
41
+ """Serialize a trace to CSV bytes."""
42
+ output = io.StringIO()
43
+ writer = csv.writer(output)
44
+ writer.writerow(["x", "y"])
45
+ for xi, yi in zip(trace.x, trace.y):
46
+ writer.writerow([xi, yi])
47
+ return output.getvalue().encode("utf-8")
48
+
49
+
50
+ def _warn_if_unstamped(work: _work_context.WorkContext | None, dataset: Any) -> None:
51
+ """Warn when a work context was active but the created dataset does not carry it."""
52
+ if work is None or not isinstance(dataset, dict) or "work_context" not in dataset:
53
+ return # nothing to check (no context, or a server without the field)
54
+ stamped = dataset["work_context"]
55
+ if isinstance(stamped, dict) and stamped.get("activity_id") == work.activity_id:
56
+ return
57
+ message = (
58
+ "cloudsprite: the dataset was not stamped with the active work context "
59
+ f"(activity {work.activity_id}); the API ignores a context that is unreadable by you "
60
+ "or belongs to another project"
61
+ )
62
+ try:
63
+ warnings.warn(message, stacklevel=4)
64
+ except Exception: # noqa: BLE001 - ``-W error`` must not leave a half-published dataset
65
+ logger.warning(message)
66
+
67
+
68
+ def publish_dataset(
69
+ client: HTTPClient,
70
+ traces: list[Trace],
71
+ name: str,
72
+ project_id: str,
73
+ description: str = "",
74
+ params: dict[str, Any] | None = None,
75
+ lineage: LineageTracker | None = None,
76
+ param_post_pool: Any | None = None,
77
+ ) -> dict[str, Any]:
78
+ """Create a new dataset with traces, parameters, and optional lineage.
79
+
80
+ Note on lineage: the CloudScript source (if `cs.cloudscript()` was called) is
81
+ attached to the dataset as a DataFile. The structured lineage metadata
82
+ (is_computed, sdk_version, input_datasets, computed_at, script_hash) is
83
+ NOT sent in the dataset payload: the API does not store those fields yet.
84
+
85
+ Args:
86
+ param_post_pool: Optional executor for parallel parameter POSTs.
87
+ Prefer passing the owning Client's pool. When omitted, parameters
88
+ are posted sequentially on the calling thread.
89
+ """
90
+ from cloudsprite.resources.datasets import apply_sdk_dataset_source
91
+
92
+ dataset_payload: dict[str, Any] = apply_sdk_dataset_source(
93
+ {
94
+ "title": name,
95
+ "project_id": project_id,
96
+ "description": description,
97
+ }
98
+ )
99
+
100
+ # The work-context header rides on this request (HTTPClient header provider), so the
101
+ # API stamps the dataset with the active activity/attempt. A context it cannot honour
102
+ # (unreadable activity, other project) is ignored server-side, not an error: say so.
103
+ owner = client.owner()
104
+ work = owner.current_work_context() if owner is not None else None
105
+ ds_result = client.post("/api/datasets/", json=dataset_payload)
106
+ ds_id = ds_result["id"]
107
+ _warn_if_unstamped(work, ds_result)
108
+
109
+ for trace in traces:
110
+ csv_bytes = _trace_to_csv_bytes(trace)
111
+ file_name = f"{trace.name}.csv"
112
+ client.post_file(
113
+ f"/api/datasets/{ds_id}/datafiles/",
114
+ file_name=file_name,
115
+ file_data=csv_bytes,
116
+ extra_fields={"name": trace.name, "x_unit": trace.x_unit, "y_unit": trace.y_unit},
117
+ )
118
+
119
+ # Source attachment is gated by lineage.upload_source (consent / kwarg / env / cloud run; see _consent).
120
+ if lineage and lineage.upload_source and lineage.script_source is not None:
121
+ client.post_file(
122
+ f"/api/datasets/{ds_id}/datafiles/",
123
+ file_name=lineage.script_name or "script.py",
124
+ file_data=lineage.script_source.encode("utf-8"),
125
+ extra_fields={"name": f"_lineage_{lineage.script_name}", "is_lineage": "true"},
126
+ )
127
+
128
+ # Compute inherited params from input traces' parent datasets
129
+ input_params_list: list[dict[str, Any]] = []
130
+ for trace in traces:
131
+ if trace.dataset and hasattr(trace.dataset, "params"):
132
+ input_params_list.append(trace.dataset.params)
133
+
134
+ merged_params = compute_inherited_params(input_params_list) if input_params_list else {}
135
+ if params:
136
+ merged_params.update(params)
137
+
138
+ if merged_params:
139
+
140
+ def _post_param(item: tuple[str, Any]) -> Any:
141
+ key, value = item
142
+ val_str = json.dumps(value) if isinstance(value, list) else str(value)
143
+ return client.post(
144
+ f"/api/datasets/{ds_id}/parameters/",
145
+ json={
146
+ "parameter_key_title": key,
147
+ "value": val_str,
148
+ },
149
+ )
150
+
151
+ if param_post_pool is not None:
152
+ # Pool threads do not inherit contextvars. Copy ours here, in the calling thread
153
+ # (one copy per task: a Context cannot be entered by two threads at once), so the
154
+ # work-context header reaches the API from the workers too.
155
+ # list() exhausts the iterator to propagate any worker exceptions
156
+ runs = [(contextvars.copy_context(), item) for item in merged_params.items()]
157
+ list(param_post_pool.map(lambda run: run[0].run(_post_param, run[1]), runs))
158
+ else:
159
+ for item in merged_params.items():
160
+ _post_param(item)
161
+
162
+ return ds_result # type: ignore[no-any-return]
cloudsprite/_redact.py ADDED
@@ -0,0 +1,179 @@
1
+ """Secret redaction for the run report's ``params`` and ``argv``.
2
+
3
+ The API redacts again; this is the client side of
4
+ that rule so a secret never leaves the machine. Keys and flags are matched on
5
+ whole words (``api_key``, ``apiKey``, ``X-Auth-Token``) so ``author`` and
6
+ ``session_id`` stay readable; values are matched on shape only, never length.
7
+ Mirrors the server rules conservatively: when in doubt, mask.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import math
14
+ import re
15
+ from typing import Any
16
+
17
+ REDACTED = "[redacted]"
18
+
19
+ # Margins under the API's limits (16 KB, depth 8): its counting is not ours to guess.
20
+ _MAX_PARAMS_BYTES = 15 * 1024
21
+ _MAX_DEPTH = 7
22
+ _MAX_ARGV_ITEMS = 100
23
+ _MAX_ARGV_CHARS = 1024
24
+
25
+ _SECRET_WORDS = frozenset(
26
+ {
27
+ "password",
28
+ "passwd",
29
+ "secret",
30
+ "token",
31
+ "credential",
32
+ "credentials",
33
+ "cookie",
34
+ "authorization",
35
+ "auth",
36
+ "bearer",
37
+ "jwt",
38
+ "signature",
39
+ "passphrase",
40
+ "pwd",
41
+ }
42
+ )
43
+ # Sibling keys of a {"name": "password", "value": "x"} record (mirror of the API's sets).
44
+ _NAME_KEYS = frozenset({"name", "key", "field", "header", "param", "parameter", "variable", "var", "env"})
45
+ _VALUE_KEYS = frozenset({"value", "val", "data", "content", "text", "string"})
46
+ _KEY_PREFIXES = frozenset({"api", "private", "access", "secret", "client"})
47
+ _TAIL_WORDS = frozenset({"pass", "pw"})
48
+ # Compound lowercase names: accesstoken, refreshtoken, privatekey, dbpassword, apikey.
49
+ _COMPOUND_SUFFIXES = ("token", "password", "passwd", "secret", "apikey", "privatekey", "accesskey", "secretkey")
50
+
51
+ _CAMEL = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
52
+ _SPLIT = re.compile(r"[^A-Za-z0-9]+")
53
+
54
+
55
+ def _words(name: str) -> list[str]:
56
+ return [w.lower() for w in _SPLIT.split(_CAMEL.sub("_", name)) if w]
57
+
58
+
59
+ def is_secret_name(name: str) -> bool:
60
+ """True when a mapping key / flag name denotes a secret."""
61
+ words = _words(name)
62
+ if not words:
63
+ return False
64
+ if any(w in _SECRET_WORDS for w in words):
65
+ return True
66
+ if words[-1] in _TAIL_WORDS:
67
+ return True
68
+ for a, b in zip(words, words[1:]):
69
+ if (a in _KEY_PREFIXES and b == "key") or (a == "pass" and b in ("word", "phrase")):
70
+ return True
71
+ return any(w.endswith(s) for w in words for s in _COMPOUND_SUFFIXES)
72
+
73
+
74
+ _VALUE_PATTERNS = (
75
+ re.compile(r"eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*"), # JWT
76
+ re.compile(r"\b(?:AKIA|ASIA)[A-Z0-9]{16}\b"), # AWS key id
77
+ re.compile(r"\b(?:sk-|ghp_|gho_|ghs_|glpat-|xox[abprs]-)[A-Za-z0-9_\-]{8,}"),
78
+ re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}"),
79
+ re.compile(r"(?i)\bBasic\s+[A-Za-z0-9+/=]{8,}"),
80
+ )
81
+ _URL_CREDS = re.compile(r"(?P<scheme>[A-Za-z][A-Za-z0-9+.-]*://)[^/\s@]*@")
82
+ _AUTH_HEADER = re.compile(r"(?i)\b(Authorization\s*:\s*)(?:\S+\s+)?\S+")
83
+ # name=value, name: value, "name": "value" (quoted values may hold spaces)
84
+ _ASSIGN = re.compile(
85
+ r"""(?P<head>(?P<name>[A-Za-z_][A-Za-z0-9_.\-]*)["']?\s*[:=]\s*)"""
86
+ r"""(?!//)(?P<value>"[^"]*"|'[^']*'|[^\s&;,}\]]*)"""
87
+ )
88
+
89
+
90
+ def redact_string(text: str) -> str:
91
+ """Mask secret-shaped values and ``SECRET_NAME=value`` assignments inside a string."""
92
+
93
+ def _assign(match: re.Match[str]) -> str:
94
+ if is_secret_name(match.group("name")) and not match.group("value").startswith("[redacted"):
95
+ return f"{match.group('head')}{REDACTED}"
96
+ return match.group(0)
97
+
98
+ out = _URL_CREDS.sub(lambda m: f"{m.group('scheme')}{REDACTED}@", text)
99
+ out = _AUTH_HEADER.sub(lambda m: f"{m.group(1)}{REDACTED}", out)
100
+ out = _ASSIGN.sub(_assign, out)
101
+ for pattern in _VALUE_PATTERNS:
102
+ out = pattern.sub(REDACTED, out)
103
+ return out
104
+
105
+
106
+ def redact_value(value: Any, depth: int = 0) -> Any:
107
+ """JSON-safe copy of ``value`` with secrets masked and depth capped at 8."""
108
+ if isinstance(value, str):
109
+ return redact_string(value)
110
+ if isinstance(value, float) and not math.isfinite(value):
111
+ return str(value) # NaN / Infinity are not valid JSON
112
+ if value is None or isinstance(value, (bool, int, float)):
113
+ return value
114
+ if depth >= _MAX_DEPTH:
115
+ # Past the cap a container is not walked, so nothing inside it can be vetted.
116
+ if isinstance(value, (dict, list, tuple, set, frozenset)):
117
+ return REDACTED
118
+ return redact_string(str(value))
119
+ if isinstance(value, dict):
120
+ out: dict[str, Any] = {}
121
+ for key, item in value.items():
122
+ k = str(key)
123
+ out[k] = REDACTED if is_secret_name(k) else redact_value(item, depth + 1)
124
+ # {"name": "password", "value": "..."} records
125
+ # (same key sets as the API)
126
+ if any(str(k).lower() in _NAME_KEYS and isinstance(v, str) and is_secret_name(v) for k, v in value.items()):
127
+ for k in out:
128
+ if k.lower() in _VALUE_KEYS:
129
+ out[k] = REDACTED
130
+ return out
131
+ if isinstance(value, (list, tuple, set, frozenset)):
132
+ items = [redact_value(item, depth + 1) for item in value]
133
+ # ["Authorization", "..."] pairs
134
+ if len(items) == 2 and isinstance(value, (list, tuple)) and isinstance(value[0], str):
135
+ if is_secret_name(value[0]):
136
+ items[1] = REDACTED
137
+ return items
138
+ return redact_string(str(value))
139
+
140
+
141
+ def redact_params(params: dict[str, Any] | None) -> dict[str, Any] | None:
142
+ """Redacted, JSON-safe params, or None when empty or over the size limit."""
143
+ if not params:
144
+ return None
145
+ clean = redact_value(dict(params))
146
+ if len(json.dumps(clean, default=str).encode("utf-8")) > _MAX_PARAMS_BYTES:
147
+ return None
148
+ return clean # type: ignore[no-any-return]
149
+
150
+
151
+ def redact_argv(argv: list[str] | None) -> list[str]:
152
+ """Redacted argv: secret flag values, ``name=value`` items, ``-p<value>``; capped at 100 x 1024."""
153
+ out: list[str] = []
154
+ mask_next = False
155
+ for raw in (argv or [])[:_MAX_ARGV_ITEMS]:
156
+ item = str(raw)
157
+ if mask_next:
158
+ mask_next = False
159
+ out.append(REDACTED)
160
+ continue
161
+ if item.startswith("-") and len(item) > 2:
162
+ flag, eq, _val = item.partition("=")
163
+ if eq and is_secret_name(flag.lstrip("-")):
164
+ out.append(f"{flag}={REDACTED}")
165
+ continue
166
+ # --token x, -token x, -password x: the next item is the value
167
+ if not eq and is_secret_name(item.lstrip("-")):
168
+ mask_next = True
169
+ out.append(item)
170
+ continue
171
+ if item == "-p":
172
+ mask_next = True
173
+ out.append(item)
174
+ continue
175
+ if re.fullmatch(r"-p.+", item) and not item.startswith("--"):
176
+ out.append(f"-p{REDACTED}")
177
+ continue
178
+ out.append(redact_string(item)[:_MAX_ARGV_CHARS])
179
+ return out
@@ -0,0 +1,63 @@
1
+ """Shared HTTP response-body parsing.
2
+
3
+ Lives in its own module because both ``_client`` and ``_auth`` need it and
4
+ ``_client`` already imports ``_auth`` — putting it in either would be a cycle.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ import requests as req
12
+
13
+ from cloudsprite._exceptions import APIError
14
+
15
+ HTML_BASE_URL_HINT = (
16
+ "Received HTML instead of JSON. base_url appears to point at the frontend, "
17
+ "not the API. Use https://api.cloudsprite.io (or your API host), not the "
18
+ "website host (https://cloudsprite.io)."
19
+ )
20
+
21
+
22
+ def looks_like_html(resp: req.Response) -> bool:
23
+ """True when the response body is an HTML document rather than JSON.
24
+
25
+ The usual cause is a ``base_url`` aimed at the website instead of the API:
26
+ the frontend's catch-all route answers every ``/api/*`` path with the SPA
27
+ shell and a **200**, so nothing in normal error handling notices.
28
+ """
29
+ content_type = (resp.headers.get("content-type") or "").lower()
30
+ if "text/html" in content_type or "application/xhtml" in content_type:
31
+ return True
32
+ if not resp.content:
33
+ return False
34
+ head = resp.content.lstrip()[:64].lower()
35
+ return head.startswith(b"<!doctype") or head.startswith(b"<html")
36
+
37
+
38
+ def parse_json_response(resp: req.Response, path: str = "") -> Any:
39
+ """Parse a success-response JSON body.
40
+
41
+ Every JSON-decoding path must go through this rather than ``resp.json()``.
42
+ A bare ``resp.json()`` on an HTML body raises
43
+ ``requests.exceptions.JSONDecodeError``, which both breaks the "no raw
44
+ requests exceptions escape" guarantee and tells the user nothing about the
45
+ actual cause.
46
+
47
+ Only call this for responses below 400 — see ``_client.raise_for_response``
48
+ for error bodies, where HTML means an intermediary answered rather than a
49
+ misconfigured ``base_url``.
50
+
51
+ Raises:
52
+ APIError: If the body is HTML, or is otherwise not valid JSON.
53
+ """
54
+ if looks_like_html(resp):
55
+ raise APIError(resp.status_code, HTML_BASE_URL_HINT, None)
56
+ try:
57
+ return resp.json()
58
+ except ValueError as exc:
59
+ raise APIError(
60
+ resp.status_code,
61
+ f"Invalid JSON response from {path or resp.url or 'API'}: {exc}",
62
+ None,
63
+ ) from exc
@@ -0,0 +1,65 @@
1
+ """ResultSet — iterable query result with convenience methods."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Generic, Iterator, TypeVar
6
+
7
+ from cloudsprite._filtering import FilterExpression
8
+
9
+ if TYPE_CHECKING:
10
+ pass
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ class ResultSet(Generic[T]):
16
+ """Iterable collection of resources with convenience methods."""
17
+
18
+ def __init__(self, items: list[T]):
19
+ self._items = items
20
+
21
+ @property
22
+ def count(self) -> int:
23
+ """Number of items in this result set."""
24
+ return len(self._items)
25
+
26
+ def first(self) -> T | None:
27
+ """Return the first item, or None if empty."""
28
+ return self._items[0] if self._items else None
29
+
30
+ def filter(self, expr: FilterExpression) -> ResultSet[T]:
31
+ """Further filter the ResultSet by a parameter expression."""
32
+ filtered = [item for item in self._items if expr.evaluate(getattr(item, "params", {}))]
33
+ return ResultSet(filtered)
34
+
35
+ def to_dataframe(self) -> Any:
36
+ """Convert ResultSet to a pandas DataFrame.
37
+
38
+ Requires the optional ``pandas`` extra::
39
+
40
+ pip install cloudsprite[pandas]
41
+ """
42
+ try:
43
+ import pandas as pd
44
+ except ImportError as exc:
45
+ raise ImportError(
46
+ "pandas is required for ResultSet.to_dataframe(). " "Install it with: pip install cloudsprite[pandas]"
47
+ ) from exc
48
+
49
+ rows = []
50
+ for item in self._items:
51
+ row: dict[str, Any] = {"name": getattr(item, "name", None)}
52
+ params = getattr(item, "params", {})
53
+ if isinstance(params, dict):
54
+ row.update(params)
55
+ rows.append(row)
56
+ return pd.DataFrame(rows)
57
+
58
+ def __iter__(self) -> Iterator[T]:
59
+ return iter(self._items)
60
+
61
+ def __len__(self) -> int:
62
+ return len(self._items)
63
+
64
+ def __repr__(self) -> str:
65
+ return f"ResultSet({self.count} items)"
@@ -0,0 +1,111 @@
1
+ """Non-mutating operations on local Touchstone files and scikit-rf networks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from os import PathLike
6
+ from typing import TYPE_CHECKING, TypeAlias
7
+
8
+ import numpy as np
9
+
10
+ from cloudsprite._exceptions import ValidationError
11
+
12
+ if TYPE_CHECKING:
13
+ from skrf import Network
14
+
15
+ NetworkInput: TypeAlias = "Network | str | PathLike[str]"
16
+
17
+
18
+ def _network(value: NetworkInput) -> Network:
19
+ try:
20
+ import skrf
21
+ except ImportError as exc:
22
+ raise ImportError(
23
+ "scikit-rf is required for RF network analysis. " "Install it with: pip install cloudsprite[rf]"
24
+ ) from exc
25
+ if isinstance(value, (str, PathLike)):
26
+ value = skrf.Network(str(value))
27
+ if not isinstance(value, skrf.Network):
28
+ raise ValidationError("Expected a scikit-rf Network or local Touchstone path.")
29
+ f = np.asarray(value.f)
30
+ if f.size == 0 or not np.all(np.isfinite(f)) or np.any(f < 0) or np.any(np.diff(f) <= 0):
31
+ raise ValidationError("Network frequencies must be nonempty, finite, nonnegative and strictly increasing.")
32
+ if value.nports < 1 or not np.all(np.isfinite(value.s)):
33
+ raise ValidationError("Network must contain finite S-parameters and at least one port.")
34
+ return value
35
+
36
+
37
+ def _two_ports(*networks: Network) -> None:
38
+ if any(n.nports != 2 for n in networks):
39
+ raise ValidationError("Cascade and de-embedding require two-port networks.")
40
+ if any(not np.array_equal(n.f, networks[0].f) for n in networks[1:]):
41
+ raise ValidationError("Networks must have identical frequency grids; interpolate explicitly first.")
42
+
43
+
44
+ def cascade_networks(*networks: NetworkInput) -> Network:
45
+ """Chain at least two two-port networks in order, returning a new Network.
46
+
47
+ Args:
48
+ *networks: scikit-rf Networks or local Touchstone paths, ordered from
49
+ source to load (port 2 of each connects to port 1 of the next).
50
+ Frequency grids must match exactly. scikit-rf handles impedance
51
+ mismatches at connected ports; no interpolation is performed.
52
+
53
+ Returns:
54
+ Cascaded scikit-rf Network. Inputs are unchanged. Requires ``[rf]``.
55
+
56
+ Raises:
57
+ ValidationError: Fewer than two networks, wrong port count or grid.
58
+ ImportError: Install with ``pip install cloudsprite[rf]``.
59
+ """
60
+ if len(networks) < 2:
61
+ raise ValidationError("Provide at least two networks to cascade.")
62
+ loaded = [_network(n) for n in networks]
63
+ _two_ports(*loaded)
64
+ result = loaded[0].copy()
65
+ for network in loaded[1:]:
66
+ result = result**network
67
+ return result
68
+
69
+
70
+ def renormalize_network(network: NetworkInput, z0_ohm: float) -> Network:
71
+ """Return a copy renormalized to the same real reference impedance at all ports.
72
+
73
+ Args:
74
+ network: scikit-rf Network or local Touchstone path (any port count).
75
+ z0_ohm: Positive finite real reference impedance in ohms.
76
+
77
+ Returns:
78
+ New Network using scikit-rf's renormalize method and existing S-wave
79
+ definition. The input is unchanged. Requires ``pip install cloudsprite[rf]``.
80
+ """
81
+ if not np.isfinite(z0_ohm) or z0_ohm <= 0:
82
+ raise ValidationError("z0_ohm must be positive and finite.")
83
+ result = _network(network).copy()
84
+ result.renormalize(z0_ohm)
85
+ return result
86
+
87
+
88
+ def deembed_network(
89
+ measured: NetworkInput, left_fixture: NetworkInput, right_fixture: NetworkInput | None = None
90
+ ) -> Network:
91
+ """Remove known two-port fixtures using scikit-rf inverse cascading.
92
+
93
+ Args:
94
+ measured: Measurement of ``left_fixture ** DUT ** right_fixture``.
95
+ left_fixture: Input fixture, port 1 facing the source and port 2 the DUT.
96
+ right_fixture: Optional output fixture, port 1 facing the DUT and port 2
97
+ the load. Flip a reverse-oriented measurement explicitly beforehand.
98
+ Omit for a measurement of ``left_fixture ** DUT``.
99
+
100
+ Returns:
101
+ New DUT Network; inputs unchanged. All networks require identical grids
102
+ and two ports. Requires ``pip install cloudsprite[rf]``. Inverse fixture
103
+ networks must be nonsingular; scikit-rf/numpy errors propagate otherwise.
104
+ """
105
+ measurement, left = _network(measured), _network(left_fixture)
106
+ right = _network(right_fixture) if right_fixture is not None else None
107
+ _two_ports(measurement, left, *([right] if right is not None else []))
108
+ result = left.inv**measurement
109
+ if right is not None:
110
+ result = result**right.inv
111
+ return result
@@ -0,0 +1,46 @@
1
+ """Read the configuration a CloudScript run was started with."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from cloudsprite._exceptions import ValidationError
10
+
11
+ RUN_CONFIG_FILENAME = "cs_run_config.json"
12
+
13
+
14
+ def run_config() -> dict[str, Any]:
15
+ """Return the config this run was started with, as a dict.
16
+
17
+ The script runner writes the run's config to ``cs_run_config.json`` in the
18
+ script's working directory when it is non-empty. This reads that file, so
19
+ call it before changing directory. Outside a run (a local script) or when
20
+ the run has no config there is no file and the result is ``{}``. Each call
21
+ returns a fresh dict.
22
+
23
+ Returns:
24
+ The run's config, or an empty dict when there is none.
25
+
26
+ Raises:
27
+ ValidationError: The file exists but is not a JSON object.
28
+
29
+ Example:
30
+ >>> config = cs.run_config()
31
+ >>> threshold = float(config.get("correlation_threshold", 0.95))
32
+ """
33
+ path = Path.cwd() / RUN_CONFIG_FILENAME
34
+ try:
35
+ text = path.read_text(encoding="utf-8")
36
+ except FileNotFoundError:
37
+ return {}
38
+ except OSError as exc:
39
+ raise ValidationError(f"Cannot read {RUN_CONFIG_FILENAME}: {exc}") from exc
40
+ try:
41
+ config = json.loads(text)
42
+ except json.JSONDecodeError as exc:
43
+ raise ValidationError(f"{RUN_CONFIG_FILENAME} is not valid JSON: {exc}") from exc
44
+ if not isinstance(config, dict):
45
+ raise ValidationError(f"{RUN_CONFIG_FILENAME} must hold a JSON object, got {type(config).__name__}")
46
+ return config