qthinking 0.0.2__tar.gz
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.
- qthinking-0.0.2/LICENSE +7 -0
- qthinking-0.0.2/MANIFEST.in +1 -0
- qthinking-0.0.2/PKG-INFO +17 -0
- qthinking-0.0.2/README.md +0 -0
- qthinking-0.0.2/pyproject.toml +25 -0
- qthinking-0.0.2/qthinking/__init__.py +49 -0
- qthinking-0.0.2/qthinking/analog/__init__.py +104 -0
- qthinking-0.0.2/qthinking/analog/_plotting.py +190 -0
- qthinking-0.0.2/qthinking/analog/_validation.py +164 -0
- qthinking-0.0.2/qthinking/analog/controls.py +144 -0
- qthinking-0.0.2/qthinking/analog/dynamics.py +105 -0
- qthinking-0.0.2/qthinking/analog/hamiltonian.py +127 -0
- qthinking-0.0.2/qthinking/analog/interaction.py +137 -0
- qthinking-0.0.2/qthinking/analog/measurement.py +166 -0
- qthinking-0.0.2/qthinking/analog/program.py +391 -0
- qthinking-0.0.2/qthinking/analog/rb87.py +608 -0
- qthinking-0.0.2/qthinking/analog/results.py +233 -0
- qthinking-0.0.2/qthinking/analog/sequence.py +509 -0
- qthinking-0.0.2/qthinking/analog/system.py +106 -0
- qthinking-0.0.2/qthinking/analog/waveforms.py +355 -0
- qthinking-0.0.2/qthinking/applications/__init__.py +118 -0
- qthinking-0.0.2/qthinking/applications/btc_experimental.py +287 -0
- qthinking-0.0.2/qthinking/applications/btc_minimal.py +307 -0
- qthinking-0.0.2/qthinking/applications/btc_volatility.py +608 -0
- qthinking-0.0.2/qthinking/applications/climate.py +671 -0
- qthinking-0.0.2/qthinking/applications/climate_results.py +219 -0
- qthinking-0.0.2/qthinking/applications/market_data.py +276 -0
- qthinking-0.0.2/qthinking/applications/results.py +423 -0
- qthinking-0.0.2/qthinking/applications/sp500_volatility.py +407 -0
- qthinking-0.0.2/qthinking/applications/stateful.py +289 -0
- qthinking-0.0.2/qthinking/applications/volatility.py +380 -0
- qthinking-0.0.2/qthinking/backends/__init__.py +7 -0
- qthinking-0.0.2/qthinking/backends/base.py +26 -0
- qthinking-0.0.2/qthinking/backends/numpy_split_step.py +383 -0
- qthinking-0.0.2/qthinking/backends/qutip.py +556 -0
- qthinking-0.0.2/qthinking/errors.py +53 -0
- qthinking-0.0.2/qthinking/handoff.py +295 -0
- qthinking-0.0.2/qthinking/ml/__init__.py +6 -0
- qthinking-0.0.2/qthinking/ml/ridge.py +227 -0
- qthinking-0.0.2/qthinking/ml/svr.py +123 -0
- qthinking-0.0.2/qthinking/qelm/__init__.py +63 -0
- qthinking-0.0.2/qthinking/qelm/config.py +322 -0
- qthinking-0.0.2/qthinking/qelm/encoding.py +216 -0
- qthinking-0.0.2/qthinking/qelm/model.py +323 -0
- qthinking-0.0.2/qthinking/qelm/presets.py +160 -0
- qthinking-0.0.2/qthinking/qelm/temporal.py +31 -0
- qthinking-0.0.2/qthinking/qrc/__init__.py +21 -0
- qthinking-0.0.2/qthinking/qrc/presets.py +240 -0
- qthinking-0.0.2/qthinking/qrc/temporal.py +264 -0
- qthinking-0.0.2/qthinking.egg-info/PKG-INFO +17 -0
- qthinking-0.0.2/qthinking.egg-info/SOURCES.txt +55 -0
- qthinking-0.0.2/qthinking.egg-info/dependency_links.txt +1 -0
- qthinking-0.0.2/qthinking.egg-info/entry_points.txt +2 -0
- qthinking-0.0.2/qthinking.egg-info/requires.txt +7 -0
- qthinking-0.0.2/qthinking.egg-info/top_level.txt +1 -0
- qthinking-0.0.2/setup.cfg +4 -0
- qthinking-0.0.2/setup.py +44 -0
qthinking-0.0.2/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright (c) 2018 Python Packaging Authority
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
recursive-include qthinking *.py *.so *.pyi
|
qthinking-0.0.2/PKG-INFO
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: qthinking
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Author: buchowatom
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: matplotlib>=3.11.2
|
|
10
|
+
Requires-Dist: numpy>=2.5.4
|
|
11
|
+
Requires-Dist: qutip>=5.3.1
|
|
12
|
+
Requires-Dist: scikit-learn>=1.9.1
|
|
13
|
+
Requires-Dist: scipy>=1.18.1
|
|
14
|
+
Requires-Dist: setuptools>=84.2.1
|
|
15
|
+
Requires-Dist: twine>=7.0.0
|
|
16
|
+
Dynamic: author
|
|
17
|
+
Dynamic: license-file
|
|
File without changes
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "qthinking"
|
|
3
|
+
version = "0.0.2"
|
|
4
|
+
description = "Add your description here"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"matplotlib>=3.11.2",
|
|
9
|
+
"numpy>=2.5.4",
|
|
10
|
+
"qutip>=5.3.1",
|
|
11
|
+
"scikit-learn>=1.9.1",
|
|
12
|
+
"scipy>=1.18.1",
|
|
13
|
+
"setuptools>=84.2.1",
|
|
14
|
+
"twine>=7.0.0",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.scripts]
|
|
18
|
+
qthinking = "qthinking:main"
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = ["uv_build>=0.12.12,<0.13.0"]
|
|
22
|
+
build-backend = "uv_build"
|
|
23
|
+
|
|
24
|
+
[tool.uv]
|
|
25
|
+
index-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Public package entry point for the neutral-atom Analog SDK.
|
|
2
|
+
|
|
3
|
+
The package exposes backend-independent Analog programs, reset-per-sample QELM
|
|
4
|
+
feature maps, state-carrying QRC models and classical readouts. QuTiP remains an
|
|
5
|
+
optional execution backend, so a future hardware adapter can consume the same
|
|
6
|
+
program objects.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from . import analog, backends, ml, qelm, qrc, applications
|
|
10
|
+
from .analog import rb87_program, rydberg_program
|
|
11
|
+
from .errors import (
|
|
12
|
+
ApplicationValidationError,
|
|
13
|
+
AnalogValidationError,
|
|
14
|
+
BackendError,
|
|
15
|
+
BackendExecutionError,
|
|
16
|
+
BackendNotAvailableError,
|
|
17
|
+
FeatureMapValidationError,
|
|
18
|
+
MLValidationError,
|
|
19
|
+
ProgramValidationError,
|
|
20
|
+
QELMValidationError,
|
|
21
|
+
QRCAnalogSDKError,
|
|
22
|
+
QRCValidationError,
|
|
23
|
+
UnsupportedProgramError,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"ApplicationValidationError",
|
|
28
|
+
"AnalogValidationError",
|
|
29
|
+
"BackendError",
|
|
30
|
+
"BackendExecutionError",
|
|
31
|
+
"BackendNotAvailableError",
|
|
32
|
+
"FeatureMapValidationError",
|
|
33
|
+
"MLValidationError",
|
|
34
|
+
"ProgramValidationError",
|
|
35
|
+
"QELMValidationError",
|
|
36
|
+
"QRCAnalogSDKError",
|
|
37
|
+
"QRCValidationError",
|
|
38
|
+
"UnsupportedProgramError",
|
|
39
|
+
"analog",
|
|
40
|
+
"applications",
|
|
41
|
+
"backends",
|
|
42
|
+
"ml",
|
|
43
|
+
"qelm",
|
|
44
|
+
"qrc",
|
|
45
|
+
"rb87_program",
|
|
46
|
+
"rydberg_program",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
__version__ = "0.6.0"
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Public backend-independent API for neutral-atom analog programs."""
|
|
2
|
+
|
|
3
|
+
from .controls import ControlSchedule, ControlValues, DetuningControl, RabiControl
|
|
4
|
+
from .dynamics import (
|
|
5
|
+
ClosedSystemDynamics,
|
|
6
|
+
DynamicsSpec,
|
|
7
|
+
LindbladDynamics,
|
|
8
|
+
LindbladRates,
|
|
9
|
+
)
|
|
10
|
+
from .hamiltonian import (
|
|
11
|
+
HamiltonianDriveParameters,
|
|
12
|
+
HamiltonianParameters,
|
|
13
|
+
RydbergHamiltonianSpec,
|
|
14
|
+
)
|
|
15
|
+
from .interaction import (
|
|
16
|
+
ExplicitInteraction,
|
|
17
|
+
InteractionNormalization,
|
|
18
|
+
InteractionSpec,
|
|
19
|
+
MatrixConvention,
|
|
20
|
+
RydbergInteraction,
|
|
21
|
+
)
|
|
22
|
+
from .measurement import MeasurementSpec, Observable
|
|
23
|
+
from .program import (
|
|
24
|
+
AnalogProgram,
|
|
25
|
+
BasisState,
|
|
26
|
+
DensityMatrixState,
|
|
27
|
+
InitialStateSpec,
|
|
28
|
+
ZeroState,
|
|
29
|
+
rydberg_program,
|
|
30
|
+
)
|
|
31
|
+
from .rb87 import (
|
|
32
|
+
DEFAULT_RB87_CAPABILITIES,
|
|
33
|
+
Rb87Capabilities,
|
|
34
|
+
Rb87TriangularArray,
|
|
35
|
+
Rb87TriangularInteraction,
|
|
36
|
+
mhz_to_rad_per_us,
|
|
37
|
+
rb87_program,
|
|
38
|
+
rb87_z_field_to_sdk_detuning,
|
|
39
|
+
rb87_z_from_sdk,
|
|
40
|
+
sdk_z_from_rb87,
|
|
41
|
+
)
|
|
42
|
+
from .results import ExecutionResult, SimulationResult
|
|
43
|
+
from .system import NeutralAtomSystem
|
|
44
|
+
from .sequence import AnalogSequence, blackman, constant, linear, sampled
|
|
45
|
+
from .waveforms import (
|
|
46
|
+
BlackmanWaveform,
|
|
47
|
+
ConstantWaveform,
|
|
48
|
+
LinearWaveform,
|
|
49
|
+
PiecewiseLinearWaveform,
|
|
50
|
+
PiecewiseConstantWaveform,
|
|
51
|
+
Waveform,
|
|
52
|
+
WaveformValue,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"AnalogProgram",
|
|
57
|
+
"AnalogSequence",
|
|
58
|
+
"BlackmanWaveform",
|
|
59
|
+
"BasisState",
|
|
60
|
+
"ClosedSystemDynamics",
|
|
61
|
+
"ConstantWaveform",
|
|
62
|
+
"ControlSchedule",
|
|
63
|
+
"ControlValues",
|
|
64
|
+
"DensityMatrixState",
|
|
65
|
+
"DEFAULT_RB87_CAPABILITIES",
|
|
66
|
+
"DetuningControl",
|
|
67
|
+
"DynamicsSpec",
|
|
68
|
+
"ExecutionResult",
|
|
69
|
+
"ExplicitInteraction",
|
|
70
|
+
"HamiltonianDriveParameters",
|
|
71
|
+
"HamiltonianParameters",
|
|
72
|
+
"InitialStateSpec",
|
|
73
|
+
"InteractionNormalization",
|
|
74
|
+
"InteractionSpec",
|
|
75
|
+
"LindbladDynamics",
|
|
76
|
+
"LindbladRates",
|
|
77
|
+
"LinearWaveform",
|
|
78
|
+
"MatrixConvention",
|
|
79
|
+
"MeasurementSpec",
|
|
80
|
+
"NeutralAtomSystem",
|
|
81
|
+
"Observable",
|
|
82
|
+
"PiecewiseLinearWaveform",
|
|
83
|
+
"PiecewiseConstantWaveform",
|
|
84
|
+
"RabiControl",
|
|
85
|
+
"Rb87Capabilities",
|
|
86
|
+
"Rb87TriangularArray",
|
|
87
|
+
"Rb87TriangularInteraction",
|
|
88
|
+
"RydbergHamiltonianSpec",
|
|
89
|
+
"RydbergInteraction",
|
|
90
|
+
"SimulationResult",
|
|
91
|
+
"Waveform",
|
|
92
|
+
"WaveformValue",
|
|
93
|
+
"ZeroState",
|
|
94
|
+
"mhz_to_rad_per_us",
|
|
95
|
+
"rb87_program",
|
|
96
|
+
"rb87_z_field_to_sdk_detuning",
|
|
97
|
+
"rb87_z_from_sdk",
|
|
98
|
+
"rydberg_program",
|
|
99
|
+
"sdk_z_from_rb87",
|
|
100
|
+
"blackman",
|
|
101
|
+
"constant",
|
|
102
|
+
"linear",
|
|
103
|
+
"sampled",
|
|
104
|
+
]
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Lazy Matplotlib helpers used by the public ``show()`` methods."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from numpy.typing import NDArray
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def show_atom_positions(
|
|
12
|
+
positions: NDArray,
|
|
13
|
+
*,
|
|
14
|
+
available_positions: NDArray | None = None,
|
|
15
|
+
ax: Any | None = None,
|
|
16
|
+
annotate: bool = False,
|
|
17
|
+
title: str = "Neutral-atom arrangement",
|
|
18
|
+
x_label: str = "x (um)",
|
|
19
|
+
y_label: str = "y (um)",
|
|
20
|
+
) -> Any:
|
|
21
|
+
"""Draw occupied atom positions and return the Matplotlib figure.
|
|
22
|
+
|
|
23
|
+
Matplotlib is imported only when this function is called. This keeps
|
|
24
|
+
model construction and backend execution usable in minimal server
|
|
25
|
+
environments that do not need plots.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
plt = _pyplot()
|
|
29
|
+
|
|
30
|
+
if ax is None:
|
|
31
|
+
_, ax = plt.subplots(figsize=(7.0, 4.8))
|
|
32
|
+
if available_positions is not None:
|
|
33
|
+
ax.scatter(
|
|
34
|
+
available_positions[:, 0],
|
|
35
|
+
available_positions[:, 1],
|
|
36
|
+
s=24,
|
|
37
|
+
color="lightgray",
|
|
38
|
+
label="available lattice sites",
|
|
39
|
+
zorder=1,
|
|
40
|
+
)
|
|
41
|
+
ax.scatter(
|
|
42
|
+
positions[:, 0],
|
|
43
|
+
positions[:, 1],
|
|
44
|
+
s=70,
|
|
45
|
+
color="tab:orange",
|
|
46
|
+
label="occupied sites",
|
|
47
|
+
zorder=2,
|
|
48
|
+
)
|
|
49
|
+
if annotate:
|
|
50
|
+
for atom, (x_value, y_value) in enumerate(positions):
|
|
51
|
+
ax.annotate(
|
|
52
|
+
str(atom),
|
|
53
|
+
(x_value, y_value),
|
|
54
|
+
xytext=(5, 5),
|
|
55
|
+
textcoords="offset points",
|
|
56
|
+
)
|
|
57
|
+
ax.set_title(title)
|
|
58
|
+
ax.set_xlabel(x_label)
|
|
59
|
+
ax.set_ylabel(y_label)
|
|
60
|
+
ax.set_aspect("equal")
|
|
61
|
+
ax.grid(alpha=0.25)
|
|
62
|
+
ax.legend()
|
|
63
|
+
ax.figure.tight_layout()
|
|
64
|
+
plt.show()
|
|
65
|
+
return ax.figure
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def show_matrix(
|
|
69
|
+
values: NDArray,
|
|
70
|
+
*,
|
|
71
|
+
ax: Any | None = None,
|
|
72
|
+
title: str = "Interaction matrix",
|
|
73
|
+
colorbar_label: str = "coupling",
|
|
74
|
+
cmap: str = "magma",
|
|
75
|
+
) -> Any:
|
|
76
|
+
"""Display one square matrix as a labeled heatmap and return its figure."""
|
|
77
|
+
|
|
78
|
+
plt = _pyplot()
|
|
79
|
+
if ax is None:
|
|
80
|
+
_, ax = plt.subplots(figsize=(5.5, 4.5))
|
|
81
|
+
image = ax.imshow(values, cmap=cmap)
|
|
82
|
+
ax.set_title(title)
|
|
83
|
+
ax.set_xlabel("atom j")
|
|
84
|
+
ax.set_ylabel("atom i")
|
|
85
|
+
colorbar = ax.figure.colorbar(image, ax=ax, shrink=0.85)
|
|
86
|
+
colorbar.set_label(colorbar_label)
|
|
87
|
+
ax.figure.tight_layout()
|
|
88
|
+
plt.show()
|
|
89
|
+
return ax.figure
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def show_waveform(
|
|
93
|
+
times_us: NDArray,
|
|
94
|
+
values: NDArray,
|
|
95
|
+
*,
|
|
96
|
+
ax: Any | None = None,
|
|
97
|
+
title: str = "Control waveform",
|
|
98
|
+
y_label: str = "value",
|
|
99
|
+
) -> Any:
|
|
100
|
+
"""Display a scalar or site-resolved waveform and return its figure."""
|
|
101
|
+
|
|
102
|
+
plt = _pyplot()
|
|
103
|
+
if ax is None:
|
|
104
|
+
_, ax = plt.subplots(figsize=(7.0, 3.5))
|
|
105
|
+
if values.ndim == 1:
|
|
106
|
+
ax.plot(times_us, values, label="global")
|
|
107
|
+
else:
|
|
108
|
+
for site in range(values.shape[1]):
|
|
109
|
+
ax.plot(times_us, values[:, site], label=f"atom {site}")
|
|
110
|
+
ax.set_title(title)
|
|
111
|
+
ax.set_xlabel("time (us)")
|
|
112
|
+
ax.set_ylabel(y_label)
|
|
113
|
+
ax.grid(alpha=0.25)
|
|
114
|
+
ax.legend()
|
|
115
|
+
ax.figure.tight_layout()
|
|
116
|
+
plt.show()
|
|
117
|
+
return ax.figure
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def show_execution_result(
|
|
121
|
+
*,
|
|
122
|
+
times_us: NDArray | None = None,
|
|
123
|
+
expectations: Mapping[str, NDArray] | None = None,
|
|
124
|
+
counts: Mapping[str, int] | None = None,
|
|
125
|
+
max_bitstrings: int = 20,
|
|
126
|
+
title: str | None = None,
|
|
127
|
+
) -> Any:
|
|
128
|
+
"""Display expectation trajectories, bitstring counts, or both."""
|
|
129
|
+
|
|
130
|
+
plt = _pyplot()
|
|
131
|
+
has_expectations = bool(expectations)
|
|
132
|
+
has_counts = counts is not None
|
|
133
|
+
panel_count = int(has_expectations) + int(has_counts)
|
|
134
|
+
if panel_count == 0:
|
|
135
|
+
raise ValueError("no expectations or bitstring counts are available to display.")
|
|
136
|
+
figure, axes = plt.subplots(
|
|
137
|
+
1,
|
|
138
|
+
panel_count,
|
|
139
|
+
figsize=(7.0 * panel_count, 3.8),
|
|
140
|
+
squeeze=False,
|
|
141
|
+
)
|
|
142
|
+
panels = iter(axes[0])
|
|
143
|
+
if has_expectations:
|
|
144
|
+
axis = next(panels)
|
|
145
|
+
if times_us is None or expectations is None:
|
|
146
|
+
raise ValueError("times_us are required for expectation plots.")
|
|
147
|
+
for name, values in expectations.items():
|
|
148
|
+
axis.plot(times_us, values, marker="o", label=name)
|
|
149
|
+
axis.set(
|
|
150
|
+
xlabel="time (us)",
|
|
151
|
+
ylabel="expectation",
|
|
152
|
+
title="Expectation values" if title is None else title,
|
|
153
|
+
)
|
|
154
|
+
axis.grid(alpha=0.25)
|
|
155
|
+
axis.legend()
|
|
156
|
+
if has_counts:
|
|
157
|
+
axis = next(panels)
|
|
158
|
+
if counts is None:
|
|
159
|
+
raise ValueError("counts are required for a bitstring plot.")
|
|
160
|
+
selected = sorted(
|
|
161
|
+
sorted(counts.items(), key=lambda item: (-item[1], item[0]))[
|
|
162
|
+
:max_bitstrings
|
|
163
|
+
]
|
|
164
|
+
)
|
|
165
|
+
axis.bar(
|
|
166
|
+
[bitstring for bitstring, _ in selected],
|
|
167
|
+
[count for _, count in selected],
|
|
168
|
+
)
|
|
169
|
+
axis.set(
|
|
170
|
+
xlabel="bitstring",
|
|
171
|
+
ylabel="shots",
|
|
172
|
+
title="Bitstring counts" if title is None or has_expectations else title,
|
|
173
|
+
)
|
|
174
|
+
axis.tick_params(axis="x", rotation=45 if len(selected) > 8 else 0)
|
|
175
|
+
figure.tight_layout()
|
|
176
|
+
plt.show()
|
|
177
|
+
return figure
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _pyplot() -> Any:
|
|
181
|
+
"""Import Matplotlib only when a public visualization is requested."""
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
import matplotlib.pyplot as plt
|
|
185
|
+
except ImportError as exc:
|
|
186
|
+
raise ImportError(
|
|
187
|
+
"show() requires Matplotlib; install it with "
|
|
188
|
+
"`pip install qrc-analog-sdk[plot]`."
|
|
189
|
+
) from exc
|
|
190
|
+
return plt
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Shared validation helpers used by the Analog data model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from numbers import Integral, Real
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from numpy.typing import ArrayLike, NDArray
|
|
9
|
+
|
|
10
|
+
from qthinking.errors import AnalogValidationError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def finite_float(
|
|
14
|
+
value: Real,
|
|
15
|
+
name: str,
|
|
16
|
+
*,
|
|
17
|
+
minimum: float | None = None,
|
|
18
|
+
strict_minimum: bool = False,
|
|
19
|
+
) -> float:
|
|
20
|
+
"""Return a finite real scalar, optionally constrained by a lower bound."""
|
|
21
|
+
|
|
22
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real):
|
|
23
|
+
raise AnalogValidationError(f"{name} must be a real scalar; got {value!r}.")
|
|
24
|
+
result = float(value)
|
|
25
|
+
if not np.isfinite(result):
|
|
26
|
+
raise AnalogValidationError(f"{name} must be finite; got {result!r}.")
|
|
27
|
+
if minimum is not None:
|
|
28
|
+
valid = result > minimum if strict_minimum else result >= minimum
|
|
29
|
+
if not valid:
|
|
30
|
+
operator = ">" if strict_minimum else ">="
|
|
31
|
+
raise AnalogValidationError(f"{name} must be {operator} {minimum}.")
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def positive_int(value: Integral, name: str) -> int:
|
|
36
|
+
"""Return a strictly positive integer; booleans are not accepted."""
|
|
37
|
+
|
|
38
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral):
|
|
39
|
+
raise AnalogValidationError(f"{name} must be an integer; got {value!r}.")
|
|
40
|
+
result = int(value)
|
|
41
|
+
if result < 1:
|
|
42
|
+
raise AnalogValidationError(f"{name} must be >= 1; got {result}.")
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def readonly_float_array(
|
|
47
|
+
value: ArrayLike,
|
|
48
|
+
name: str,
|
|
49
|
+
*,
|
|
50
|
+
ndim: int | None = None,
|
|
51
|
+
shape: tuple[int | None, ...] | None = None,
|
|
52
|
+
allow_empty: bool = False,
|
|
53
|
+
) -> NDArray[np.float64]:
|
|
54
|
+
"""Return an owned, finite, C-contiguous and read-only float array."""
|
|
55
|
+
|
|
56
|
+
return _readonly_numeric_array(
|
|
57
|
+
value, name, np.float64, ndim=ndim, shape=shape, allow_empty=allow_empty
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def readonly_complex_array(
|
|
62
|
+
value: ArrayLike,
|
|
63
|
+
name: str,
|
|
64
|
+
*,
|
|
65
|
+
ndim: int | None = None,
|
|
66
|
+
shape: tuple[int | None, ...] | None = None,
|
|
67
|
+
allow_empty: bool = False,
|
|
68
|
+
) -> NDArray[np.complex128]:
|
|
69
|
+
"""Return an owned, finite, C-contiguous and read-only complex array."""
|
|
70
|
+
|
|
71
|
+
return _readonly_numeric_array(
|
|
72
|
+
value, name, np.complex128, ndim=ndim, shape=shape, allow_empty=allow_empty
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def readonly_int_array(
|
|
77
|
+
value: ArrayLike,
|
|
78
|
+
name: str,
|
|
79
|
+
*,
|
|
80
|
+
ndim: int | None = None,
|
|
81
|
+
shape: tuple[int | None, ...] | None = None,
|
|
82
|
+
allow_empty: bool = False,
|
|
83
|
+
) -> NDArray[np.int64]:
|
|
84
|
+
"""Return a read-only integer array without silently truncating floats."""
|
|
85
|
+
|
|
86
|
+
raw = np.asarray(value)
|
|
87
|
+
if raw.dtype.kind not in "iu":
|
|
88
|
+
raise AnalogValidationError(f"{name} must contain integer values.")
|
|
89
|
+
try:
|
|
90
|
+
result = np.array(raw, dtype=np.int64, order="C", copy=True)
|
|
91
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
92
|
+
raise AnalogValidationError(f"{name} must contain valid integers.") from exc
|
|
93
|
+
_check_shape(result, name, ndim, shape, allow_empty)
|
|
94
|
+
result.setflags(write=False)
|
|
95
|
+
return result
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def site_vector(
|
|
99
|
+
value: ArrayLike,
|
|
100
|
+
n_atoms: int,
|
|
101
|
+
name: str,
|
|
102
|
+
*,
|
|
103
|
+
nonnegative: bool = False,
|
|
104
|
+
) -> NDArray[np.float64]:
|
|
105
|
+
"""Broadcast a scalar or validate a length-N value as a read-only site vector."""
|
|
106
|
+
|
|
107
|
+
array = readonly_float_array(value, name)
|
|
108
|
+
if array.ndim == 0:
|
|
109
|
+
result = np.full(n_atoms, float(array), dtype=np.float64)
|
|
110
|
+
elif array.shape == (n_atoms,):
|
|
111
|
+
result = np.array(array, copy=True)
|
|
112
|
+
else:
|
|
113
|
+
raise AnalogValidationError(
|
|
114
|
+
f"{name} must be scalar or have shape ({n_atoms},); got {array.shape}."
|
|
115
|
+
)
|
|
116
|
+
if nonnegative and np.any(result < 0.0):
|
|
117
|
+
raise AnalogValidationError(f"{name} must be non-negative.")
|
|
118
|
+
result.setflags(write=False)
|
|
119
|
+
return result
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _readonly_numeric_array(
|
|
123
|
+
value: ArrayLike,
|
|
124
|
+
name: str,
|
|
125
|
+
dtype: type[np.float64] | type[np.complex128],
|
|
126
|
+
*,
|
|
127
|
+
ndim: int | None,
|
|
128
|
+
shape: tuple[int | None, ...] | None,
|
|
129
|
+
allow_empty: bool,
|
|
130
|
+
):
|
|
131
|
+
"""Implement common float and complex array conversion."""
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
result = np.array(value, dtype=dtype, order="C", copy=True)
|
|
135
|
+
except (TypeError, ValueError, OverflowError) as exc:
|
|
136
|
+
raise AnalogValidationError(f"{name} must contain numeric values.") from exc
|
|
137
|
+
_check_shape(result, name, ndim, shape, allow_empty)
|
|
138
|
+
if not np.all(np.isfinite(result)):
|
|
139
|
+
raise AnalogValidationError(f"{name} must contain only finite values.")
|
|
140
|
+
result.setflags(write=False)
|
|
141
|
+
return result
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _check_shape(
|
|
145
|
+
array: np.ndarray,
|
|
146
|
+
name: str,
|
|
147
|
+
ndim: int | None,
|
|
148
|
+
shape: tuple[int | None, ...] | None,
|
|
149
|
+
allow_empty: bool,
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Apply shared size and shape constraints."""
|
|
152
|
+
|
|
153
|
+
if not allow_empty and array.size == 0:
|
|
154
|
+
raise AnalogValidationError(f"{name} must not be empty.")
|
|
155
|
+
if ndim is not None and array.ndim != ndim:
|
|
156
|
+
raise AnalogValidationError(f"{name} must have {ndim} dimensions.")
|
|
157
|
+
if shape is None:
|
|
158
|
+
return
|
|
159
|
+
matches = array.ndim == len(shape) and all(
|
|
160
|
+
expected is None or actual == expected
|
|
161
|
+
for actual, expected in zip(array.shape, shape)
|
|
162
|
+
)
|
|
163
|
+
if not matches:
|
|
164
|
+
raise AnalogValidationError(f"{name} must have shape {shape}; got {array.shape}.")
|