cqlib-pulse 0.1.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.
@@ -0,0 +1,89 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2026 China Telecom Quantum Group.
4
+ #
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ #
9
+ # Any modifications or derivative works of this code must retain this
10
+ # copyright notice, and modified files need to carry a notice indicating
11
+ # that they have been altered from the originals.
12
+
13
+ """Standalone Python pulse module for Cqlib."""
14
+
15
+ from importlib.metadata import version as _distribution_version
16
+
17
+ from .cloud import (
18
+ CloudPulseVisualizer,
19
+ TianyanAuthClient,
20
+ TianyanWaveformClient,
21
+ WaveformAPI,
22
+ WaveformJob,
23
+ )
24
+ from .core import (
25
+ PXY,
26
+ PZ,
27
+ PZ0,
28
+ CosineWaveform,
29
+ CouplerQubit,
30
+ FlattopWaveform,
31
+ G,
32
+ NumericWaveform,
33
+ Operation,
34
+ PulseCircuit,
35
+ PulseInstruction,
36
+ PulseOperation,
37
+ PulseTarget,
38
+ Qubit,
39
+ ScheduledOperation,
40
+ SlepianWaveform,
41
+ StandardOperation,
42
+ Waveform,
43
+ WaveformType,
44
+ )
45
+ from .errors import (
46
+ PulseError,
47
+ PulseValidationError,
48
+ QCISParseError,
49
+ TianyanAuthenticationError,
50
+ WaveformAPIError,
51
+ )
52
+ from .qcis import dumps as qcis_dumps
53
+ from .qcis import loads as qcis_loads
54
+
55
+ __version__ = _distribution_version("cqlib-pulse")
56
+
57
+ __all__ = [
58
+ "CloudPulseVisualizer",
59
+ "CosineWaveform",
60
+ "CouplerQubit",
61
+ "FlattopWaveform",
62
+ "G",
63
+ "NumericWaveform",
64
+ "Operation",
65
+ "PulseCircuit",
66
+ "PulseError",
67
+ "PulseInstruction",
68
+ "PulseOperation",
69
+ "PulseTarget",
70
+ "PulseValidationError",
71
+ "PXY",
72
+ "PZ",
73
+ "PZ0",
74
+ "QCISParseError",
75
+ "Qubit",
76
+ "SlepianWaveform",
77
+ "ScheduledOperation",
78
+ "StandardOperation",
79
+ "TianyanAuthClient",
80
+ "TianyanAuthenticationError",
81
+ "TianyanWaveformClient",
82
+ "Waveform",
83
+ "WaveformAPI",
84
+ "WaveformAPIError",
85
+ "WaveformJob",
86
+ "WaveformType",
87
+ "qcis_dumps",
88
+ "qcis_loads",
89
+ ]
@@ -0,0 +1,29 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2026 China Telecom Quantum Group.
4
+ #
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ #
9
+ # Any modifications or derivative works of this code must retain this
10
+ # copyright notice, and modified files need to carry a notice indicating
11
+ # that they have been altered from the originals.
12
+
13
+ """Tianyan waveform visualization adapters."""
14
+
15
+ from .auth import TianyanAuthClient
16
+ from .visualization import (
17
+ CloudPulseVisualizer,
18
+ TianyanWaveformClient,
19
+ WaveformAPI,
20
+ WaveformJob,
21
+ )
22
+
23
+ __all__ = [
24
+ "CloudPulseVisualizer",
25
+ "TianyanAuthClient",
26
+ "TianyanWaveformClient",
27
+ "WaveformAPI",
28
+ "WaveformJob",
29
+ ]
@@ -0,0 +1,99 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2026 China Telecom Quantum Group.
4
+ #
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ #
9
+ # Any modifications or derivative works of this code must retain this
10
+ # copyright notice, and modified files need to carry a notice indicating
11
+ # that they have been altered from the originals.
12
+
13
+ """Tianyan API-key authentication without credential persistence."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from typing import cast
19
+ from urllib.error import HTTPError, URLError
20
+ from urllib.parse import urlencode
21
+ from urllib.request import Request, urlopen
22
+
23
+ from ..errors import TianyanAuthenticationError
24
+
25
+ DEFAULT_TIANYAN_URL = "https://qc.zdxlz.com"
26
+ LOGIN_PATH = "/qccp-auth/oauth2/sdk/opnId"
27
+ SDK_BASIC_AUTHORIZATION = "Basic d2ViQXBwOndlYkFwcA=="
28
+
29
+
30
+ class TianyanAuthClient:
31
+ """Exchange a personal-center API Key for a short-lived access token."""
32
+
33
+ def __init__(
34
+ self,
35
+ api_key: str,
36
+ *,
37
+ base_url: str = DEFAULT_TIANYAN_URL,
38
+ request_timeout_secs: float = 30,
39
+ ) -> None:
40
+ if not isinstance(api_key, str) or not api_key.strip():
41
+ raise ValueError("api_key must be a non-empty string")
42
+ if not isinstance(base_url, str) or not base_url.startswith(("http://", "https://")):
43
+ raise ValueError("base_url must start with http:// or https://")
44
+ if request_timeout_secs <= 0:
45
+ raise ValueError("request_timeout_secs must be positive")
46
+ self._api_key = api_key
47
+ self.base_url = base_url.rstrip("/")
48
+ self.request_timeout_secs = request_timeout_secs
49
+
50
+ def get_access_token(self) -> str:
51
+ """Perform one login exchange and return ``data.access_token``."""
52
+
53
+ body = urlencode(
54
+ {
55
+ "grant_type": "openId",
56
+ "openId": self._api_key,
57
+ "account_type": "member",
58
+ }
59
+ ).encode("utf-8")
60
+ request = Request(
61
+ f"{self.base_url}{LOGIN_PATH}",
62
+ data=body,
63
+ method="POST",
64
+ headers={
65
+ "Accept": "application/json",
66
+ "Authorization": SDK_BASIC_AUTHORIZATION,
67
+ "Content-Type": "application/x-www-form-urlencoded",
68
+ },
69
+ )
70
+ result = self._send(request)
71
+ if result.get("code", 0) != 0:
72
+ message = result.get("message") or result.get("msg") or "unknown error"
73
+ raise TianyanAuthenticationError(f"Tianyan login failed: {message}")
74
+
75
+ token = result.get("access_token")
76
+ data = result.get("data")
77
+ if not token and isinstance(data, dict):
78
+ token = data.get("access_token")
79
+ if not isinstance(token, str) or not token:
80
+ raise TianyanAuthenticationError("Tianyan login response is missing data.access_token")
81
+ return token
82
+
83
+ def _send(self, request: Request) -> dict[str, object]:
84
+ try:
85
+ with urlopen(request, timeout=self.request_timeout_secs) as response:
86
+ result = json.loads(response.read().decode("utf-8"))
87
+ except HTTPError as exc:
88
+ raise TianyanAuthenticationError(
89
+ f"Tianyan login returned HTTP {exc.code}: {exc.reason}"
90
+ ) from exc
91
+ except URLError as exc:
92
+ raise TianyanAuthenticationError(
93
+ f"Unable to reach Tianyan login API: {exc.reason}"
94
+ ) from exc
95
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
96
+ raise TianyanAuthenticationError("Tianyan login API returned invalid JSON") from exc
97
+ if not isinstance(result, dict):
98
+ raise TianyanAuthenticationError("Tianyan login response must be a JSON object")
99
+ return cast(dict[str, object], result)
@@ -0,0 +1,266 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2026 China Telecom Quantum Group.
4
+ #
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ #
9
+ # Any modifications or derivative works of this code must retain this
10
+ # copyright notice, and modified files need to carry a notice indicating
11
+ # that they have been altered from the originals.
12
+
13
+ """Cloud pulse-waveform visualization workflow."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import time
19
+ from collections.abc import Callable
20
+ from dataclasses import dataclass
21
+ from typing import Protocol, cast, runtime_checkable
22
+ from urllib.error import HTTPError, URLError
23
+ from urllib.parse import urlencode
24
+ from urllib.request import Request, urlopen
25
+
26
+ from ..core.circuit import PulseCircuit
27
+ from ..errors import WaveformAPIError
28
+ from .auth import DEFAULT_TIANYAN_URL, TianyanAuthClient
29
+
30
+ CREATE_WAVEFORM_PATH = "/qccp-quantum/sdk/generateWaveformDiagram"
31
+ QUERY_WAVEFORM_PATH = "/qccp-quantum/sdk/getWaveformDiagram"
32
+
33
+
34
+ @runtime_checkable
35
+ class WaveformAPI(Protocol):
36
+ """The two cloud operations needed for waveform visualization.
37
+
38
+ :class:`TianyanWaveformClient` implements this protocol over HTTP. Other
39
+ platform adapters and test doubles can implement the same two methods.
40
+ """
41
+
42
+ def create_waveform_data(
43
+ self,
44
+ circuit: str,
45
+ circuit_name: str | None = None,
46
+ is_verify: bool = True,
47
+ ) -> int | str: ...
48
+
49
+ def query_waveform_data(self, query_id: int | str) -> str | None: ...
50
+
51
+
52
+ @dataclass(frozen=True, slots=True)
53
+ class WaveformJob:
54
+ """Cloud waveform-generation task identifier."""
55
+
56
+ query_id: int | str
57
+
58
+
59
+ class TianyanWaveformClient:
60
+ """HTTP client for the two Tianyan waveform-diagram endpoints.
61
+
62
+ ``token`` is sent only in the request header. ``qc_code`` is serialized as
63
+ the create endpoint's ``qcCode`` field.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ token: str,
69
+ qc_code: str,
70
+ *,
71
+ base_url: str = DEFAULT_TIANYAN_URL,
72
+ request_timeout_secs: float = 30,
73
+ _token_provider: Callable[[], str] | None = None,
74
+ ) -> None:
75
+ if not isinstance(token, str) or not token.strip():
76
+ raise ValueError("token must be a non-empty string")
77
+ if not isinstance(qc_code, str) or not qc_code.strip():
78
+ raise ValueError("qc_code must be a non-empty string")
79
+ if not isinstance(base_url, str) or not base_url.startswith(("http://", "https://")):
80
+ raise ValueError("base_url must start with http:// or https://")
81
+ if request_timeout_secs <= 0:
82
+ raise ValueError("request_timeout_secs must be positive")
83
+ self._token = token
84
+ self.qc_code = qc_code
85
+ self.base_url = base_url.rstrip("/")
86
+ self.request_timeout_secs = request_timeout_secs
87
+ self._token_provider = _token_provider
88
+
89
+ @classmethod
90
+ def from_api_key(
91
+ cls,
92
+ api_key: str,
93
+ qc_code: str,
94
+ *,
95
+ base_url: str = DEFAULT_TIANYAN_URL,
96
+ request_timeout_secs: float = 30,
97
+ ) -> TianyanWaveformClient:
98
+ """Log in with an API Key and retain an in-memory refresh provider."""
99
+
100
+ auth = TianyanAuthClient(
101
+ api_key,
102
+ base_url=base_url,
103
+ request_timeout_secs=request_timeout_secs,
104
+ )
105
+ return cls(
106
+ auth.get_access_token(),
107
+ qc_code,
108
+ base_url=base_url,
109
+ request_timeout_secs=request_timeout_secs,
110
+ _token_provider=auth.get_access_token,
111
+ )
112
+
113
+ def create_waveform_data(
114
+ self,
115
+ circuit: str,
116
+ circuit_name: str | None = None,
117
+ is_verify: bool = True,
118
+ ) -> int | str:
119
+ if not isinstance(circuit, str) or not circuit.strip():
120
+ raise ValueError("circuit must contain non-empty QCIS")
121
+ payload: dict[str, object] = {
122
+ "circuit": circuit,
123
+ "qcCode": self.qc_code,
124
+ "circuitName": circuit_name,
125
+ "isVerify": is_verify,
126
+ }
127
+ data = self._request_json("POST", CREATE_WAVEFORM_PATH, payload=payload)
128
+ query_id = data.get("id")
129
+ if isinstance(query_id, bool) or not isinstance(query_id, (int, str)) or query_id == "":
130
+ raise WaveformAPIError("Waveform creation response data.id must be an int or string")
131
+ return query_id
132
+
133
+ def query_waveform_data(self, query_id: int | str) -> str | None:
134
+ if isinstance(query_id, bool) or not isinstance(query_id, (int, str)) or query_id == "":
135
+ raise ValueError("query_id must be a non-empty integer or string")
136
+ data = self._request_json(
137
+ "GET",
138
+ QUERY_WAVEFORM_PATH,
139
+ params={"id": query_id},
140
+ )
141
+ url = data.get("visibleUrl")
142
+ if url in (None, ""):
143
+ return None
144
+ if not isinstance(url, str):
145
+ raise WaveformAPIError("Waveform query response data.visibleUrl must be a string")
146
+ return url
147
+
148
+ def _request_json(
149
+ self,
150
+ method: str,
151
+ path: str,
152
+ *,
153
+ payload: dict[str, object] | None = None,
154
+ params: dict[str, int | str] | None = None,
155
+ ) -> dict[str, object]:
156
+ url = f"{self.base_url}{path}"
157
+ if params:
158
+ url = f"{url}?{urlencode(params)}"
159
+ body = None if payload is None else json.dumps(payload).encode("utf-8")
160
+ refreshed = False
161
+ while True:
162
+ request = Request(
163
+ url,
164
+ data=body,
165
+ method=method,
166
+ headers={
167
+ "Accept": "application/json",
168
+ "Authorization": f"Bearer {self._token}",
169
+ "basicToken": self._token,
170
+ "Content-Type": "application/json",
171
+ "token": self._token,
172
+ },
173
+ )
174
+ try:
175
+ with urlopen(request, timeout=self.request_timeout_secs) as response:
176
+ result = json.loads(response.read().decode("utf-8"))
177
+ break
178
+ except HTTPError as exc:
179
+ if exc.code == 401 and self._token_provider is not None and not refreshed:
180
+ self._token = self._token_provider()
181
+ refreshed = True
182
+ continue
183
+ raise WaveformAPIError(
184
+ f"Waveform API returned HTTP {exc.code}: {exc.reason}"
185
+ ) from exc
186
+ except URLError as exc:
187
+ raise WaveformAPIError(f"Unable to reach waveform API: {exc.reason}") from exc
188
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
189
+ raise WaveformAPIError("Waveform API returned invalid JSON") from exc
190
+
191
+ if not isinstance(result, dict):
192
+ raise WaveformAPIError("Waveform API response must be a JSON object")
193
+ data = result.get("data")
194
+ if not isinstance(data, dict):
195
+ message = result.get("message") or result.get("msg") or "missing data object"
196
+ raise WaveformAPIError(f"Waveform API request failed: {message}")
197
+ return cast(dict[str, object], data)
198
+
199
+
200
+ class CloudPulseVisualizer:
201
+ """Call the cloud create/query APIs and return the generated asset URL."""
202
+
203
+ def __init__(self, api: WaveformAPI) -> None:
204
+ self.api = api
205
+
206
+ def create(
207
+ self,
208
+ circuit: PulseCircuit | str,
209
+ *,
210
+ circuit_name: str | None = None,
211
+ is_verify: bool = True,
212
+ ) -> WaveformJob:
213
+ qcis = circuit.to_qcis() if isinstance(circuit, PulseCircuit) else circuit
214
+ if not isinstance(qcis, str) or not qcis.strip():
215
+ raise ValueError("circuit must contain non-empty QCIS")
216
+ query_id = self.api.create_waveform_data(
217
+ qcis,
218
+ circuit_name=circuit_name,
219
+ is_verify=is_verify,
220
+ )
221
+ if query_id is None or query_id == "":
222
+ raise RuntimeError("Cloud waveform API returned an empty query id")
223
+ return WaveformJob(query_id)
224
+
225
+ def query(self, job: WaveformJob | int | str) -> str | None:
226
+ query_id = job.query_id if isinstance(job, WaveformJob) else job
227
+ return self.api.query_waveform_data(query_id)
228
+
229
+ def wait(
230
+ self,
231
+ job: WaveformJob | int | str,
232
+ *,
233
+ timeout_secs: float = 300,
234
+ poll_interval_secs: float = 3,
235
+ ) -> str:
236
+ """Poll until the cloud returns a visualization URL or timeout expires."""
237
+
238
+ if timeout_secs <= 0 or poll_interval_secs <= 0:
239
+ raise ValueError("timeout_secs and poll_interval_secs must be positive")
240
+ deadline = time.monotonic() + timeout_secs
241
+ while True:
242
+ url = self.query(job)
243
+ if url:
244
+ return url
245
+ remaining = deadline - time.monotonic()
246
+ if remaining <= 0:
247
+ raise TimeoutError("Timed out waiting for pulse waveform visualization")
248
+ time.sleep(min(poll_interval_secs, remaining))
249
+
250
+ def visualize(
251
+ self,
252
+ circuit: PulseCircuit | str,
253
+ *,
254
+ circuit_name: str | None = None,
255
+ is_verify: bool = True,
256
+ timeout_secs: float = 300,
257
+ poll_interval_secs: float = 3,
258
+ ) -> str:
259
+ """Create a cloud waveform task and wait for its visualization URL."""
260
+
261
+ job = self.create(circuit, circuit_name=circuit_name, is_verify=is_verify)
262
+ return self.wait(
263
+ job,
264
+ timeout_secs=timeout_secs,
265
+ poll_interval_secs=poll_interval_secs,
266
+ )
@@ -0,0 +1,48 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2026 China Telecom Quantum Group.
4
+ #
5
+ # This code is licensed under the Apache License, Version 2.0. You may
6
+ # obtain a copy of this license in the LICENSE file in the root directory
7
+ # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
+ #
9
+ # Any modifications or derivative works of this code must retain this
10
+ # copyright notice, and modified files need to carry a notice indicating
11
+ # that they have been altered from the originals.
12
+
13
+ """Pulse targets, waveforms, instructions, operations and circuits."""
14
+
15
+ from .circuit import PulseCircuit
16
+ from .instructions import PXY, PZ, PZ0, G, PulseInstruction
17
+ from .operations import Operation, PulseOperation, ScheduledOperation, StandardOperation
18
+ from .targets import CouplerQubit, PulseTarget, Qubit
19
+ from .waveforms import (
20
+ CosineWaveform,
21
+ FlattopWaveform,
22
+ NumericWaveform,
23
+ SlepianWaveform,
24
+ Waveform,
25
+ WaveformType,
26
+ )
27
+
28
+ __all__ = [
29
+ "CosineWaveform",
30
+ "CouplerQubit",
31
+ "FlattopWaveform",
32
+ "G",
33
+ "NumericWaveform",
34
+ "Operation",
35
+ "PulseCircuit",
36
+ "PulseInstruction",
37
+ "PulseOperation",
38
+ "PulseTarget",
39
+ "PXY",
40
+ "PZ",
41
+ "PZ0",
42
+ "Qubit",
43
+ "ScheduledOperation",
44
+ "SlepianWaveform",
45
+ "StandardOperation",
46
+ "Waveform",
47
+ "WaveformType",
48
+ ]