cqlib-vqe 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.
cqlib_vqe/__init__.py ADDED
@@ -0,0 +1,97 @@
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
+ """Public API for cqlib-vqe."""
14
+ from __future__ import annotations
15
+
16
+ from .chemistry import (
17
+ ActiveSpaceConfig,
18
+ ActiveSpaceReport,
19
+ CanonicalBasisAudit,
20
+ MolecularDataEngine,
21
+ SingletExcitation,
22
+ canonical_parameter_count,
23
+ canonical_singlet_descriptors,
24
+ canonical_singlet_operator,
25
+ encoded_occupied_qubits,
26
+ estimate_frozen_core_orbitals,
27
+ map_fermion_operator,
28
+ normalize_mapper_type,
29
+ pack_closed_shell_ccsd,
30
+ select_active_space,
31
+ )
32
+ from .vqe import (
33
+ AdaptiveRound,
34
+ AdaptiveSelectedUCCSDResult,
35
+ AdaptiveSelectedUCCSDSolver,
36
+ AdaptiveSelectionConfig,
37
+ CandidateGradient,
38
+ CloudEnergyEstimator,
39
+ DirectStatevectorEstimator,
40
+ EnergyEstimator,
41
+ FastStatevectorEstimator,
42
+ NativeStatevectorEstimator,
43
+ ParallelEnergyEstimator,
44
+ TianyanCloudEnergyEstimator,
45
+ TianyanEnergyEstimator,
46
+ TianyanEnergyResult,
47
+ TianyanGroupResult,
48
+ TianyanMeasurementGroup,
49
+ TianyanMeasurementPlan,
50
+ TianyanSubmittedEvaluation,
51
+ TianyanTermResult,
52
+ UCCSDFactory,
53
+ UCCSD_Factory,
54
+ VQESolver,
55
+ )
56
+
57
+ __version__ = "0.1.0"
58
+
59
+ __all__ = [
60
+ "__version__",
61
+ "ActiveSpaceConfig",
62
+ "ActiveSpaceReport",
63
+ "CanonicalBasisAudit",
64
+ "MolecularDataEngine",
65
+ "SingletExcitation",
66
+ "canonical_parameter_count",
67
+ "canonical_singlet_descriptors",
68
+ "canonical_singlet_operator",
69
+ "encoded_occupied_qubits",
70
+ "estimate_frozen_core_orbitals",
71
+ "map_fermion_operator",
72
+ "normalize_mapper_type",
73
+ "pack_closed_shell_ccsd",
74
+ "select_active_space",
75
+ "AdaptiveRound",
76
+ "AdaptiveSelectedUCCSDResult",
77
+ "AdaptiveSelectedUCCSDSolver",
78
+ "AdaptiveSelectionConfig",
79
+ "CandidateGradient",
80
+ "CloudEnergyEstimator",
81
+ "DirectStatevectorEstimator",
82
+ "EnergyEstimator",
83
+ "FastStatevectorEstimator",
84
+ "NativeStatevectorEstimator",
85
+ "ParallelEnergyEstimator",
86
+ "TianyanCloudEnergyEstimator",
87
+ "TianyanEnergyEstimator",
88
+ "TianyanEnergyResult",
89
+ "TianyanGroupResult",
90
+ "TianyanMeasurementGroup",
91
+ "TianyanMeasurementPlan",
92
+ "TianyanSubmittedEvaluation",
93
+ "TianyanTermResult",
94
+ "UCCSDFactory",
95
+ "UCCSD_Factory",
96
+ "VQESolver",
97
+ ]
@@ -0,0 +1,47 @@
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
+ """Molecular electronic-structure and active-space helpers."""
14
+
15
+ from .active_space import (
16
+ ActiveSpaceConfig,
17
+ ActiveSpaceReport,
18
+ estimate_frozen_core_orbitals,
19
+ select_active_space,
20
+ )
21
+ from .molecule import MolecularDataEngine
22
+ from .mapping import encoded_occupied_qubits, map_fermion_operator, normalize_mapper_type
23
+ from .uccsd import (
24
+ CanonicalBasisAudit,
25
+ SingletExcitation,
26
+ canonical_parameter_count,
27
+ canonical_singlet_descriptors,
28
+ canonical_singlet_operator,
29
+ )
30
+ from .uccsd_amplitudes import pack_closed_shell_ccsd
31
+
32
+ __all__ = [
33
+ "ActiveSpaceConfig",
34
+ "ActiveSpaceReport",
35
+ "CanonicalBasisAudit",
36
+ "MolecularDataEngine",
37
+ "encoded_occupied_qubits",
38
+ "map_fermion_operator",
39
+ "normalize_mapper_type",
40
+ "SingletExcitation",
41
+ "canonical_parameter_count",
42
+ "canonical_singlet_descriptors",
43
+ "canonical_singlet_operator",
44
+ "estimate_frozen_core_orbitals",
45
+ "pack_closed_shell_ccsd",
46
+ "select_active_space",
47
+ ]
@@ -0,0 +1,398 @@
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
+ """Deterministic full, manual, and automatic molecular active spaces.
14
+
15
+ The active-space Hamiltonian itself is built by OpenFermion's
16
+ ``MolecularData.get_molecular_hamiltonian``. That routine folds frozen occupied
17
+ orbitals into the scalar and one-electron parts of the reduced Hamiltonian.
18
+ This module only selects and reports the orbital partition; it does not pretend
19
+ to perform CASSCF orbital optimization.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from dataclasses import asdict, dataclass, field
25
+ from typing import Iterable, Literal, Sequence
26
+
27
+ import numpy as np
28
+
29
+
30
+ _ATOMIC_NUMBERS = {
31
+ "H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7,
32
+ "O": 8, "F": 9, "Ne": 10, "Na": 11, "Mg": 12, "Al": 13,
33
+ "Si": 14, "P": 15, "S": 16, "Cl": 17, "Ar": 18, "K": 19,
34
+ "Ca": 20, "Sc": 21, "Ti": 22, "V": 23, "Cr": 24, "Mn": 25,
35
+ "Fe": 26, "Co": 27, "Ni": 28, "Cu": 29, "Zn": 30, "Ga": 31,
36
+ "Ge": 32, "As": 33, "Se": 34, "Br": 35, "Kr": 36, "Rb": 37,
37
+ "Sr": 38, "Y": 39, "Zr": 40, "Nb": 41, "Mo": 42, "Tc": 43,
38
+ "Ru": 44, "Rh": 45, "Pd": 46, "Ag": 47, "Cd": 48, "In": 49,
39
+ "Sn": 50, "Sb": 51, "Te": 52, "I": 53, "Xe": 54,
40
+ }
41
+
42
+
43
+ def _previous_noble_gas_electrons(atomic_number: int) -> int:
44
+ if atomic_number <= 2:
45
+ return 0
46
+ if atomic_number <= 10:
47
+ return 2
48
+ if atomic_number <= 18:
49
+ return 10
50
+ if atomic_number <= 36:
51
+ return 18
52
+ if atomic_number <= 54:
53
+ return 36
54
+ if atomic_number <= 86:
55
+ return 54
56
+ return 86
57
+
58
+
59
+ def estimate_frozen_core_orbitals(symbols: Iterable[str]) -> int:
60
+ """Estimate the conventional frozen-core spatial-orbital count."""
61
+
62
+ frozen_electrons = 0
63
+ for raw_symbol in symbols:
64
+ symbol = str(raw_symbol).strip()
65
+ if symbol not in _ATOMIC_NUMBERS:
66
+ raise ValueError(
67
+ f"Unknown element {symbol!r} for automatic frozen-core selection; "
68
+ "use a manual active space."
69
+ )
70
+ frozen_electrons += _previous_noble_gas_electrons(_ATOMIC_NUMBERS[symbol])
71
+ return frozen_electrons // 2
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class ActiveSpaceConfig:
76
+ """Configuration for full, manual, or deterministic automatic selection."""
77
+
78
+ mode: Literal["full", "auto", "manual"] = "full"
79
+ freeze_core: bool = True
80
+ max_active_qubits: int | None = None
81
+ max_active_orbitals: int | None = None
82
+ active_electrons: int | None = None
83
+ active_orbitals: int | None = None
84
+ min_virtual_orbitals: int = 1
85
+ virtual_energy_window: float | None = None
86
+ allow_additional_frozen_occupied: bool = True
87
+
88
+ @classmethod
89
+ def full(cls) -> "ActiveSpaceConfig":
90
+ return cls(mode="full", freeze_core=False)
91
+
92
+ @classmethod
93
+ def automatic(
94
+ cls,
95
+ *,
96
+ max_active_qubits: int | None = None,
97
+ max_active_orbitals: int | None = None,
98
+ active_electrons: int | None = None,
99
+ active_orbitals: int | None = None,
100
+ freeze_core: bool = True,
101
+ min_virtual_orbitals: int = 1,
102
+ virtual_energy_window: float | None = None,
103
+ allow_additional_frozen_occupied: bool = True,
104
+ ) -> "ActiveSpaceConfig":
105
+ return cls(
106
+ mode="auto",
107
+ freeze_core=freeze_core,
108
+ max_active_qubits=max_active_qubits,
109
+ max_active_orbitals=max_active_orbitals,
110
+ active_electrons=active_electrons,
111
+ active_orbitals=active_orbitals,
112
+ min_virtual_orbitals=min_virtual_orbitals,
113
+ virtual_energy_window=virtual_energy_window,
114
+ allow_additional_frozen_occupied=allow_additional_frozen_occupied,
115
+ )
116
+
117
+ @classmethod
118
+ def manual(cls) -> "ActiveSpaceConfig":
119
+ return cls(mode="manual")
120
+
121
+ def validate(self) -> None:
122
+ if self.mode not in {"full", "auto", "manual"}:
123
+ raise ValueError(f"Unknown active-space mode {self.mode!r}")
124
+ if self.max_active_qubits is not None and (
125
+ self.max_active_qubits <= 0 or self.max_active_qubits % 2
126
+ ):
127
+ raise ValueError("max_active_qubits must be a positive even integer")
128
+ for name, value in (
129
+ ("max_active_orbitals", self.max_active_orbitals),
130
+ ("active_orbitals", self.active_orbitals),
131
+ ):
132
+ if value is not None and value < 0:
133
+ raise ValueError(f"{name} must be non-negative")
134
+ if self.min_virtual_orbitals < 1:
135
+ raise ValueError("min_virtual_orbitals must be at least 1")
136
+ if self.active_electrons is not None and (
137
+ self.active_electrons <= 0 or self.active_electrons % 2
138
+ ):
139
+ raise ValueError("active_electrons must be a positive even integer")
140
+ if self.virtual_energy_window is not None and self.virtual_energy_window <= 0:
141
+ raise ValueError("virtual_energy_window must be positive")
142
+ budget_count = sum(
143
+ value is not None
144
+ for value in (
145
+ self.max_active_qubits,
146
+ self.max_active_orbitals,
147
+ self.active_orbitals,
148
+ )
149
+ )
150
+ if budget_count > 1:
151
+ raise ValueError(
152
+ "Specify only one of max_active_qubits, max_active_orbitals, "
153
+ "or active_orbitals"
154
+ )
155
+
156
+ def to_dict(self) -> dict[str, object]:
157
+ return asdict(self)
158
+
159
+
160
+ @dataclass(frozen=True)
161
+ class ActiveSpaceReport:
162
+ mode: str
163
+ original_spatial_orbitals: int
164
+ original_electrons: int
165
+ occupied_spatial_orbitals: int
166
+ frozen_occupied_indices: tuple[int, ...]
167
+ active_indices: tuple[int, ...]
168
+ excluded_virtual_indices: tuple[int, ...]
169
+ active_electrons: int
170
+ active_spatial_orbitals: int
171
+ pre_taper_qubits: int
172
+ estimated_core_orbitals: int
173
+ additional_frozen_occupied: int
174
+ selection_reason: str
175
+ orbital_energies: tuple[float, ...] = field(default_factory=tuple)
176
+ warnings: tuple[str, ...] = field(default_factory=tuple)
177
+
178
+ def to_dict(self) -> dict[str, object]:
179
+ return asdict(self)
180
+
181
+
182
+ def _manual_report(
183
+ occupied_indices: Sequence[int] | None,
184
+ active_indices: Sequence[int] | None,
185
+ *,
186
+ n_orbitals: int,
187
+ n_electrons: int,
188
+ orbital_energies: np.ndarray,
189
+ ) -> ActiveSpaceReport:
190
+ frozen = tuple(sorted(int(index) for index in (occupied_indices or ())))
191
+ active = tuple(sorted(int(index) for index in (active_indices or ())))
192
+ if len(set(frozen)) != len(frozen) or len(set(active)) != len(active):
193
+ raise ValueError("Manual active-space indices must be unique")
194
+ if set(frozen) & set(active):
195
+ raise ValueError("occupied_indices and active_indices must be disjoint")
196
+ if any(index < 0 or index >= n_orbitals for index in (*frozen, *active)):
197
+ raise ValueError("Manual active-space index is outside the orbital range")
198
+ n_occ = n_electrons // 2
199
+ if any(index >= n_occ for index in frozen):
200
+ raise ValueError("occupied_indices may contain only occupied spatial orbitals")
201
+ if not active:
202
+ active = tuple(index for index in range(n_orbitals) if index not in frozen)
203
+ missing_occupied = sorted(set(range(n_occ)) - set(frozen) - set(active))
204
+ if missing_occupied:
205
+ raise ValueError(
206
+ "Every occupied orbital must be either frozen or active; missing "
207
+ f"occupied indices {missing_occupied}"
208
+ )
209
+ active_electrons = n_electrons - 2 * len(frozen)
210
+ if active_electrons <= 0 or active_electrons > 2 * len(active):
211
+ raise ValueError(
212
+ f"Inconsistent manual active space: {active_electrons} electrons in "
213
+ f"{len(active)} spatial orbitals"
214
+ )
215
+ excluded_virtual = tuple(
216
+ index for index in range(n_occ, n_orbitals) if index not in active
217
+ )
218
+ warnings: tuple[str, ...] = ()
219
+ if active and active != tuple(range(active[0], active[-1] + 1)):
220
+ warnings = ("Manual active orbital indices are non-contiguous.",)
221
+ return ActiveSpaceReport(
222
+ mode="manual",
223
+ original_spatial_orbitals=n_orbitals,
224
+ original_electrons=n_electrons,
225
+ occupied_spatial_orbitals=n_occ,
226
+ frozen_occupied_indices=frozen,
227
+ active_indices=active,
228
+ excluded_virtual_indices=excluded_virtual,
229
+ active_electrons=active_electrons,
230
+ active_spatial_orbitals=len(active),
231
+ pre_taper_qubits=2 * len(active),
232
+ estimated_core_orbitals=len(frozen),
233
+ additional_frozen_occupied=0,
234
+ selection_reason="User-provided manual active space.",
235
+ orbital_energies=tuple(float(value) for value in orbital_energies),
236
+ warnings=warnings,
237
+ )
238
+
239
+
240
+ def select_active_space(
241
+ *,
242
+ config: ActiveSpaceConfig,
243
+ geometry: Sequence[tuple[str, Sequence[float]]],
244
+ n_orbitals: int,
245
+ n_electrons: int,
246
+ orbital_energies: Sequence[float],
247
+ occupied_indices: Sequence[int] | None = None,
248
+ active_indices: Sequence[int] | None = None,
249
+ ) -> ActiveSpaceReport:
250
+ """Select a deterministic active space and return a complete report."""
251
+
252
+ config.validate()
253
+ energies = np.asarray(orbital_energies, dtype=float).reshape(-1)
254
+ if energies.size != n_orbitals:
255
+ raise ValueError(
256
+ f"Expected {n_orbitals} orbital energies, received {energies.size}"
257
+ )
258
+ if n_electrons <= 0 or n_electrons % 2:
259
+ raise ValueError(
260
+ "This active-space implementation currently requires a positive, "
261
+ "even closed-shell electron count"
262
+ )
263
+ n_occ = n_electrons // 2
264
+ if n_occ > n_orbitals:
265
+ raise ValueError("Electron count exceeds available orbitals")
266
+
267
+ if config.mode == "manual" or occupied_indices is not None or active_indices is not None:
268
+ return _manual_report(
269
+ occupied_indices,
270
+ active_indices,
271
+ n_orbitals=n_orbitals,
272
+ n_electrons=n_electrons,
273
+ orbital_energies=energies,
274
+ )
275
+
276
+ if config.mode == "full":
277
+ active = tuple(range(n_orbitals))
278
+ return ActiveSpaceReport(
279
+ mode="full",
280
+ original_spatial_orbitals=n_orbitals,
281
+ original_electrons=n_electrons,
282
+ occupied_spatial_orbitals=n_occ,
283
+ frozen_occupied_indices=(),
284
+ active_indices=active,
285
+ excluded_virtual_indices=(),
286
+ active_electrons=n_electrons,
287
+ active_spatial_orbitals=n_orbitals,
288
+ pre_taper_qubits=2 * n_orbitals,
289
+ estimated_core_orbitals=0,
290
+ additional_frozen_occupied=0,
291
+ selection_reason="Full molecular orbital space retained.",
292
+ orbital_energies=tuple(float(value) for value in energies),
293
+ )
294
+
295
+ symbols = [atom for atom, _ in geometry]
296
+ estimated_core = estimate_frozen_core_orbitals(symbols) if config.freeze_core else 0
297
+ estimated_core = min(estimated_core, max(0, n_occ - 1))
298
+
299
+ if config.active_electrons is not None:
300
+ if config.active_electrons > n_electrons:
301
+ raise ValueError("active_electrons cannot exceed molecular electrons")
302
+ requested_frozen = (n_electrons - config.active_electrons) // 2
303
+ frozen_count = max(estimated_core, requested_frozen)
304
+ else:
305
+ frozen_count = estimated_core
306
+
307
+ if config.active_orbitals is not None:
308
+ capacity = config.active_orbitals
309
+ elif config.max_active_orbitals is not None:
310
+ capacity = config.max_active_orbitals
311
+ elif config.max_active_qubits is not None:
312
+ capacity = config.max_active_qubits // 2
313
+ else:
314
+ capacity = n_orbitals - frozen_count
315
+ capacity = min(int(capacity), n_orbitals)
316
+ if capacity <= 0:
317
+ raise ValueError("Active-space orbital budget must be positive")
318
+
319
+ min_virtual = int(config.min_virtual_orbitals)
320
+ active_occupied_count = n_occ - frozen_count
321
+ additional_frozen = 0
322
+ warnings: list[str] = []
323
+ if active_occupied_count + min_virtual > capacity:
324
+ if not config.allow_additional_frozen_occupied:
325
+ raise ValueError(
326
+ "Active-space budget cannot retain the non-core occupied orbitals "
327
+ f"and {min_virtual} virtual orbital(s)"
328
+ )
329
+ additional_frozen = active_occupied_count + min_virtual - capacity
330
+ frozen_count += additional_frozen
331
+ active_occupied_count = n_occ - frozen_count
332
+ warnings.append(
333
+ "The qubit budget froze occupied orbitals beyond the conventional core."
334
+ )
335
+ if active_occupied_count <= 0:
336
+ raise ValueError("Automatic selection removed all occupied active orbitals")
337
+
338
+ occupied_by_energy = sorted(
339
+ range(n_occ), key=lambda index: (float(energies[index]), index)
340
+ )
341
+ frozen_set = set(occupied_by_energy[:frozen_count])
342
+ active_occupied = sorted(index for index in range(n_occ) if index not in frozen_set)
343
+
344
+ virtual_candidates = sorted(
345
+ range(n_occ, n_orbitals), key=lambda index: (float(energies[index]), index)
346
+ )
347
+ if config.virtual_energy_window is not None and virtual_candidates:
348
+ lumo = float(energies[virtual_candidates[0]])
349
+ limit = lumo + float(config.virtual_energy_window)
350
+ within_window = [
351
+ index for index in virtual_candidates if float(energies[index]) <= limit
352
+ ]
353
+ virtual_candidates = (
354
+ within_window
355
+ if len(within_window) >= min_virtual
356
+ else virtual_candidates[:min_virtual]
357
+ )
358
+
359
+ virtual_capacity = capacity - len(active_occupied)
360
+ selected_virtual = sorted(virtual_candidates[:virtual_capacity])
361
+ if len(selected_virtual) < min_virtual:
362
+ raise ValueError(
363
+ f"Only {len(selected_virtual)} virtual orbital(s) fit; {min_virtual} required"
364
+ )
365
+
366
+ frozen = tuple(sorted(frozen_set))
367
+ active = tuple(active_occupied + selected_virtual)
368
+ excluded_virtual = tuple(
369
+ index for index in range(n_occ, n_orbitals) if index not in selected_virtual
370
+ )
371
+ return ActiveSpaceReport(
372
+ mode="auto",
373
+ original_spatial_orbitals=n_orbitals,
374
+ original_electrons=n_electrons,
375
+ occupied_spatial_orbitals=n_occ,
376
+ frozen_occupied_indices=frozen,
377
+ active_indices=active,
378
+ excluded_virtual_indices=excluded_virtual,
379
+ active_electrons=n_electrons - 2 * frozen_count,
380
+ active_spatial_orbitals=len(active),
381
+ pre_taper_qubits=2 * len(active),
382
+ estimated_core_orbitals=estimated_core,
383
+ additional_frozen_occupied=additional_frozen,
384
+ selection_reason=(
385
+ "Frozen-core and orbital-energy selection: highest occupied and lowest "
386
+ "virtual orbitals retained within the configured budget."
387
+ ),
388
+ orbital_energies=tuple(float(value) for value in energies),
389
+ warnings=tuple(warnings),
390
+ )
391
+
392
+
393
+ __all__ = [
394
+ "ActiveSpaceConfig",
395
+ "ActiveSpaceReport",
396
+ "estimate_frozen_core_orbitals",
397
+ "select_active_space",
398
+ ]