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.
- cloudsprite/__init__.py +451 -0
- cloudsprite/_antenna.py +83 -0
- cloudsprite/_auth.py +295 -0
- cloudsprite/_client.py +502 -0
- cloudsprite/_config.py +203 -0
- cloudsprite/_consent.py +104 -0
- cloudsprite/_context.py +945 -0
- cloudsprite/_exceptions.py +136 -0
- cloudsprite/_figure_models.py +158 -0
- cloudsprite/_figure_validation.py +168 -0
- cloudsprite/_filter_foster.py +165 -0
- cloudsprite/_filter_synthesis.py +400 -0
- cloudsprite/_filtering.py +134 -0
- cloudsprite/_impedance_matching.py +262 -0
- cloudsprite/_interpolation.py +47 -0
- cloudsprite/_lineage.py +775 -0
- cloudsprite/_link_budget.py +99 -0
- cloudsprite/_logging.py +53 -0
- cloudsprite/_mixed_mode.py +49 -0
- cloudsprite/_monte_carlo.py +193 -0
- cloudsprite/_noise_figure.py +44 -0
- cloudsprite/_pagination.py +130 -0
- cloudsprite/_parsers.py +75 -0
- cloudsprite/_publish.py +162 -0
- cloudsprite/_redact.py +179 -0
- cloudsprite/_response.py +63 -0
- cloudsprite/_resultset.py +65 -0
- cloudsprite/_rf_network.py +111 -0
- cloudsprite/_run_config.py +46 -0
- cloudsprite/_script_runner.py +217 -0
- cloudsprite/_script_workspace.py +271 -0
- cloudsprite/_sparameter_metrics.py +75 -0
- cloudsprite/_tdr.py +283 -0
- cloudsprite/_trace.py +112 -0
- cloudsprite/_version.py +23 -0
- cloudsprite/_visualizer.py +380 -0
- cloudsprite/_visualizer_cli.py +412 -0
- cloudsprite/_visualizer_preview.py +864 -0
- cloudsprite/_work_context.py +116 -0
- cloudsprite/_ws.py +577 -0
- cloudsprite/cli.py +300 -0
- cloudsprite/py.typed +0 -0
- cloudsprite/resources/__init__.py +1 -0
- cloudsprite/resources/_base.py +293 -0
- cloudsprite/resources/_models.py +50 -0
- cloudsprite/resources/cloudscripts.py +173 -0
- cloudsprite/resources/datasets.py +431 -0
- cloudsprite/resources/figures.py +282 -0
- cloudsprite/resources/instruments.py +295 -0
- cloudsprite/resources/notebooks.py +183 -0
- cloudsprite/resources/orbs.py +99 -0
- cloudsprite/resources/parameters.py +77 -0
- cloudsprite/resources/projects.py +182 -0
- cloudsprite/resources/related.py +125 -0
- cloudsprite/resources/reports.py +992 -0
- cloudsprite/resources/search.py +245 -0
- cloudsprite/resources/shares.py +229 -0
- cloudsprite/resources/sprites.py +15 -0
- cloudsprite/resources/tags.py +107 -0
- cloudsprite/resources/teams.py +86 -0
- cloudsprite/resources/traces.py +147 -0
- cloudsprite/resources/usage.py +152 -0
- cloudsprite/resources/visualizer_templates.py +466 -0
- cloudsprite/resources/workflows.py +59 -0
- cloudsprite-0.11.0.dist-info/METADATA +358 -0
- cloudsprite-0.11.0.dist-info/RECORD +70 -0
- cloudsprite-0.11.0.dist-info/WHEEL +5 -0
- cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
- cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
- cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""CloudSprite SDK error hierarchy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CloudSpriteError(Exception):
|
|
9
|
+
"""Base exception for all CloudSprite SDK errors."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AuthError(CloudSpriteError):
|
|
13
|
+
"""Authentication failed — no API key, invalid key, or expired token."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self, *args: object, status_code: int | None = None, response_body: dict[str, Any] | None = None
|
|
17
|
+
) -> None:
|
|
18
|
+
self.status_code = status_code
|
|
19
|
+
self.response_body = response_body
|
|
20
|
+
super().__init__(*args)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class NotFoundError(CloudSpriteError):
|
|
24
|
+
"""Requested resource does not exist."""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
resource_type: str,
|
|
29
|
+
identifier: str,
|
|
30
|
+
*,
|
|
31
|
+
status_code: int | None = None,
|
|
32
|
+
response_body: dict[str, Any] | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
self.resource_type = resource_type
|
|
35
|
+
self.identifier = identifier
|
|
36
|
+
self.status_code = status_code
|
|
37
|
+
self.response_body = response_body
|
|
38
|
+
super().__init__(f"{resource_type} not found: {identifier}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class QuotaExceededError(CloudSpriteError):
|
|
42
|
+
"""Upload or API quota exceeded for current plan tier."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, message: str, limit: str | None = None, upgrade_url: str | None = None) -> None:
|
|
45
|
+
self.limit = limit
|
|
46
|
+
self.upgrade_url = upgrade_url or "https://cloudsprite.io/settings/billing"
|
|
47
|
+
full_message = message
|
|
48
|
+
if limit:
|
|
49
|
+
full_message += f"\nCurrent limit: {limit}"
|
|
50
|
+
full_message += f"\nUpgrade your plan at {self.upgrade_url}"
|
|
51
|
+
super().__init__(full_message)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class APIError(CloudSpriteError):
|
|
55
|
+
"""Server returned an error response."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, status_code: int, message: str, response_body: dict[str, Any] | None = None) -> None:
|
|
58
|
+
self.status_code = status_code
|
|
59
|
+
self.response_body = response_body
|
|
60
|
+
super().__init__(f"API error {status_code}: {message}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ValidationError(CloudSpriteError):
|
|
64
|
+
"""Client-side validation failed before making API call."""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self, *args: object, status_code: int | None = None, response_body: dict[str, Any] | None = None
|
|
68
|
+
) -> None:
|
|
69
|
+
self.status_code = status_code
|
|
70
|
+
self.response_body = response_body
|
|
71
|
+
super().__init__(*args)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ExportError(CloudSpriteError):
|
|
75
|
+
"""A report export failed or could not be completed.
|
|
76
|
+
|
|
77
|
+
``code`` is the API's lowercase failure code (``inputs_changed``,
|
|
78
|
+
``permission_denied``, ``too_large``, ``render_timeout``, ...) or one of the
|
|
79
|
+
SDK's own: ``timeout`` (``wait`` gave up) and ``expired`` (the artifact
|
|
80
|
+
expired before it could be fetched). ``message`` is user-safe and never
|
|
81
|
+
contains report content.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(self, code: str, message: str, *, job_id: str | None = None) -> None:
|
|
85
|
+
self.code = code
|
|
86
|
+
self.message = message
|
|
87
|
+
self.job_id = job_id
|
|
88
|
+
super().__init__(f"Export failed ({code}): {message}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ExportInputsChangedError(ExportError):
|
|
92
|
+
"""The report or the caller's access changed while the export waited. Request the export again."""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ExportPermissionDeniedError(ExportError):
|
|
96
|
+
"""The requester can no longer read the report (``permission_denied``)."""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ExportTimeoutError(ExportError, TimeoutError):
|
|
100
|
+
"""``wait`` gave up before the export finished. The job keeps running; call ``wait`` again."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
_EXPORT_ERROR_TYPES: dict[str, type[ExportError]] = {
|
|
104
|
+
"inputs_changed": ExportInputsChangedError,
|
|
105
|
+
"permission_denied": ExportPermissionDeniedError,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def export_error(code: str, message: str, *, job_id: str | None = None) -> ExportError:
|
|
110
|
+
"""Build the typed :class:`ExportError` for an API failure ``code`` (case-insensitive)."""
|
|
111
|
+
normalised = (code or "unknown").lower()
|
|
112
|
+
return _EXPORT_ERROR_TYPES.get(normalised, ExportError)(normalised, message, job_id=job_id)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def validate_id(value: str, name: str = "id") -> str:
|
|
116
|
+
"""Validate that a value is safe to use as a URL path segment.
|
|
117
|
+
|
|
118
|
+
Prevents path traversal and malformed URLs from user-supplied IDs.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
value: The ID string to validate (typically a UUID).
|
|
122
|
+
name: Human-readable name for error messages.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
The validated value (unchanged).
|
|
126
|
+
|
|
127
|
+
Raises:
|
|
128
|
+
ValidationError: If the value contains unsafe characters.
|
|
129
|
+
"""
|
|
130
|
+
if not value:
|
|
131
|
+
raise ValidationError(f"{name} must not be empty")
|
|
132
|
+
if "/" in value or "\\" in value or ".." in value:
|
|
133
|
+
raise ValidationError(f"Invalid {name}: contains unsafe characters: {value!r}")
|
|
134
|
+
if len(value) > 256:
|
|
135
|
+
raise ValidationError(f"Invalid {name}: exceeds maximum length (256)")
|
|
136
|
+
return value
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Generated figure wire types; do not edit.
|
|
2
|
+
Source SHA-256: 1fddcd2495c88dbaac36fa5c609e0ad2f74ecf0cacb30b0e4942d8d6de0ccb29.
|
|
3
|
+
Regenerate with scripts/generate_figure_contract.py."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any, Literal, NotRequired, TypedDict
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FigureCreateSchema(TypedDict):
|
|
11
|
+
"""Wire fields of API FigureCreateSchema."""
|
|
12
|
+
|
|
13
|
+
author: NotRequired[str | None]
|
|
14
|
+
config: NotRequired[dict[str, Any] | None]
|
|
15
|
+
conversation_id: NotRequired[str | None]
|
|
16
|
+
dataset_id: NotRequired[str | None]
|
|
17
|
+
figure: dict[str, Any]
|
|
18
|
+
frames: NotRequired[list[Any] | None]
|
|
19
|
+
name: str
|
|
20
|
+
notebook_id: NotRequired[str | None]
|
|
21
|
+
plotly_version: NotRequired[str | None]
|
|
22
|
+
producer: NotRequired[str | None]
|
|
23
|
+
project_id: str
|
|
24
|
+
source: NotRequired[Literal["assistant", "sdk", "app"]]
|
|
25
|
+
source_provenance: NotRequired[dict[str, Any] | None]
|
|
26
|
+
spec: NotRequired[dict[str, Any]]
|
|
27
|
+
title: NotRequired[str | None]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class FigureErrorSchema(TypedDict):
|
|
31
|
+
"""Wire fields of API FigureErrorSchema."""
|
|
32
|
+
|
|
33
|
+
error: str
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class FigureReplaceSchema(TypedDict):
|
|
37
|
+
"""Wire fields of API FigureReplaceSchema."""
|
|
38
|
+
|
|
39
|
+
author: NotRequired[str | None]
|
|
40
|
+
config: NotRequired[dict[str, Any] | None]
|
|
41
|
+
figure: dict[str, Any]
|
|
42
|
+
frames: NotRequired[list[Any] | None]
|
|
43
|
+
name: NotRequired[str | None]
|
|
44
|
+
plotly_version: NotRequired[str | None]
|
|
45
|
+
producer: NotRequired[str | None]
|
|
46
|
+
source_provenance: NotRequired[dict[str, Any] | None]
|
|
47
|
+
spec: NotRequired[dict[str, Any] | None]
|
|
48
|
+
title: NotRequired[str | None]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class FigureRevisionSchema(TypedDict):
|
|
52
|
+
"""Wire fields of API FigureRevisionSchema."""
|
|
53
|
+
|
|
54
|
+
author: NotRequired[str]
|
|
55
|
+
config: NotRequired[dict[str, Any]]
|
|
56
|
+
created_at: str
|
|
57
|
+
created_by_id: NotRequired[str | None]
|
|
58
|
+
figure: dict[str, Any]
|
|
59
|
+
figure_id: str
|
|
60
|
+
frames: NotRequired[list[Any] | None]
|
|
61
|
+
id: str
|
|
62
|
+
original_upload_hash: NotRequired[str | None]
|
|
63
|
+
original_upload_id: NotRequired[str | None]
|
|
64
|
+
plotly_version: NotRequired[str]
|
|
65
|
+
point_count: NotRequired[int]
|
|
66
|
+
producer: NotRequired[str]
|
|
67
|
+
revision: int
|
|
68
|
+
size_bytes: NotRequired[int]
|
|
69
|
+
source_provenance: NotRequired[dict[str, Any]]
|
|
70
|
+
support_report: NotRequired[dict[str, Any]]
|
|
71
|
+
title: NotRequired[str]
|
|
72
|
+
validation_reasons: NotRequired[list[str]]
|
|
73
|
+
validation_status: str
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class FigureRevisionSummarySchema(TypedDict):
|
|
77
|
+
"""Wire fields of API FigureRevisionSummarySchema."""
|
|
78
|
+
|
|
79
|
+
author: NotRequired[str]
|
|
80
|
+
created_at: str
|
|
81
|
+
created_by_id: NotRequired[str | None]
|
|
82
|
+
figure_id: str
|
|
83
|
+
id: str
|
|
84
|
+
original_upload_hash: NotRequired[str | None]
|
|
85
|
+
original_upload_id: NotRequired[str | None]
|
|
86
|
+
plotly_version: NotRequired[str]
|
|
87
|
+
point_count: NotRequired[int]
|
|
88
|
+
producer: NotRequired[str]
|
|
89
|
+
revision: int
|
|
90
|
+
size_bytes: NotRequired[int]
|
|
91
|
+
title: NotRequired[str]
|
|
92
|
+
validation_reasons: NotRequired[list[str]]
|
|
93
|
+
validation_status: str
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class FigureSchema(TypedDict):
|
|
97
|
+
"""Wire fields of API FigureSchema."""
|
|
98
|
+
|
|
99
|
+
author: NotRequired[str]
|
|
100
|
+
config: NotRequired[dict[str, Any]]
|
|
101
|
+
conversation_id: NotRequired[str | None]
|
|
102
|
+
created_at: str
|
|
103
|
+
dataset_id: NotRequired[str | None]
|
|
104
|
+
figure: dict[str, Any]
|
|
105
|
+
frames: NotRequired[list[Any] | None]
|
|
106
|
+
id: str
|
|
107
|
+
name: str
|
|
108
|
+
notebook_id: NotRequired[str | None]
|
|
109
|
+
original_upload_hash: NotRequired[str | None]
|
|
110
|
+
original_upload_id: NotRequired[str | None]
|
|
111
|
+
owner_id: NotRequired[str | None]
|
|
112
|
+
plotly_version: NotRequired[str]
|
|
113
|
+
point_count: NotRequired[int]
|
|
114
|
+
producer: NotRequired[str]
|
|
115
|
+
project_id: str
|
|
116
|
+
revision: NotRequired[int]
|
|
117
|
+
size_bytes: NotRequired[int]
|
|
118
|
+
source: str
|
|
119
|
+
source_provenance: NotRequired[dict[str, Any]]
|
|
120
|
+
spec: NotRequired[dict[str, Any]]
|
|
121
|
+
support_report: NotRequired[dict[str, Any]]
|
|
122
|
+
title: NotRequired[str]
|
|
123
|
+
updated_at: str
|
|
124
|
+
validation_reasons: NotRequired[list[str]]
|
|
125
|
+
validation_status: NotRequired[str]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class FigureSupportMatrixSchema(TypedDict):
|
|
129
|
+
"""Wire fields of API FigureSupportMatrixSchema."""
|
|
130
|
+
|
|
131
|
+
bundle_plotly_major: int
|
|
132
|
+
limits: dict[str, Any]
|
|
133
|
+
trace_types: dict[str, Any]
|
|
134
|
+
unsupported_categories: list[str]
|
|
135
|
+
version: str
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class FigureUpdateSchema(TypedDict):
|
|
139
|
+
"""Wire fields of API FigureUpdateSchema."""
|
|
140
|
+
|
|
141
|
+
author: NotRequired[str | None]
|
|
142
|
+
config: NotRequired[dict[str, Any] | None]
|
|
143
|
+
dataset_id: NotRequired[str | None]
|
|
144
|
+
figure: NotRequired[dict[str, Any] | None]
|
|
145
|
+
frames: NotRequired[list[Any] | None]
|
|
146
|
+
name: NotRequired[str | None]
|
|
147
|
+
notebook_id: NotRequired[str | None]
|
|
148
|
+
plotly_version: NotRequired[str | None]
|
|
149
|
+
producer: NotRequired[str | None]
|
|
150
|
+
source_provenance: NotRequired[dict[str, Any] | None]
|
|
151
|
+
spec: NotRequired[dict[str, Any] | None]
|
|
152
|
+
title: NotRequired[str | None]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class PreferredFigureIn(TypedDict):
|
|
156
|
+
"""Wire fields of API PreferredFigureIn."""
|
|
157
|
+
|
|
158
|
+
figure_id: str
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Local serialization and declarative-only preflight for saved figures."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import binascii
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import re
|
|
10
|
+
from datetime import date, datetime
|
|
11
|
+
from html import unescape
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from cloudsprite._exceptions import ValidationError
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from plotly.graph_objects import Figure as PlotlyFigure
|
|
20
|
+
|
|
21
|
+
_UNSAFE = re.compile(
|
|
22
|
+
r"<\s*[a-z!/]|javascript\s*:|data\s*:\s*text/html|" r"\bon\w+\s*=|\beval\s*\(|new\s+Function|\bfunction\s*\(|=>",
|
|
23
|
+
re.IGNORECASE,
|
|
24
|
+
)
|
|
25
|
+
_FORBIDDEN_KEYS = frozenset(
|
|
26
|
+
{"callback", "callbacks", "jscallback", "jscallbacks", "plotlyserverurl", "mapboxaccesstoken"}
|
|
27
|
+
)
|
|
28
|
+
_DTYPES = frozenset({"i1", "u1", "i2", "u2", "i4", "u4", "f4", "f8"})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _normalize(value: Any) -> Any:
|
|
32
|
+
if isinstance(value, dict):
|
|
33
|
+
# Plotly.py 6 emits typed binary arrays; the v1 server counts/renders
|
|
34
|
+
# ordinary arrays. Expand locally so preflight cannot miss their points.
|
|
35
|
+
if "bdata" in value and "dtype" in value:
|
|
36
|
+
dtype = value["dtype"]
|
|
37
|
+
if not isinstance(dtype, str) or dtype not in _DTYPES:
|
|
38
|
+
raise ValidationError("Unsupported Plotly binary array dtype")
|
|
39
|
+
try:
|
|
40
|
+
raw = base64.b64decode(value["bdata"], validate=True)
|
|
41
|
+
array = np.frombuffer(raw, dtype=np.dtype(dtype).newbyteorder("<"))
|
|
42
|
+
if "shape" in value:
|
|
43
|
+
shape = tuple(int(part.strip()) for part in str(value["shape"]).split(","))
|
|
44
|
+
if not shape or any(part < 0 for part in shape):
|
|
45
|
+
raise ValueError("Invalid shape")
|
|
46
|
+
array = array.reshape(shape)
|
|
47
|
+
return _normalize(array.tolist())
|
|
48
|
+
except (ValueError, TypeError, binascii.Error) as exc:
|
|
49
|
+
raise ValidationError("Invalid Plotly binary array") from exc
|
|
50
|
+
if any(not isinstance(key, str) for key in value):
|
|
51
|
+
raise ValidationError("Figure JSON object keys must be strings")
|
|
52
|
+
return {key: _normalize(item) for key, item in value.items()}
|
|
53
|
+
if isinstance(value, (list, tuple)):
|
|
54
|
+
return [_normalize(item) for item in value]
|
|
55
|
+
if isinstance(value, np.ndarray):
|
|
56
|
+
return _normalize(value.tolist())
|
|
57
|
+
if isinstance(value, np.generic):
|
|
58
|
+
return _normalize(value.item())
|
|
59
|
+
if isinstance(value, (date, datetime)):
|
|
60
|
+
return value.isoformat()
|
|
61
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
62
|
+
return None
|
|
63
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
64
|
+
return value
|
|
65
|
+
raise ValidationError("Figure must contain JSON data, not executable objects")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _scan(value: Any) -> None:
|
|
69
|
+
if isinstance(value, str):
|
|
70
|
+
text = unescape(value)
|
|
71
|
+
if _UNSAFE.search(text):
|
|
72
|
+
raise ValidationError("Embedded HTML/JavaScript is not allowed in figure JSON or config")
|
|
73
|
+
if text.strip().lower().startswith(("https://", "http://")):
|
|
74
|
+
raise ValidationError("Figure must be self-contained; remote resource URLs are not allowed")
|
|
75
|
+
elif isinstance(value, dict):
|
|
76
|
+
for key, item in value.items():
|
|
77
|
+
if key.lower() in _FORBIDDEN_KEYS:
|
|
78
|
+
raise ValidationError(f"HTML/JavaScript callbacks or external resources are not allowed: {key}")
|
|
79
|
+
_scan(key)
|
|
80
|
+
_scan(item)
|
|
81
|
+
elif isinstance(value, list):
|
|
82
|
+
for item in value:
|
|
83
|
+
_scan(item)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def serialize_figure(
|
|
87
|
+
figure: PlotlyFigure | dict[str, Any], config: dict[str, Any] | None
|
|
88
|
+
) -> tuple[dict[str, Any], str | None]:
|
|
89
|
+
"""Convert a dict or optional Plotly Figure into safe JSON-native fields."""
|
|
90
|
+
version = None
|
|
91
|
+
if isinstance(figure, dict):
|
|
92
|
+
raw = figure
|
|
93
|
+
else:
|
|
94
|
+
try:
|
|
95
|
+
import plotly
|
|
96
|
+
from plotly.graph_objects import Figure
|
|
97
|
+
except ImportError as exc:
|
|
98
|
+
raise ValidationError("Pass a figure dict or install Plotly: pip install 'cloudsprite[plotly]'") from exc
|
|
99
|
+
if not isinstance(figure, Figure):
|
|
100
|
+
raise ValidationError("figure must be a plotly.graph_objects.Figure or a dict")
|
|
101
|
+
raw = figure.to_plotly_json()
|
|
102
|
+
version = plotly.__version__
|
|
103
|
+
try:
|
|
104
|
+
document = _normalize(raw)
|
|
105
|
+
if not isinstance(document, dict):
|
|
106
|
+
raise ValidationError("Figure must be a JSON object with a data array")
|
|
107
|
+
normalized_config = _normalize(config if config is not None else document.pop("config", {}))
|
|
108
|
+
_scan(document)
|
|
109
|
+
_scan(normalized_config)
|
|
110
|
+
except (RecursionError, OverflowError) as exc:
|
|
111
|
+
raise ValidationError("Figure JSON is cyclic or nested too deeply") from exc
|
|
112
|
+
if not isinstance(normalized_config, dict):
|
|
113
|
+
raise ValidationError("config must be a JSON object")
|
|
114
|
+
if normalized_config.get("showLink") is True or normalized_config.get("sendDataToCloud") is True:
|
|
115
|
+
raise ValidationError("Figure config cannot send data to an external Plotly account")
|
|
116
|
+
data = document.get("data")
|
|
117
|
+
if not isinstance(data, list) or not data or any(not isinstance(trace, dict) for trace in data):
|
|
118
|
+
raise ValidationError("Figure must include a non-empty data array of trace objects")
|
|
119
|
+
layout = document.get("layout", {})
|
|
120
|
+
if not isinstance(layout, dict):
|
|
121
|
+
raise ValidationError("Figure layout must be a JSON object")
|
|
122
|
+
frames = document.get("frames")
|
|
123
|
+
if frames is not None and not isinstance(frames, list):
|
|
124
|
+
raise ValidationError("Figure frames must be an array")
|
|
125
|
+
return {"figure": {"data": data, "layout": layout}, "config": normalized_config, "frames": frames}, version
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def preflight(payload: dict[str, Any], matrix: dict[str, Any]) -> None:
|
|
129
|
+
"""Check the live byte, point, trace and subplot ceilings before upload."""
|
|
130
|
+
limits = matrix.get("limits")
|
|
131
|
+
names = ("max_size_bytes", "max_point_count", "max_traces_per_subplot", "max_subplots")
|
|
132
|
+
if not isinstance(limits, dict) or any(type(limits.get(key)) is not int or limits[key] <= 0 for key in names):
|
|
133
|
+
raise ValidationError("Figure support matrix has missing or invalid limits")
|
|
134
|
+
document = {**payload["figure"], "frames": payload["frames"]}
|
|
135
|
+
# Include config conservatively, although the backend's byte count omits it.
|
|
136
|
+
if payload["config"]:
|
|
137
|
+
document["config"] = payload["config"]
|
|
138
|
+
size = len(json.dumps(document, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8"))
|
|
139
|
+
points = 0
|
|
140
|
+
subplots: dict[tuple[str, str], int] = {}
|
|
141
|
+
for trace in document["data"]:
|
|
142
|
+
z = trace.get("z")
|
|
143
|
+
if isinstance(z, list) and z and isinstance(z[0], list):
|
|
144
|
+
points += sum(len(row) if isinstance(row, list) else 1 for row in z)
|
|
145
|
+
else:
|
|
146
|
+
points += max(
|
|
147
|
+
(
|
|
148
|
+
len(trace[key])
|
|
149
|
+
for key in ("x", "y", "real", "imag", "r", "theta", "lon", "lat", "z", "values")
|
|
150
|
+
if isinstance(trace.get(key), list)
|
|
151
|
+
),
|
|
152
|
+
default=0,
|
|
153
|
+
)
|
|
154
|
+
key = (str(trace.get("xaxis") or "x"), str(trace.get("yaxis") or "y"))
|
|
155
|
+
subplots[key] = subplots.get(key, 0) + 1
|
|
156
|
+
subplot_count = len(subplots)
|
|
157
|
+
grid = document["layout"].get("grid")
|
|
158
|
+
if isinstance(grid, dict):
|
|
159
|
+
try:
|
|
160
|
+
subplot_count = max(
|
|
161
|
+
subplot_count, int(grid.get("rows") or 1) * int(grid.get("columns") or grid.get("cols") or 1)
|
|
162
|
+
)
|
|
163
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
164
|
+
raise ValidationError("Invalid figure subplot grid") from exc
|
|
165
|
+
estimates = (size, points, max(subplots.values()), subplot_count)
|
|
166
|
+
for name, estimate in zip(names, estimates):
|
|
167
|
+
if estimate > limits[name]:
|
|
168
|
+
raise ValidationError(f"Figure exceeds {name}: estimated {estimate}, API limit {limits[name]}")
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Passive transformer-coupled Foster realization of even elliptic prototypes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from numpy.typing import NDArray
|
|
11
|
+
from scipy import signal
|
|
12
|
+
|
|
13
|
+
from cloudsprite._exceptions import ValidationError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class FosterSection:
|
|
18
|
+
"""A reactive one-port coupled to both filter ports by ideal transformers.
|
|
19
|
+
|
|
20
|
+
Each section has two ideal transformers. Their port-side windings connect
|
|
21
|
+
to filter ports 1 and 2; their element-side windings connect in parallel
|
|
22
|
+
across the same reactive one-port. Signed turns n=(n1,n2) specify polarity, with currents INTO both
|
|
23
|
+
filter ports. For foster-impedance, V_i=n_i*v and the element current is
|
|
24
|
+
n1*I1+n2*I2, so Z_section=z_element*outer(n,n). Connect corresponding
|
|
25
|
+
filter ports of ALL sections in SERIES (not a two-port cascade).
|
|
26
|
+
|
|
27
|
+
For foster-admittance use the dual wiring: I_i=n_i*i and the element
|
|
28
|
+
voltage is n1*V1+n2*V2, so Y_section=y_element*outer(n,n). Connect
|
|
29
|
+
corresponding filter ports of ALL sections in PARALLEL. The dual
|
|
30
|
+
transformer's element-side/port-side voltage ratio is n_i; its element-side
|
|
31
|
+
windings are in series with the reactive one-port. Negative turns reverse
|
|
32
|
+
winding polarity. These ideal transformers are required circuit elements.
|
|
33
|
+
|
|
34
|
+
A single non-None L/C is an inductor/capacitor. With both present the
|
|
35
|
+
one-port is parallel LC for foster-impedance, series LC for
|
|
36
|
+
foster-admittance. Values are H/F; normalized values use 1 rad/s and 1 ohm.
|
|
37
|
+
No finite-Q, leakage, core, parasitic or physical transformer design.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
inductance_h: float | None
|
|
41
|
+
capacitance_f: float | None
|
|
42
|
+
normalized_inductance: float | None
|
|
43
|
+
normalized_capacitance: float | None
|
|
44
|
+
transformer_turns: tuple[float, float]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _even_polynomials(
|
|
48
|
+
zpk: tuple[NDArray[np.complex128], NDArray[np.complex128], float],
|
|
49
|
+
) -> tuple[list[np.poly1d], np.poly1d]:
|
|
50
|
+
# Extended precision reduces cancellation in the reflection square root.
|
|
51
|
+
zeros, poles, gain = zpk
|
|
52
|
+
e = np.poly1d(np.poly(poles.astype(np.clongdouble)).real)
|
|
53
|
+
p = np.poly1d(np.poly(zeros.astype(np.clongdouble)).real * np.longdouble(gain))
|
|
54
|
+
order = e.order
|
|
55
|
+
minus = np.poly1d([-1, 0])
|
|
56
|
+
square = e * e(minus) - p * p(minus)
|
|
57
|
+
coeff = np.zeros(order + 1, dtype=np.longdouble)
|
|
58
|
+
coeff[0] = np.sqrt(square[2 * order])
|
|
59
|
+
for i in range(1, order + 1):
|
|
60
|
+
coeff[i] = (square[2 * order - i] - sum(coeff[j] * coeff[i - j] for j in range(1, i))) / (2 * coeff[0])
|
|
61
|
+
coeff[1::2] = 0
|
|
62
|
+
f = np.poly1d(coeff)
|
|
63
|
+
even, odd = (e + e(minus)) / 2, (e - e(minus)) / 2
|
|
64
|
+
# S=[[F,P],[P,-F]]/E; Z=(I+S)(I-S)^-1.
|
|
65
|
+
return [even + f, p, even - f], odd
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _rank_one(values: NDArray[np.float64]) -> tuple[float, tuple[float, float]]:
|
|
69
|
+
matrix = np.array([[values[0], values[1]], [values[1], values[2]]])
|
|
70
|
+
if not np.all(np.isfinite(matrix)):
|
|
71
|
+
raise ValidationError("Nonfinite Foster residue.")
|
|
72
|
+
eigenvalues, vectors = np.linalg.eigh(matrix)
|
|
73
|
+
strength = float(eigenvalues[-1])
|
|
74
|
+
if strength <= 0 or abs(eigenvalues[0]) > strength * 1e-5:
|
|
75
|
+
raise ValidationError(
|
|
76
|
+
"Foster residue is not a positive rank-one passive section; prototype is ill-conditioned."
|
|
77
|
+
)
|
|
78
|
+
turns = vectors[:, -1]
|
|
79
|
+
if turns[0] < 0:
|
|
80
|
+
turns = -turns
|
|
81
|
+
return strength, (float(turns[0]), float(turns[1]))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _foster_modes(
|
|
85
|
+
numerators: list[np.poly1d], denominator: np.poly1d
|
|
86
|
+
) -> list[tuple[float | None, NDArray[np.float64]]]:
|
|
87
|
+
derivative = np.polyder(denominator)
|
|
88
|
+
modes: list[tuple[float | None, NDArray[np.float64]]] = [
|
|
89
|
+
(None, np.array([n.c[0] / denominator.c[0] for n in numerators], dtype=float)),
|
|
90
|
+
(0.0, np.array([n(0) / derivative(0) for n in numerators], dtype=float)),
|
|
91
|
+
]
|
|
92
|
+
# Solve in s²: avoids discarding small real parts of nominally imaginary poles.
|
|
93
|
+
roots = np.roots(np.asarray(denominator.c[::2], dtype=float))
|
|
94
|
+
if any(abs(r.imag) > 1e-9 or r.real >= 0 for r in roots):
|
|
95
|
+
raise ValidationError("Foster poles are not simple imaginary pairs; prototype is ill-conditioned.")
|
|
96
|
+
frequencies = sorted(math.sqrt(-float(r.real)) for r in roots)
|
|
97
|
+
for frequency in frequencies:
|
|
98
|
+
pole = np.clongdouble(1j) * frequency
|
|
99
|
+
values = np.array([2 * n(pole) / derivative(pole) for n in numerators])
|
|
100
|
+
if np.max(np.abs(values.imag)) > 1e-8 * np.max(np.abs(values.real)):
|
|
101
|
+
raise ValidationError("Foster residues are not real; prototype is ill-conditioned.")
|
|
102
|
+
modes.append((frequency, np.asarray(values.real, dtype=float)))
|
|
103
|
+
return modes
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _scaled_section(
|
|
107
|
+
mode: tuple[float | None, NDArray[np.float64]],
|
|
108
|
+
impedance: float,
|
|
109
|
+
omega: float,
|
|
110
|
+
dual: bool,
|
|
111
|
+
) -> FosterSection:
|
|
112
|
+
frequency, residue = mode
|
|
113
|
+
strength, turns = _rank_one(residue)
|
|
114
|
+
if frequency is None:
|
|
115
|
+
inductance: float | None = strength
|
|
116
|
+
elif frequency == 0:
|
|
117
|
+
inductance = None
|
|
118
|
+
else:
|
|
119
|
+
inductance = strength / frequency**2
|
|
120
|
+
cap = None if frequency is None else 1 / strength
|
|
121
|
+
if dual:
|
|
122
|
+
inductance, cap = cap, inductance
|
|
123
|
+
l_h = None if inductance is None else inductance * impedance / omega
|
|
124
|
+
c_f = None if cap is None else cap / impedance / omega
|
|
125
|
+
if any(v is not None and (not math.isfinite(v) or v <= 0) for v in (l_h, c_f)):
|
|
126
|
+
raise ValidationError("Foster component scaling exceeds floating-point range.")
|
|
127
|
+
return FosterSection(l_h, c_f, inductance, cap, turns)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _verify_foster(
|
|
131
|
+
sections: tuple[FosterSection, ...],
|
|
132
|
+
zpk: tuple[NDArray[np.complex128], NDArray[np.complex128], float],
|
|
133
|
+
dual: bool,
|
|
134
|
+
) -> None:
|
|
135
|
+
w = np.r_[np.geomspace(1e-4, 0.1, 30), np.linspace(0.101, 1.1, 401), np.geomspace(1.101, 100, 160)]
|
|
136
|
+
s = 1j * w
|
|
137
|
+
matrix = np.zeros((len(w), 2, 2), dtype=complex)
|
|
138
|
+
for section in sections:
|
|
139
|
+
inductance, cap = section.normalized_inductance, section.normalized_capacitance
|
|
140
|
+
if dual:
|
|
141
|
+
inductance, cap = cap, inductance
|
|
142
|
+
if inductance is None:
|
|
143
|
+
assert cap is not None
|
|
144
|
+
reactance = 1 / (s * cap)
|
|
145
|
+
else:
|
|
146
|
+
reactance = s * inductance if cap is None else s * inductance / (1 + s * s * inductance * cap)
|
|
147
|
+
matrix += reactance[:, None, None] * np.outer(section.transformer_turns, section.transformer_turns)
|
|
148
|
+
scattering = np.linalg.solve(matrix + np.eye(2), matrix - np.eye(2))
|
|
149
|
+
_, expected = signal.freqs_zpk(*zpk, worN=w)
|
|
150
|
+
# The admittance dual negates S; transmission magnitude is identical.
|
|
151
|
+
if not np.allclose(scattering[:, 0, 1], expected, rtol=2e-6, atol=2e-7):
|
|
152
|
+
raise ValidationError("Foster circuit failed response verification; use less extreme prototype parameters.")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _even_elliptic_sections(
|
|
156
|
+
zpk: tuple[NDArray[np.complex128], NDArray[np.complex128], float],
|
|
157
|
+
source: float,
|
|
158
|
+
cutoff: float,
|
|
159
|
+
first: Literal["series", "shunt"],
|
|
160
|
+
) -> tuple[FosterSection, ...]:
|
|
161
|
+
numerators, denominator = _even_polynomials(zpk)
|
|
162
|
+
modes = _foster_modes(numerators, denominator)
|
|
163
|
+
sections = tuple(_scaled_section(mode, source, 2 * math.pi * cutoff, first == "shunt") for mode in modes)
|
|
164
|
+
_verify_foster(sections, zpk, first == "shunt")
|
|
165
|
+
return sections
|