cqlib-adapter 0.3.2__tar.gz → 0.3.3__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.
Files changed (32) hide show
  1. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/PKG-INFO +1 -1
  2. cqlib_adapter-0.3.3/cqlib_adapter/VERSION.txt +1 -0
  3. cqlib_adapter-0.3.3/cqlib_adapter/utils/api_client.py +210 -0
  4. cqlib_adapter-0.3.3/cqlib_adapter/utils/converter.py +474 -0
  5. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter.egg-info/PKG-INFO +1 -1
  6. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter.egg-info/SOURCES.txt +3 -1
  7. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/pyproject.toml +3 -3
  8. cqlib_adapter-0.3.2/cqlib_adapter/VERSION.txt +0 -1
  9. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/LICENSE +0 -0
  10. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/README.md +0 -0
  11. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/__init__.py +0 -0
  12. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/_version.py +0 -0
  13. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/__init__.py +0 -0
  14. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/circuit_executor.py +0 -0
  15. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/compilation.py +0 -0
  16. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/cqlib_config.toml +0 -0
  17. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/device.py +0 -0
  18. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/ext_mapping.py +0 -0
  19. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/pennylane_ext/native_gates.py +0 -0
  20. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/__init__.py +0 -0
  21. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/gates.py +0 -0
  22. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/job.py +0 -0
  23. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/sampler.py +0 -0
  24. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/submit_job.py +0 -0
  25. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/tianyan_backend.py +0 -0
  26. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter/qiskit_ext/tianyan_provider.py +0 -0
  27. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter.egg-info/dependency_links.txt +0 -0
  28. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter.egg-info/entry_points.txt +0 -0
  29. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter.egg-info/requires.txt +0 -0
  30. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/cqlib_adapter.egg-info/top_level.txt +0 -0
  31. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/requirements.txt +0 -0
  32. {cqlib_adapter-0.3.2 → cqlib_adapter-0.3.3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cqlib-adapter
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: Cqlib adapter
5
5
  Author-email: China Telecom Quantum Group Quantum Computing Team <tianyan@chinatelecom.cn>
6
6
  License-Expression: Apache-2.0
@@ -0,0 +1 @@
1
+ 0.3.3
@@ -0,0 +1,210 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2025-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
+ """
14
+ API Client module for interacting with quantum computing platforms.
15
+ """
16
+ import os
17
+ import time
18
+ from datetime import datetime
19
+
20
+ import requests
21
+ from cqlib.circuits import Circuit
22
+ from cqlib.exceptions import CqlibRequestError
23
+ from cqlib.quantum_platform import TianYanPlatform, QuantumLanguage
24
+
25
+
26
+ class ApiClient:
27
+ """
28
+ A client for managing API interactions with a quantum computing platform.
29
+
30
+ Attributes
31
+ ----------
32
+ base_url : str
33
+ The base URL for the API endpoints.
34
+ backends : str
35
+ The endpoint for fetching available quantum backends.
36
+ quantum_computer_config : str
37
+ The endpoint for fetching all quantum computer configurations.
38
+ quantum_machine_config : str
39
+ The endpoint for fetching quantum machine configurations.
40
+ query_experiment_result : str
41
+ The endpoint for querying experiment results.
42
+ """
43
+ base_url = 'https://qc.zdxlz.com'
44
+ backends = "/qccp-quantum/experiments/quantum/computer/by/user"
45
+ quantum_computer_config = "/qccp-quantum/experiments/quantum/computer/config"
46
+ quantum_machine_config = '/qccp-quantum/sdk/experiment/download/config'
47
+ query_experiment_result = '/qccp-quantum/sdk/experiment/result/find'
48
+
49
+ def __init__(self, token: str = None, base_url: str | None = None) -> None:
50
+ """
51
+ Initializes the ApiClient with an optional token and base URL.
52
+
53
+ Args:
54
+ token(str): The authentication token for the API. If not provided,
55
+ it will be fetched from the environment variable CQLIB_TOKEN.
56
+ base_url(str): The base URL for the API endpoints. If not provided,
57
+ the default URL will be used.
58
+ """
59
+ if base_url is not None:
60
+ self.base_url = base_url
61
+ if token is None:
62
+ token = os.environ.get("CQLIB_TOKEN", "")
63
+ self.session = requests.Session()
64
+ self._token = token
65
+ if token is not None:
66
+ self._pf = TianYanPlatform(token)
67
+ else:
68
+ self._pf = None
69
+
70
+ @property
71
+ def platform(self) -> TianYanPlatform:
72
+ """
73
+ Returns the TianYanPlatform instance associated with the client.
74
+
75
+ Returns:
76
+ TianYanPlatform: The platform instance for managing quantum
77
+ computing tasks.
78
+ """
79
+ if self._pf is None:
80
+ self._pf = TianYanPlatform(self._token)
81
+ return self._pf
82
+
83
+ def get_backends(self) -> list[dict]:
84
+ """
85
+ Fetches the list of available quantum backends.
86
+
87
+ Returns:
88
+ list[dict]: A list of dictionaries containing information about
89
+ available quantum backends.
90
+ """
91
+ response = self.session.get(
92
+ f'{self.base_url}{self.backends}',
93
+ params={'a': str(int(time.time())), 'apiCode': 'byUser', },
94
+ headers={
95
+ 'Accept': 'application/json, text/plain, */*',
96
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0)'
97
+ ' Gecko/20100101 Firefox/137.0',
98
+ 'apiCode': 'byUser',
99
+ 'requestTime': self._request_time()
100
+ })
101
+ data = response.json()
102
+ if data.get('code') != 200:
103
+ raise CqlibRequestError(f"request error. \n{data.get('message')}")
104
+ return data.get('data', [])
105
+
106
+ def get_quantum_computer_config(self, computer_id) -> dict:
107
+ """
108
+ Fetches the configuration of a specific quantum computer.
109
+
110
+ Args:
111
+ computer_id(str): The ID of the quantum computer.
112
+
113
+ Returns:
114
+ dict: A dictionary containing the configuration details of the quantum computer.
115
+ """
116
+ response = self.session.get(
117
+ f'{self.base_url}{self.quantum_computer_config}',
118
+ params={
119
+ 'a': str(int(time.time())),
120
+ 'type': 'overview',
121
+ 'quantumComputerId': computer_id,
122
+ 'label': 'qubits,couplers,coupler_map,disabled_qubits,disabled_couplers'
123
+ },
124
+ headers={
125
+ 'Accept': 'application/json, text/plain, */*',
126
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) '
127
+ 'Gecko/20100101 Firefox/137.0',
128
+ 'apiCode': 'config',
129
+ 'requestTime': self._request_time()
130
+ })
131
+ data = response.json()
132
+ return data.get('data', {})
133
+
134
+ def get_quantum_machine_config(self, computer_code: str) -> dict:
135
+ """
136
+ Downloads the physical machine parameters for a quantum machine (not a simulator).
137
+
138
+ Args:
139
+ computer_code(str): The code of the quantum machine.
140
+
141
+ Returns:
142
+ dict: A dictionary containing the configuration details of the quantum machine.
143
+ """
144
+ return self.platform.download_config(machine=computer_code)
145
+
146
+ def submit_job(
147
+ self,
148
+ circuits: Circuit | list[Circuit],
149
+ machine: str,
150
+ **kwargs
151
+ ) -> list[str]:
152
+ """
153
+ Submits a job (or list of jobs) to a specified quantum machine.
154
+
155
+ Args:
156
+ circuits(Circuit | list[Circuit]): The quantum circuit(s) to be executed.
157
+ machine(str): The name of the quantum machine to execute the job.
158
+ **kwargs: Additional keyword arguments, such as the number of shots.
159
+
160
+ Returns:
161
+ list[str]: A list of task IDs for the submitted jobs.
162
+ """
163
+ if not isinstance(circuits, list):
164
+ circuits = [circuits]
165
+
166
+ task_ids = self.platform.submit_experiment(
167
+ [c.as_str() for c in circuits],
168
+ machine_name=machine,
169
+ language=QuantumLanguage.QCIS,
170
+ num_shots=kwargs.get('shots', 1000),
171
+ )
172
+ return task_ids
173
+
174
+ def query_job(self, task_ids: list[str]) -> list[dict]:
175
+ """
176
+ Queries the results of submitted jobs using their task IDs.
177
+
178
+ Args:
179
+ task_ids(list[str]): A list of task IDs to query.
180
+
181
+ Returns:
182
+ list[dict]: A list of dictionaries containing the results of the queried jobs.
183
+
184
+ Raises:
185
+ CqlibRequestError: If the request to query job results fails.
186
+ """
187
+ response = self.session.post(
188
+ f'{self.base_url}{self.query_experiment_result}',
189
+ json={"query_ids": task_ids},
190
+ headers={
191
+ 'Accept': 'application/json, text/plain, */*',
192
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) '
193
+ 'Gecko/20100101 Firefox/137.0',
194
+ 'apiCode': 'config',
195
+ 'requestTime': self._request_time(),
196
+ "basicToken": self.platform.access_token,
197
+ "Authorization": f'Bearer {self.platform.access_token}'
198
+ })
199
+ data = response.json()
200
+ if data.get('code') != 0:
201
+ raise CqlibRequestError(f"request error {data.get('msg')}")
202
+ return data.get('data').get('experimentResultModelList')
203
+
204
+ @staticmethod
205
+ def _request_time() -> str:
206
+ """
207
+ Generates a formatted timestamp for API requests.
208
+ """
209
+ return datetime.now().strftime("%m/%d/%Y, %I:%M:%S %p") \
210
+ .replace("/0", "/").lstrip("0").replace(" 0", " ")
@@ -0,0 +1,474 @@
1
+ # This code is part of cqlib.
2
+ #
3
+ # Copyright (C) 2025-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
+
14
+ import sys
15
+ import numpy as np
16
+ from typing import Union
17
+ from qiskit import QuantumCircuit, transpile
18
+ from qiskit.circuit import ParameterExpression
19
+ from cqlib import Circuit
20
+ from cqlib import Parameter as CqlibParameter
21
+ import pennylane as qml
22
+ from pennylane.tape import QuantumTape
23
+
24
+ def qiskit_to_cqlib(
25
+ qiskit_qc: QuantumCircuit,
26
+ mapping: Union[dict, list] = None,
27
+ decompose: bool = False
28
+ ) -> Circuit:
29
+ """
30
+ Convert a Qiskit QuantumCircuit into a cqlib Circuit.
31
+
32
+ Features:
33
+ - Native support for complex parameter expressions.
34
+ - Recursive custom gate unwrapping.
35
+ - Buffered mid-circuit measurement handling to strictly preserve endianness.
36
+ - Strict Virtual-to-Physical Qubit Mapping (Layout routing) via physical qubit lists.
37
+
38
+ Args:
39
+ qiskit_qc (QuantumCircuit): The source Qiskit quantum circuit.
40
+ mapping (dict or list, optional): Mapping from Qiskit virtual qubit indices to
41
+ cqlib physical qubit indices. Must contain all
42
+ qubits used in the circuit if provided.
43
+ E.g., {0: 7, 1: 3, 2: 1} or [7, 3, 1]. Defaults to None.
44
+ decompose (bool): If True, transpiles the circuit to hardware basis gates.
45
+
46
+ Returns:
47
+ Circuit: The converted cqlib Circuit instance.
48
+
49
+ Raises:
50
+ ValueError: If a qubit index is missing from the provided mapping.
51
+ """
52
+
53
+ if decompose:
54
+ basis_gates = ['x', 'y', 'z','s','sdg','t', 'tdg', 'sx', 'sxdg', 'id', 'rx', 'ry', 'rz', 'p', 'cz', 'barrier', 'delay','measure']
55
+ qiskit_qc = transpile(qiskit_qc, basis_gates=basis_gates)
56
+
57
+ # ==========================================
58
+ # 2. Parameter Initialization
59
+ # ==========================================
60
+ param_mapping = {}
61
+ cqlib_params = []
62
+
63
+ for q_param in qiskit_qc.parameters:
64
+ cq_param = CqlibParameter(q_param.name)
65
+ param_mapping[q_param.name] = cq_param
66
+ cqlib_params.append(cq_param)
67
+
68
+ # ==========================================
69
+ # 3. Strict Virtual-to-Physical Qubit Mapping
70
+ # ==========================================
71
+ top_level_qubit_map = {}
72
+ physical_qubits_list = [] # To store the exact layout, e.g., [7, 3, 1]
73
+
74
+ for q in qiskit_qc.qubits:
75
+ v_idx = qiskit_qc.find_bit(q).index
76
+
77
+ # Determine the target physical index based on user mapping
78
+ if mapping is not None:
79
+ if isinstance(mapping, dict):
80
+ # Strict check: raise error if v_idx is missing from the dictionary
81
+ if v_idx not in mapping:
82
+ raise ValueError(
83
+ f"Virtual qubit index {v_idx} is missing from the provided mapping dictionary. "
84
+ f"Please ensure all qubits in the circuit are mapped."
85
+ )
86
+ p_idx = mapping[v_idx]
87
+ elif isinstance(mapping, (list, tuple)):
88
+ # Strict check: raise error if the list doesn't cover all qubits
89
+ if v_idx >= len(mapping):
90
+ raise ValueError(
91
+ f"Virtual qubit index {v_idx} exceeds the length of the provided mapping list. "
92
+ f"Please provide a mapping for every qubit."
93
+ )
94
+ p_idx = mapping[v_idx]
95
+ else:
96
+ raise TypeError("The 'mapping' parameter must be a dict or a list/tuple.")
97
+ else:
98
+ p_idx = v_idx
99
+
100
+ top_level_qubit_map[q] = p_idx
101
+ physical_qubits_list.append(p_idx)
102
+
103
+
104
+ cqlib_qc = Circuit(physical_qubits_list, parameters=cqlib_params)
105
+
106
+ # --- Helper: Parse Mathematical Parameters ---
107
+ def parse_param(q_param):
108
+ if isinstance(q_param, ParameterExpression):
109
+ if len(q_param.parameters) == 0:
110
+ return float(q_param)
111
+ elif len(q_param.parameters) == 1 and q_param == list(q_param.parameters)[0]:
112
+ return param_mapping[list(q_param.parameters)[0].name]
113
+ else:
114
+ expr_str = str(q_param)
115
+ local_env = {name: param for name, param in param_mapping.items()}
116
+ try:
117
+ return eval(expr_str, {"__builtins__": None}, local_env)
118
+ except Exception as e:
119
+ raise ValueError(f"Failed to translate math expression '{expr_str}'. Error: {e}")
120
+ else:
121
+ return float(q_param)
122
+
123
+ # ==========================================
124
+ # 4. Recursive Instruction Processor
125
+ # ==========================================
126
+ def process_circuit(circuit_to_parse: QuantumCircuit, qubit_map: dict, clbit_map: dict = None):
127
+ """Recursively unroll instructions, custom gates, and buffered measurements."""
128
+ measure_buffer = {}
129
+
130
+ def flush_measurements():
131
+ if measure_buffer:
132
+ sorted_c_indices = sorted(measure_buffer.keys())
133
+ ordered_q_indices = [measure_buffer[c_idx] for c_idx in sorted_c_indices]
134
+ cqlib_qc.measure(ordered_q_indices)
135
+ measure_buffer.clear()
136
+
137
+ for instruction in circuit_to_parse.data:
138
+ op = instruction.operation
139
+ name = op.name.lower()
140
+
141
+ # --- Measurement Handling ---
142
+ if name == 'measure':
143
+ q_obj = instruction.qubits[0]
144
+ c_obj = instruction.clbits[0]
145
+ q_idx = qubit_map[q_obj]
146
+
147
+ if clbit_map is not None and c_obj in clbit_map:
148
+ c_idx = clbit_map[c_obj]
149
+ else:
150
+ c_idx = qiskit_qc.find_bit(c_obj).index
151
+
152
+ measure_buffer[c_idx] = q_idx
153
+ continue
154
+
155
+ # Non-Measurement Gate encountered: Flush pending measurements first
156
+ flush_measurements()
157
+
158
+ # Map inner virtual qubits to absolute physical indices using the current dictionary
159
+ q_indices = [qubit_map[q] for q in instruction.qubits]
160
+
161
+ if name == 'h': cqlib_qc.h(q_indices[0])
162
+ elif name == 'x': cqlib_qc.x(q_indices[0])
163
+ elif name == 'y': cqlib_qc.y(q_indices[0])
164
+ elif name == 'z': cqlib_qc.z(q_indices[0])
165
+ elif name == 's': cqlib_qc.s(q_indices[0])
166
+ elif name == 'sdg': cqlib_qc.sd(q_indices[0])
167
+ elif name == 't': cqlib_qc.t(q_indices[0])
168
+ elif name == 'tdg': cqlib_qc.td(q_indices[0])
169
+ elif name == 'sx': cqlib_qc.x2p(q_indices[0])
170
+ elif name == 'sxdg': cqlib_qc.x2m(q_indices[0])
171
+ elif name == 'id':
172
+ pass
173
+
174
+
175
+ elif name == 'delay':
176
+ raw_duration = op.duration
177
+
178
+ if op.unit:
179
+ unit = op.unit.lower()
180
+ parsed_duration = parse_param(raw_duration)
181
+
182
+ if unit == 'dt':
183
+ raise ValueError(
184
+ "Unsupported delay unit 'dt'. Unit 'dt' requires explicit backend sampling rate. "
185
+ "Please use 'ns', 'us', 'ms', or 's'."
186
+ )
187
+ elif unit == 'ps':
188
+ raise ValueError(
189
+ "Unsupported delay unit 'ps'. Unit 'ps' exceeds hardware timing resolution. "
190
+ "Please use 'ns', 'us', 'ms', or 's'."
191
+ )
192
+ elif unit == 'ns':
193
+ cqlib_duration = parsed_duration
194
+ elif unit == 'us':
195
+ cqlib_duration = parsed_duration * 1e3
196
+ elif unit == 'ms':
197
+ cqlib_duration = parsed_duration * 1e6
198
+ elif unit == 's':
199
+ cqlib_duration = parsed_duration * 1e9
200
+ else:
201
+ raise ValueError(f"Unknown delay unit: '{unit}'.")
202
+
203
+ else:
204
+ raise ValueError(
205
+ "Default unit of delay is 'dt', which requires explicit backend sampling rate. "
206
+ "Please explicitly input one of the following units: 'ns', 'us' (for mu s), 'ms', 's'."
207
+ )
208
+
209
+ for q_idx in q_indices:
210
+ cqlib_qc.i(q_idx, cqlib_duration)
211
+
212
+
213
+ elif name == 'rx': cqlib_qc.rx(q_indices[0], theta=parse_param(op.params[0]))
214
+ elif name == 'ry': cqlib_qc.ry(q_indices[0], theta=parse_param(op.params[0]))
215
+ elif name in ['rz', 'p']: cqlib_qc.rz(q_indices[0], theta=parse_param(op.params[0]))
216
+ elif name in ['u3', 'u']:
217
+ cqlib_qc.u(q_indices[0],
218
+ theta=parse_param(op.params[0]),
219
+ phi=parse_param(op.params[1]),
220
+ lam=parse_param(op.params[2]))
221
+
222
+ elif name == 'cx': cqlib_qc.cx(q_indices[0], q_indices[1])
223
+ elif name == 'cy': cqlib_qc.cy(q_indices[0], q_indices[1])
224
+ elif name == 'cz': cqlib_qc.cz(q_indices[0], q_indices[1])
225
+ elif name == 'ccx': cqlib_qc.ccx(q_indices[0], q_indices[1], q_indices[2])
226
+ elif name == 'swap': cqlib_qc.swap(q_indices[0], q_indices[1])
227
+
228
+ elif name == 'crx': cqlib_qc.crx(q_indices[0], q_indices[1], theta=parse_param(op.params[0]))
229
+ elif name == 'cry': cqlib_qc.cry(q_indices[0], q_indices[1], theta=parse_param(op.params[0]))
230
+ elif name == 'crz': cqlib_qc.crz(q_indices[0], q_indices[1], theta=parse_param(op.params[0]))
231
+
232
+ elif name == 'barrier':
233
+ cqlib_qc.barrier(*q_indices)
234
+
235
+ # Custom Gate Unwrapping
236
+ elif hasattr(op, 'definition') and op.definition is not None:
237
+ inner_qc = op.definition
238
+ # Propagate physical mappings down to the custom gate's internal virtual qubits
239
+ inner_qubit_map = {inner_q: q_indices[i] for i, inner_q in enumerate(inner_qc.qubits)}
240
+ process_circuit(inner_qc, inner_qubit_map, clbit_map)
241
+ else:
242
+ print(f"Warning: Gate '{name}' is unsupported and has no definition. Skipped.")
243
+
244
+ # Final flush for any trailing measurements
245
+ flush_measurements()
246
+
247
+ # ==========================================
248
+ # 5. Initiate Parsing
249
+ # ==========================================
250
+ top_level_clbit_map = {c: qiskit_qc.find_bit(c).index for c in qiskit_qc.clbits}
251
+
252
+ # Process using the dynamically routed top_level_qubit_map
253
+ process_circuit(qiskit_qc, top_level_qubit_map, top_level_clbit_map)
254
+
255
+ return cqlib_qc
256
+
257
+
258
+ def pennylane_to_cqlib(
259
+ tape: QuantumTape,
260
+ mapping: Union[dict, list] = None,
261
+ parameters: list = None,
262
+ decompose: bool = False
263
+ ) -> Circuit:
264
+ """
265
+ Convert a PennyLane QuantumTape into a cqlib Circuit.
266
+
267
+ Features:
268
+ - Virtual-to-Physical Qubit Mapping (Layout routing).
269
+ - Explicit parameter injection (zero-overhead) or Auto-extraction.
270
+ - Smart Hardware Basis Interceptor (decompose=True) routes topology-incompatible
271
+ gates (CNOT, CY) and basis-incompatible gates (H) to the hardware equivalents,
272
+ while preserving the whitelisted native set (X, Y, Z, S, T, SX, RZ, CZ, ID).
273
+ - Recursive unwrapping of PennyLane QML Templates and complex gates.
274
+ - Robust Mid-Circuit Measurement (MidMeasureMP) support.
275
+
276
+ Args:
277
+ tape (QuantumTape): The source PennyLane quantum tape.
278
+ mapping (dict or list, optional): Mapping from virtual wires to physical qubits.
279
+ parameters (list, optional): Explicit list of cqlib.Parameter instances.
280
+ decompose (bool): If True, strictly transpiles the circuit to the native hardware basis.
281
+ """
282
+
283
+ # ==========================================
284
+ # 1. Parameter Handling (Explicit vs Implicit)
285
+ # ==========================================
286
+ cqlib_params = []
287
+
288
+ if parameters is not None:
289
+ cqlib_params = parameters
290
+ else:
291
+ def collect_params(p_obj):
292
+ if isinstance(p_obj, CqlibParameter):
293
+ if p_obj not in cqlib_params:
294
+ cqlib_params.append(p_obj)
295
+ elif isinstance(p_obj, (list, tuple, np.ndarray)):
296
+ for item in np.array(p_obj).flatten():
297
+ collect_params(item)
298
+ elif hasattr(p_obj, 'numpy'):
299
+ try:
300
+ for item in np.array(p_obj.numpy()).flatten():
301
+ collect_params(item)
302
+ except Exception:
303
+ pass
304
+
305
+
306
+ for op in tape.operations:
307
+ if hasattr(op, 'parameters'):
308
+ for p in op.parameters:
309
+ collect_params(p)
310
+
311
+ # ==========================================
312
+ # 2. Virtual-to-Physical Wire Mapping
313
+ # ==========================================
314
+ original_wires = tape.wires.tolist()
315
+ top_level_qubit_map = {}
316
+ physical_qubits_list = []
317
+
318
+ for v_idx, wire in enumerate(original_wires):
319
+ if mapping is not None:
320
+ if isinstance(mapping, dict):
321
+ if wire in mapping:
322
+ p_idx = mapping[wire]
323
+ elif v_idx in mapping:
324
+ p_idx = mapping[v_idx]
325
+ else:
326
+ raise ValueError(f"Wire '{wire}' is missing from the mapping dictionary.")
327
+ elif isinstance(mapping, (list, tuple)):
328
+ if v_idx >= len(mapping):
329
+ raise ValueError(f"Wire index {v_idx} exceeds mapping list length.")
330
+ p_idx = mapping[v_idx]
331
+ else:
332
+ p_idx = wire if isinstance(wire, int) else v_idx
333
+
334
+ top_level_qubit_map[wire] = p_idx
335
+ if p_idx not in physical_qubits_list:
336
+ physical_qubits_list.append(p_idx)
337
+
338
+ cqlib_qc = Circuit(physical_qubits_list, parameters=cqlib_params)
339
+
340
+ def parse_param(p):
341
+ if isinstance(p, CqlibParameter):
342
+ return p
343
+ if hasattr(p, 'numpy'):
344
+ p = p.numpy()
345
+ try:
346
+ return float(p)
347
+ except (TypeError, ValueError):
348
+ return p
349
+
350
+ # ==========================================
351
+ # 3. Recursive Operation Processor & Decomposer
352
+ # ==========================================
353
+ measure_buffer = []
354
+
355
+ def flush_measurements():
356
+ if measure_buffer:
357
+ cqlib_qc.measure(measure_buffer)
358
+ measure_buffer.clear()
359
+
360
+ def process_operations(operations):
361
+ for op in operations:
362
+ name = op.name
363
+ wires = op.wires.tolist()
364
+
365
+
366
+ raw_params = getattr(op, 'parameters', [])
367
+ params = [parse_param(p) for p in raw_params]
368
+
369
+ # --- Measurement Handling ---
370
+ if name == 'MidMeasureMP':
371
+ q_indices = [top_level_qubit_map[w] for w in wires]
372
+ measure_buffer.extend(q_indices)
373
+ continue
374
+
375
+ flush_measurements()
376
+
377
+
378
+ if decompose:
379
+ if name == 'CNOT':
380
+ sub_ops = [
381
+ qml.Hadamard(wires=wires[1]),
382
+ qml.CZ(wires=[wires[0], wires[1]]),
383
+ qml.Hadamard(wires=wires[1])
384
+ ]
385
+ process_operations(sub_ops)
386
+ continue
387
+ elif name == 'CY':
388
+ sub_ops = [
389
+ qml.adjoint(qml.S(wires=wires[1])),
390
+ qml.CNOT(wires=[wires[0], wires[1]]),
391
+ qml.S(wires=wires[1])
392
+ ]
393
+ process_operations(sub_ops)
394
+ continue
395
+ elif name == 'Hadamard':
396
+ sub_ops = [
397
+ qml.RZ(np.pi/2, wires=wires[0]),
398
+ qml.SX(wires=wires[0]),
399
+ qml.RZ(np.pi/2, wires=wires[0])
400
+ ]
401
+ process_operations(sub_ops)
402
+ continue
403
+
404
+ hardware_basis = {
405
+ 'PauliX', 'PauliY', 'PauliZ', 'RX', 'RY','RZ', 'CZ', 'Identity', 'SX', 'Adjoint(SX)', 'Barrier', 'PhaseShift',
406
+ 'PauliZ', 'S', 'Adjoint(S)', 'T', 'Adjoint(T)'
407
+ }
408
+
409
+ if name not in hardware_basis and op.has_decomposition:
410
+ process_operations(op.decomposition())
411
+ continue
412
+
413
+ # ==========================================
414
+ # --- Standard Gates Mapping ---
415
+ # ==========================================
416
+ q_indices = [top_level_qubit_map[w] for w in wires]
417
+
418
+ if name == 'PauliZ': cqlib_qc.z(q_indices[0])
419
+ elif name == 'S': cqlib_qc.s(q_indices[0])
420
+ elif name == 'Adjoint(S)': cqlib_qc.sd(q_indices[0])
421
+ elif name == 'T': cqlib_qc.t(q_indices[0])
422
+ elif name == 'Adjoint(T)': cqlib_qc.td(q_indices[0])
423
+
424
+ elif name == 'Hadamard': cqlib_qc.h(q_indices[0])
425
+ elif name == 'PauliX': cqlib_qc.x(q_indices[0])
426
+ elif name == 'PauliY': cqlib_qc.y(q_indices[0])
427
+ elif name == 'SX': cqlib_qc.x2p(q_indices[0])
428
+ elif name == 'Adjoint(SX)': cqlib_qc.x2m(q_indices[0])
429
+ elif name == 'Identity': pass
430
+
431
+ elif name == 'RX': cqlib_qc.rx(q_indices[0], theta=params[0])
432
+ elif name == 'RY': cqlib_qc.ry(q_indices[0], theta=params[0])
433
+ elif name in ['RZ', 'PhaseShift']: cqlib_qc.rz(q_indices[0], theta=params[0])
434
+
435
+ elif name == 'CNOT': cqlib_qc.cx(q_indices[0], q_indices[1])
436
+ elif name == 'CY': cqlib_qc.cy(q_indices[0], q_indices[1])
437
+ elif name == 'CZ': cqlib_qc.cz(q_indices[0], q_indices[1])
438
+ elif name == 'Toffoli': cqlib_qc.ccx(q_indices[0], q_indices[1], q_indices[2])
439
+ elif name == 'SWAP': cqlib_qc.swap(q_indices[0], q_indices[1])
440
+
441
+ elif name == 'CRX': cqlib_qc.crx(q_indices[0], q_indices[1], theta=params[0])
442
+ elif name == 'CRY': cqlib_qc.cry(q_indices[0], q_indices[1], theta=params[0])
443
+ elif name == 'CRZ': cqlib_qc.crz(q_indices[0], q_indices[1], theta=params[0])
444
+
445
+ elif name == 'Barrier':
446
+ cqlib_qc.barrier(*q_indices)
447
+
448
+ elif op.has_decomposition:
449
+ process_operations(op.decomposition())
450
+ else:
451
+ print(f"Warning: Gate '{name}' is unsupported and has no decomposition. Skipped.")
452
+
453
+ # ==========================================
454
+ # 4. Initiate Parsing & Terminal Measurements
455
+ # ==========================================
456
+ process_operations(tape.operations)
457
+ flush_measurements()
458
+
459
+ final_measured_wires = []
460
+ for m in tape.measurements:
461
+ if m.wires:
462
+ final_measured_wires.extend([top_level_qubit_map[w] for w in m.wires.tolist()])
463
+ else:
464
+ final_measured_wires.extend([top_level_qubit_map[w] for w in original_wires])
465
+
466
+ unique_final_meas = []
467
+ for q in final_measured_wires:
468
+ if q not in unique_final_meas:
469
+ unique_final_meas.append(q)
470
+
471
+ if unique_final_meas:
472
+ cqlib_qc.measure(unique_final_meas)
473
+
474
+ return cqlib_qc
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cqlib-adapter
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: Cqlib adapter
5
5
  Author-email: China Telecom Quantum Group Quantum Computing Team <tianyan@chinatelecom.cn>
6
6
  License-Expression: Apache-2.0
@@ -24,4 +24,6 @@ cqlib_adapter/qiskit_ext/job.py
24
24
  cqlib_adapter/qiskit_ext/sampler.py
25
25
  cqlib_adapter/qiskit_ext/submit_job.py
26
26
  cqlib_adapter/qiskit_ext/tianyan_backend.py
27
- cqlib_adapter/qiskit_ext/tianyan_provider.py
27
+ cqlib_adapter/qiskit_ext/tianyan_provider.py
28
+ cqlib_adapter/utils/api_client.py
29
+ cqlib_adapter/utils/converter.py
@@ -36,9 +36,9 @@ keywords = [
36
36
  [project.entry-points."pennylane.plugins"]
37
37
  "cqlib.device" = "cqlib_adapter.pennylane_ext.device:CQLibDevice"
38
38
 
39
- [tool.setuptools]
40
- packages = ["cqlib_adapter", "cqlib_adapter.qiskit_ext", "cqlib_adapter.pennylane_ext"]
41
- include-package-data = true
39
+ [tool.setuptools.packages.find]
40
+ where = ["."]
41
+ include = ["cqlib_adapter*"]
42
42
 
43
43
  [tool.setuptools.package-data]
44
44
  "cqlib_adapter.pennylane_ext" = ["cqlib_config.toml"]
@@ -1 +0,0 @@
1
- 0.3.2
File without changes
File without changes
File without changes