qsl-quantum 0.2.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.
- qsl/__init__.py +244 -0
- qsl/__main__.py +134 -0
- qsl/ai/__init__.py +34 -0
- qsl/ai/agent.py +275 -0
- qsl/ai/discovery.py +118 -0
- qsl/ai/explainer.py +132 -0
- qsl/ai/hypotheses.py +173 -0
- qsl/ai/translator.py +145 -0
- qsl/algorithms/__init__.py +49 -0
- qsl/algorithms/qaoa.py +302 -0
- qsl/algorithms/qft.py +86 -0
- qsl/algorithms/shor.py +295 -0
- qsl/algorithms/vqe.py +507 -0
- qsl/backends/__init__.py +24 -0
- qsl/backends/auto_selector.py +116 -0
- qsl/backends/aws_braket.py +216 -0
- qsl/backends/base.py +105 -0
- qsl/backends/ibm.py +574 -0
- qsl/backends/registry.py +93 -0
- qsl/backends/simulator.py +138 -0
- qsl/compiler/__init__.py +27 -0
- qsl/compiler/compiler.py +289 -0
- qsl/compiler/dsl.py +231 -0
- qsl/compiler/error_mitigation.py +175 -0
- qsl/compiler/optimizer.py +150 -0
- qsl/compiler/program.py +143 -0
- qsl/compiler/transpiler.py +241 -0
- qsl/core/__init__.py +16 -0
- qsl/core/grover.py +462 -0
- qsl/core/parser.py +345 -0
- qsl/core/state.py +766 -0
- qsl/meta/__init__.py +18 -0
- qsl/meta/algorithm_search.py +309 -0
- qsl/meta/quantum_compiler_ai.py +353 -0
- qsl/meta/theory_generator.py +221 -0
- qsl/network/__init__.py +20 -0
- qsl/network/distributed_node.py +204 -0
- qsl/network/quantum_blockchain.py +241 -0
- qsl/pipelines/__init__.py +18 -0
- qsl/pipelines/crypto_analysis.py +150 -0
- qsl/pipelines/drug_discovery.py +161 -0
- qsl/pipelines/portfolio.py +205 -0
- qsl/qml/__init__.py +15 -0
- qsl/qml/kernels.py +110 -0
- qsl/qml/layers.py +247 -0
- qsl/qml/qgan.py +204 -0
- qsl/qml/qnn.py +160 -0
- qsl/qml/qsvm.py +170 -0
- qsl/quantum_gates.py +326 -0
- qsl/utils/__init__.py +1 -0
- qsl/utils/exceptions.py +180 -0
- qsl/utils/validation.py +178 -0
- qsl_quantum-0.2.0.dist-info/METADATA +229 -0
- qsl_quantum-0.2.0.dist-info/RECORD +60 -0
- qsl_quantum-0.2.0.dist-info/WHEEL +5 -0
- qsl_quantum-0.2.0.dist-info/entry_points.txt +2 -0
- qsl_quantum-0.2.0.dist-info/licenses/LICENSE +21 -0
- qsl_quantum-0.2.0.dist-info/top_level.txt +2 -0
- /321/206/342/225/241/320/233/321/210/320/277/320/245_/321/206/320/254/320/274/321/205/320/254/342/226/221_/321/204/342/225/225/320/235/321/204/342/225/225/320/232/321/204/342/225/235/320/260/demo_interactive.py +236 -0
- /321/206/342/225/241/320/233/321/210/320/277/320/245_/321/206/320/254/320/274/321/205/320/254/342/226/221_/321/204/342/225/225/320/235/321/204/342/225/225/320/232/321/204/342/225/235/320/260/quantum_password_recovery.py +386 -0
qsl/__init__.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""
|
|
2
|
+
QSL - Quantum Search Language
|
|
3
|
+
=============================
|
|
4
|
+
|
|
5
|
+
Quantum computing framework supporting:
|
|
6
|
+
- Declarative quantum search (Grover)
|
|
7
|
+
- Quantum algorithms (QFT, Shor, QAOA, VQE)
|
|
8
|
+
- Quantum machine learning (QNN, QSVM, QGAN)
|
|
9
|
+
- Hardware backends (IBM, AWS Braket, Simulator)
|
|
10
|
+
- Circuit compiler optimization (gate fusion, transpiler, error mitigation)
|
|
11
|
+
- AI-powered quantum scientist (LLM translator, autonomous agent)
|
|
12
|
+
- Self-evolving quantum AI (genetic circuit search, RL compiler)
|
|
13
|
+
- Distributed quantum computing & quantum blockchain
|
|
14
|
+
- Application pipelines (drug discovery, crypto analysis, portfolio)
|
|
15
|
+
|
|
16
|
+
Modes:
|
|
17
|
+
1. Classical simulator (default) - numpy-based, zero external deps
|
|
18
|
+
2. IBM quantum computer - requires qiskit
|
|
19
|
+
3. AWS Braket - requires boto3
|
|
20
|
+
|
|
21
|
+
Quick start:
|
|
22
|
+
>>> from qsl import QSLProgram, QSLCompiler
|
|
23
|
+
>>> program = QSLProgram(name="test", n_qubits=3, premises=["x0 & x1"])
|
|
24
|
+
>>> compiler = QSLCompiler()
|
|
25
|
+
>>> result = compiler.compile_and_run(program)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
__version__ = "0.2.0"
|
|
29
|
+
__author__ = "Song Ziming"
|
|
30
|
+
__email__ = "15011462616@163.com"
|
|
31
|
+
|
|
32
|
+
# ----------------------------------------------------------------
|
|
33
|
+
# Core API (always available, zero deps)
|
|
34
|
+
# ----------------------------------------------------------------
|
|
35
|
+
from .compiler.program import QSLProgram
|
|
36
|
+
from .compiler.compiler import QSLCompiler, compile_and_run, analyze
|
|
37
|
+
from .compiler.dsl import parse_qsl
|
|
38
|
+
from .core.parser import parse_bool
|
|
39
|
+
from .core.state import QuantumState
|
|
40
|
+
from .core.grover import GroverSearch, GroverResult, solve_sat
|
|
41
|
+
from .backends.registry import list_backends, get_backend
|
|
42
|
+
from .backends.simulator import SimulatorBackend
|
|
43
|
+
|
|
44
|
+
# ----------------------------------------------------------------
|
|
45
|
+
# Quantum Gates (requires numpy)
|
|
46
|
+
# ----------------------------------------------------------------
|
|
47
|
+
try:
|
|
48
|
+
from .quantum_gates import (
|
|
49
|
+
I, X, Y, Z, H, S, T,
|
|
50
|
+
rx, ry, rz, u3,
|
|
51
|
+
swap, cswap, mcx,
|
|
52
|
+
kron, controlled_gate,
|
|
53
|
+
)
|
|
54
|
+
_has_gates = True
|
|
55
|
+
except ImportError:
|
|
56
|
+
_has_gates = False
|
|
57
|
+
|
|
58
|
+
# ----------------------------------------------------------------
|
|
59
|
+
# Quantum Algorithms (requires numpy, scipy optional)
|
|
60
|
+
# ----------------------------------------------------------------
|
|
61
|
+
try:
|
|
62
|
+
from .algorithms import (
|
|
63
|
+
QuantumFourierTransform,
|
|
64
|
+
ShorSolver,
|
|
65
|
+
QAOA,
|
|
66
|
+
VQE,
|
|
67
|
+
)
|
|
68
|
+
_has_algorithms = True
|
|
69
|
+
except ImportError:
|
|
70
|
+
_has_algorithms = False
|
|
71
|
+
|
|
72
|
+
# ----------------------------------------------------------------
|
|
73
|
+
# Quantum Machine Learning (requires torch, scipy, sklearn)
|
|
74
|
+
# ----------------------------------------------------------------
|
|
75
|
+
try:
|
|
76
|
+
from .qml import QuantumLayer, QNN, quantum_kernel, QuantumSVM, QGAN
|
|
77
|
+
_has_qml = True
|
|
78
|
+
except ImportError:
|
|
79
|
+
_has_qml = False
|
|
80
|
+
|
|
81
|
+
# ----------------------------------------------------------------
|
|
82
|
+
# Advanced Backends (requires qiskit, boto3)
|
|
83
|
+
# ----------------------------------------------------------------
|
|
84
|
+
try:
|
|
85
|
+
from .backends.ibm import IBMBackend
|
|
86
|
+
_has_ibm = True
|
|
87
|
+
except ImportError:
|
|
88
|
+
_has_ibm = False
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
from .backends.aws_braket import AWSBraketBackend
|
|
92
|
+
_has_aws = True
|
|
93
|
+
except ImportError:
|
|
94
|
+
_has_aws = False
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
from .backends.auto_selector import AutoBackend
|
|
98
|
+
_has_auto_backend = True
|
|
99
|
+
except ImportError:
|
|
100
|
+
_has_auto_backend = False
|
|
101
|
+
|
|
102
|
+
# ----------------------------------------------------------------
|
|
103
|
+
# Compiler Optimizations (requires numpy)
|
|
104
|
+
# ----------------------------------------------------------------
|
|
105
|
+
try:
|
|
106
|
+
from .compiler.optimizer import gate_fusion, commutation_optimization, depth_reduction
|
|
107
|
+
from .compiler.transpiler import layout_mapping, swap_insertion, get_coupling_graph
|
|
108
|
+
_has_compiler_opt = True
|
|
109
|
+
except ImportError:
|
|
110
|
+
_has_compiler_opt = False
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
from .compiler.error_mitigation import (
|
|
114
|
+
zne,
|
|
115
|
+
readout_error_correction,
|
|
116
|
+
build_confusion_matrix,
|
|
117
|
+
richardson_extrapolate,
|
|
118
|
+
)
|
|
119
|
+
_has_error_mitigation = True
|
|
120
|
+
except ImportError:
|
|
121
|
+
_has_error_mitigation = False
|
|
122
|
+
|
|
123
|
+
# ----------------------------------------------------------------
|
|
124
|
+
# AI Scientist (requires openai, langchain)
|
|
125
|
+
# ----------------------------------------------------------------
|
|
126
|
+
try:
|
|
127
|
+
from .ai import (
|
|
128
|
+
ProblemTranslator,
|
|
129
|
+
QuantumAgent,
|
|
130
|
+
HypothesisTester,
|
|
131
|
+
DiscoveryPipeline,
|
|
132
|
+
ResultExplainer,
|
|
133
|
+
)
|
|
134
|
+
_has_ai = True
|
|
135
|
+
except ImportError:
|
|
136
|
+
_has_ai = False
|
|
137
|
+
|
|
138
|
+
# ----------------------------------------------------------------
|
|
139
|
+
# Application Pipelines (requires core + algorithms)
|
|
140
|
+
# ----------------------------------------------------------------
|
|
141
|
+
try:
|
|
142
|
+
from .pipelines import (
|
|
143
|
+
DrugDiscoveryPipeline,
|
|
144
|
+
CryptoAnalysisPipeline,
|
|
145
|
+
PortfolioOptimizer,
|
|
146
|
+
)
|
|
147
|
+
_has_pipelines = True
|
|
148
|
+
except ImportError:
|
|
149
|
+
_has_pipelines = False
|
|
150
|
+
|
|
151
|
+
# ----------------------------------------------------------------
|
|
152
|
+
# Meta / Self-Evolving System
|
|
153
|
+
# ----------------------------------------------------------------
|
|
154
|
+
try:
|
|
155
|
+
from .meta import AlgorithmSearcher, QuantumCompilerAI, QuantumTheoremProver
|
|
156
|
+
_has_meta = True
|
|
157
|
+
except ImportError:
|
|
158
|
+
_has_meta = False
|
|
159
|
+
|
|
160
|
+
# ----------------------------------------------------------------
|
|
161
|
+
# Quantum Network
|
|
162
|
+
# ----------------------------------------------------------------
|
|
163
|
+
try:
|
|
164
|
+
from .network import (
|
|
165
|
+
DistributedNode,
|
|
166
|
+
QuantumCluster,
|
|
167
|
+
QuantumBlockchain,
|
|
168
|
+
QuantumBlock,
|
|
169
|
+
)
|
|
170
|
+
_has_network = True
|
|
171
|
+
except ImportError:
|
|
172
|
+
_has_network = False
|
|
173
|
+
|
|
174
|
+
# ----------------------------------------------------------------
|
|
175
|
+
# Export list
|
|
176
|
+
# ----------------------------------------------------------------
|
|
177
|
+
__all__ = [
|
|
178
|
+
# Core
|
|
179
|
+
"QSLProgram",
|
|
180
|
+
"QSLCompiler",
|
|
181
|
+
"compile_and_run",
|
|
182
|
+
"analyze",
|
|
183
|
+
"parse_qsl",
|
|
184
|
+
"parse_bool",
|
|
185
|
+
"QuantumState",
|
|
186
|
+
"GroverSearch",
|
|
187
|
+
"GroverResult",
|
|
188
|
+
"solve_sat",
|
|
189
|
+
"SimulatorBackend",
|
|
190
|
+
"list_backends",
|
|
191
|
+
"get_backend",
|
|
192
|
+
# Gates
|
|
193
|
+
"I", "X", "Y", "Z", "H", "S", "T",
|
|
194
|
+
"rx", "ry", "rz", "u3",
|
|
195
|
+
"swap", "cswap", "mcx",
|
|
196
|
+
"kron", "controlled_gate",
|
|
197
|
+
# Algorithms
|
|
198
|
+
"QuantumFourierTransform",
|
|
199
|
+
"ShorSolver",
|
|
200
|
+
"QAOA",
|
|
201
|
+
"VQE",
|
|
202
|
+
# QML
|
|
203
|
+
"QuantumLayer",
|
|
204
|
+
"QNN",
|
|
205
|
+
"quantum_kernel",
|
|
206
|
+
"QuantumSVM",
|
|
207
|
+
"QGAN",
|
|
208
|
+
# Backends
|
|
209
|
+
"IBMBackend",
|
|
210
|
+
"AWSBraketBackend",
|
|
211
|
+
"AutoBackend",
|
|
212
|
+
# Compiler
|
|
213
|
+
"gate_fusion",
|
|
214
|
+
"commutation_optimization",
|
|
215
|
+
"depth_reduction",
|
|
216
|
+
"layout_mapping",
|
|
217
|
+
"swap_insertion",
|
|
218
|
+
"get_coupling_graph",
|
|
219
|
+
"zne",
|
|
220
|
+
"readout_error_correction",
|
|
221
|
+
"build_confusion_matrix",
|
|
222
|
+
"richardson_extrapolate",
|
|
223
|
+
# AI
|
|
224
|
+
"ProblemTranslator",
|
|
225
|
+
"QuantumAgent",
|
|
226
|
+
"HypothesisTester",
|
|
227
|
+
"DiscoveryPipeline",
|
|
228
|
+
"ResultExplainer",
|
|
229
|
+
# Pipelines
|
|
230
|
+
"DrugDiscoveryPipeline",
|
|
231
|
+
"CryptoAnalysisPipeline",
|
|
232
|
+
"PortfolioOptimizer",
|
|
233
|
+
# Meta
|
|
234
|
+
"AlgorithmSearcher",
|
|
235
|
+
"QuantumCompilerAI",
|
|
236
|
+
"QuantumTheoremProver",
|
|
237
|
+
# Network
|
|
238
|
+
"DistributedNode",
|
|
239
|
+
"QuantumCluster",
|
|
240
|
+
"QuantumBlockchain",
|
|
241
|
+
"QuantumBlock",
|
|
242
|
+
# Version
|
|
243
|
+
"__version__",
|
|
244
|
+
]
|
qsl/__main__.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
QSL 命令行入口。
|
|
3
|
+
|
|
4
|
+
使用:
|
|
5
|
+
python -m qsl # 交互式选择示例
|
|
6
|
+
python -m qsl --demo 1 # 运行指定示例
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
"""命令行主入口。"""
|
|
14
|
+
from qsl import QSLProgram, QSLCompiler, parse_qsl
|
|
15
|
+
|
|
16
|
+
if len(sys.argv) > 1 and sys.argv[1] == "--demo":
|
|
17
|
+
run_demo()
|
|
18
|
+
elif len(sys.argv) > 1 and sys.argv[1] == "--help":
|
|
19
|
+
print_help()
|
|
20
|
+
else:
|
|
21
|
+
run_interactive()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def print_help():
|
|
25
|
+
print("""
|
|
26
|
+
QSL - Quantum Search Language
|
|
27
|
+
=============================
|
|
28
|
+
|
|
29
|
+
用法:
|
|
30
|
+
python -m qsl 交互式模式
|
|
31
|
+
python -m qsl --demo 1 运行指定示例
|
|
32
|
+
python -m qsl --help 显示此帮助
|
|
33
|
+
""")
|
|
34
|
+
print("""
|
|
35
|
+
Python API:
|
|
36
|
+
>>> from qsl import QSLProgram, QSLCompiler
|
|
37
|
+
>>> program = QSLProgram(
|
|
38
|
+
... name="我的搜索问题",
|
|
39
|
+
... n_qubits=4,
|
|
40
|
+
... premises=["x0 & x1", "~x2 | x3"],
|
|
41
|
+
... shots=10
|
|
42
|
+
... )
|
|
43
|
+
>>> compiler = QSLCompiler(backend="simulator")
|
|
44
|
+
>>> result = compiler.compile_and_run(program)
|
|
45
|
+
""")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def run_demo():
|
|
49
|
+
print("\n" + "=" * 60)
|
|
50
|
+
print(" QSL - Quantum Search Language v1.0.0")
|
|
51
|
+
print(" Grover 量子搜索演示")
|
|
52
|
+
print("=" * 60)
|
|
53
|
+
|
|
54
|
+
from qsl import QSLProgram, QSLCompiler
|
|
55
|
+
|
|
56
|
+
# 内嵌示例
|
|
57
|
+
demos = {
|
|
58
|
+
"1": ("SAT 求解 (n=3)", QSLProgram(
|
|
59
|
+
name="3-SAT 求解",
|
|
60
|
+
n_qubits=3,
|
|
61
|
+
premises=["x0 | ~x1", "x1 | x2", "~x0 | ~x2"],
|
|
62
|
+
shots=5,
|
|
63
|
+
)),
|
|
64
|
+
"2": ("图着色 (3顶点2色)", QSLProgram(
|
|
65
|
+
name="图着色",
|
|
66
|
+
n_qubits=3,
|
|
67
|
+
premises=["x0 ^ x1", "x1 ^ x2"],
|
|
68
|
+
shots=5,
|
|
69
|
+
)),
|
|
70
|
+
"3": ("恰好一个1 (n=3)", QSLProgram(
|
|
71
|
+
name="恰好一个1",
|
|
72
|
+
n_qubits=3,
|
|
73
|
+
premises=["x0 | x1 | x2", "~x0 | ~x1", "~x0 | ~x2", "~x1 | ~x2"],
|
|
74
|
+
shots=5,
|
|
75
|
+
)),
|
|
76
|
+
"4": ("大空间搜索 (n=6)", QSLProgram(
|
|
77
|
+
name="大空间搜索",
|
|
78
|
+
n_qubits=6,
|
|
79
|
+
premises=["~(x0 ^ x1 ^ x2)", "x3 | x4", "x5"],
|
|
80
|
+
shots=3,
|
|
81
|
+
)),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
print("\n可用示例:")
|
|
85
|
+
for key, (desc, _) in demos.items():
|
|
86
|
+
print(f" {key}. {desc}")
|
|
87
|
+
print(f" 0. 运行所有示例")
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
choice = input("\n请选择 [0-4]: ").strip()
|
|
91
|
+
if not choice:
|
|
92
|
+
choice = "0"
|
|
93
|
+
except (EOFError, KeyboardInterrupt):
|
|
94
|
+
print()
|
|
95
|
+
return
|
|
96
|
+
|
|
97
|
+
compiler = QSLCompiler(verbose=True)
|
|
98
|
+
|
|
99
|
+
if choice == "0":
|
|
100
|
+
for key, (desc, program) in demos.items():
|
|
101
|
+
print(f"\n{'─'*60}")
|
|
102
|
+
print(f" 示例 {key}: {desc}")
|
|
103
|
+
print(f"{'─'*60}")
|
|
104
|
+
try:
|
|
105
|
+
result = compiler.compile_and_run(program)
|
|
106
|
+
print(f" 结果: {result.summary()}")
|
|
107
|
+
except Exception as e:
|
|
108
|
+
print(f" 错误: {e}")
|
|
109
|
+
elif choice in demos:
|
|
110
|
+
desc, program = demos[choice]
|
|
111
|
+
print(f"\n{'─'*60}")
|
|
112
|
+
print(f" 示例 {choice}: {desc}")
|
|
113
|
+
print(f"{'─'*60}")
|
|
114
|
+
try:
|
|
115
|
+
result = compiler.compile_and_run(program)
|
|
116
|
+
print(f" 结果: {result.summary()}")
|
|
117
|
+
except Exception as e:
|
|
118
|
+
print(f" 错误: {e}")
|
|
119
|
+
else:
|
|
120
|
+
print(f"无效选择: {choice}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def run_interactive():
|
|
124
|
+
print("\n" + "=" * 60)
|
|
125
|
+
print(" QSL - Quantum Search Language v1.0.0")
|
|
126
|
+
print(" Quantum Search Language")
|
|
127
|
+
print("=" * 60)
|
|
128
|
+
print("\n用法: python -m qsl --demo 运行演示")
|
|
129
|
+
print(" python -m qsl --help 查看帮助")
|
|
130
|
+
print()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
if __name__ == "__main__":
|
|
134
|
+
main()
|
qsl/ai/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""QSL AI Quantum Scientist - LLM-powered quantum computing automation."""
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from .translator import ProblemTranslator
|
|
5
|
+
except ImportError:
|
|
6
|
+
ProblemTranslator = None
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from .agent import QuantumAgent
|
|
10
|
+
except ImportError:
|
|
11
|
+
QuantumAgent = None
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
from .hypotheses import HypothesisTester
|
|
15
|
+
except ImportError:
|
|
16
|
+
HypothesisTester = None
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
from .discovery import DiscoveryPipeline
|
|
20
|
+
except ImportError:
|
|
21
|
+
DiscoveryPipeline = None
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from .explainer import ResultExplainer
|
|
25
|
+
except ImportError:
|
|
26
|
+
ResultExplainer = None
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"ProblemTranslator",
|
|
30
|
+
"QuantumAgent",
|
|
31
|
+
"HypothesisTester",
|
|
32
|
+
"DiscoveryPipeline",
|
|
33
|
+
"ResultExplainer",
|
|
34
|
+
]
|
qsl/ai/agent.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Autonomous Quantum Agent - Self-directed quantum problem solving.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Optional, Any
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from langchain.agents import AgentExecutor, create_react_agent
|
|
11
|
+
from langchain_openai import ChatOpenAI
|
|
12
|
+
from langchain.tools import Tool
|
|
13
|
+
HAS_LANGCHAIN = True
|
|
14
|
+
except ImportError:
|
|
15
|
+
HAS_LANGCHAIN = False
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class AgentResult:
|
|
20
|
+
"""Result from a QuantumAgent run."""
|
|
21
|
+
task: str
|
|
22
|
+
success: bool
|
|
23
|
+
algorithm_used: str
|
|
24
|
+
backend_used: str
|
|
25
|
+
iterations: int
|
|
26
|
+
result_summary: str
|
|
27
|
+
data: dict = field(default_factory=dict)
|
|
28
|
+
error: Optional[str] = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class QuantumAgent:
|
|
32
|
+
"""
|
|
33
|
+
Autonomous quantum computing agent.
|
|
34
|
+
|
|
35
|
+
Decision chain:
|
|
36
|
+
LLM parse -> Select algorithm -> Select backend -> Compile -> Execute ->
|
|
37
|
+
LLM explain results -> Decide iteration (max 3 rounds)
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
task_description: Natural language task description
|
|
41
|
+
max_iterations: Maximum decision rounds (default 3)
|
|
42
|
+
verbose: Print progress messages
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self,
|
|
46
|
+
task_description: str,
|
|
47
|
+
max_iterations: int = 3,
|
|
48
|
+
verbose: bool = True):
|
|
49
|
+
self.task = task_description
|
|
50
|
+
self.max_iterations = max_iterations
|
|
51
|
+
self.verbose = verbose
|
|
52
|
+
self._llm = None
|
|
53
|
+
self._tools = []
|
|
54
|
+
|
|
55
|
+
def _init_llm(self):
|
|
56
|
+
"""Initialize LLM if available."""
|
|
57
|
+
if self._llm is not None:
|
|
58
|
+
return self._llm
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
import os
|
|
62
|
+
api_key = os.environ.get("OPENAI_API_KEY")
|
|
63
|
+
if not api_key:
|
|
64
|
+
if HAS_LANGCHAIN:
|
|
65
|
+
self._llm = ChatOpenAI(model="gpt-4", api_key=api_key)
|
|
66
|
+
return self._llm
|
|
67
|
+
if HAS_LANGCHAIN:
|
|
68
|
+
self._llm = ChatOpenAI(model="gpt-4", api_key=api_key)
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
return self._llm
|
|
73
|
+
|
|
74
|
+
def run(self) -> AgentResult:
|
|
75
|
+
"""
|
|
76
|
+
Execute the agent's decision loop.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
AgentResult with task outcome
|
|
80
|
+
"""
|
|
81
|
+
if self.verbose:
|
|
82
|
+
print(f"\n{'='*60}")
|
|
83
|
+
print(f" Quantum Agent: {self.task}")
|
|
84
|
+
print(f"{'='*60}")
|
|
85
|
+
|
|
86
|
+
llm = self._init_llm()
|
|
87
|
+
|
|
88
|
+
# Step 1: Parse task
|
|
89
|
+
algorithm, params = self._select_algorithm(llm)
|
|
90
|
+
if self.verbose:
|
|
91
|
+
print(f" Selected algorithm: {algorithm}")
|
|
92
|
+
|
|
93
|
+
# Step 2: Select backend
|
|
94
|
+
backend = self._select_backend(params)
|
|
95
|
+
if self.verbose:
|
|
96
|
+
print(f" Selected backend: {backend}")
|
|
97
|
+
|
|
98
|
+
# Step 3-5: Execute with retry loop
|
|
99
|
+
for iteration in range(1, self.max_iterations + 1):
|
|
100
|
+
try:
|
|
101
|
+
result = self._execute_quantum_task(algorithm, params, backend)
|
|
102
|
+
|
|
103
|
+
if result.get("success", False):
|
|
104
|
+
if self.verbose:
|
|
105
|
+
print(f" Iteration {iteration}: Success!")
|
|
106
|
+
|
|
107
|
+
# LLM explain results
|
|
108
|
+
explanation = self._explain_result(llm, result)
|
|
109
|
+
|
|
110
|
+
return AgentResult(
|
|
111
|
+
task=self.task,
|
|
112
|
+
success=True,
|
|
113
|
+
algorithm_used=algorithm,
|
|
114
|
+
backend_used=backend,
|
|
115
|
+
iterations=iteration,
|
|
116
|
+
result_summary=explanation or "Task completed",
|
|
117
|
+
data=result,
|
|
118
|
+
)
|
|
119
|
+
else:
|
|
120
|
+
if self.verbose:
|
|
121
|
+
print(f" Iteration {iteration}: Failed, retrying...")
|
|
122
|
+
|
|
123
|
+
# Update parameters based on failure
|
|
124
|
+
params = self._adjust_params(algorithm, params, result)
|
|
125
|
+
|
|
126
|
+
except Exception as e:
|
|
127
|
+
if self.verbose:
|
|
128
|
+
print(f" Iteration {iteration}: Error - {e}")
|
|
129
|
+
if iteration >= self.max_iterations:
|
|
130
|
+
return AgentResult(
|
|
131
|
+
task=self.task,
|
|
132
|
+
success=False,
|
|
133
|
+
algorithm_used=algorithm,
|
|
134
|
+
backend_used=backend,
|
|
135
|
+
iterations=iteration,
|
|
136
|
+
result_summary="Failed after max iterations",
|
|
137
|
+
error=str(e),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return AgentResult(
|
|
141
|
+
task=self.task,
|
|
142
|
+
success=False,
|
|
143
|
+
algorithm_used=algorithm,
|
|
144
|
+
backend_used=backend,
|
|
145
|
+
iterations=self.max_iterations,
|
|
146
|
+
result_summary="Max iterations reached without success",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
def _select_algorithm(self, llm) -> tuple[str, dict]:
|
|
150
|
+
"""Determine which quantum algorithm to use."""
|
|
151
|
+
task_lower = self.task.lower()
|
|
152
|
+
|
|
153
|
+
if llm:
|
|
154
|
+
prompt = f"""Select the best quantum algorithm for this task.
|
|
155
|
+
Options: grover, shor, qaoa, vqe
|
|
156
|
+
|
|
157
|
+
Task: {self.task}
|
|
158
|
+
|
|
159
|
+
Respond with just the algorithm name."""
|
|
160
|
+
try:
|
|
161
|
+
response = llm.invoke(prompt)
|
|
162
|
+
alg = response.content.strip().lower()
|
|
163
|
+
if alg in ("grover", "shor", "qaoa", "vqe"):
|
|
164
|
+
return alg, {"n_qubits": 4}
|
|
165
|
+
except Exception:
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
# Fallback: keyword matching
|
|
169
|
+
if any(w in task_lower for w in ("factor", "rsa", "decrypt", "shor")):
|
|
170
|
+
return "shor", {"N": 15}
|
|
171
|
+
elif any(w in task_lower for w in ("optimize", "maxcut", "portfolio", "qaoa")):
|
|
172
|
+
return "qaoa", {"n_qubits": 4}
|
|
173
|
+
elif any(w in task_lower for w in ("energy", "ground", "chemistry", "vqe")):
|
|
174
|
+
return "vqe", {"n_qubits": 4}
|
|
175
|
+
else:
|
|
176
|
+
return "grover", {"n_qubits": 4, "premises": ["x0 & x1"]}
|
|
177
|
+
|
|
178
|
+
def _select_backend(self, params: dict) -> str:
|
|
179
|
+
"""Select optimal backend."""
|
|
180
|
+
n_qubits = params.get("n_qubits", 4)
|
|
181
|
+
if n_qubits <= 20:
|
|
182
|
+
return "simulator"
|
|
183
|
+
elif n_qubits <= 127:
|
|
184
|
+
return "ibm_kyoto"
|
|
185
|
+
else:
|
|
186
|
+
return "aws_sv1"
|
|
187
|
+
|
|
188
|
+
def _execute_quantum_task(self, algorithm: str, params: dict, backend: str) -> dict:
|
|
189
|
+
"""Execute the quantum computation."""
|
|
190
|
+
try:
|
|
191
|
+
if algorithm == "grover":
|
|
192
|
+
from ..compiler.program import QSLProgram
|
|
193
|
+
from ..compiler.compiler import QSLCompiler
|
|
194
|
+
|
|
195
|
+
prog = QSLProgram(
|
|
196
|
+
name=self.task,
|
|
197
|
+
n_qubits=params.get("n_qubits", 4),
|
|
198
|
+
premises=params.get("premises", ["x0 & x1"]),
|
|
199
|
+
shots=100,
|
|
200
|
+
backend=backend,
|
|
201
|
+
)
|
|
202
|
+
compiler = QSLCompiler(backend=backend)
|
|
203
|
+
result = compiler.compile_and_run(prog)
|
|
204
|
+
|
|
205
|
+
solutions = result.get_solutions()
|
|
206
|
+
return {
|
|
207
|
+
"success": len(solutions) > 0,
|
|
208
|
+
"solutions": solutions,
|
|
209
|
+
"iterations": result.iterations,
|
|
210
|
+
"success_rate": result.empirical_success_rate,
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
elif algorithm == "shor":
|
|
214
|
+
from ..algorithms.shor import ShorSolver
|
|
215
|
+
N = params.get("N", 15)
|
|
216
|
+
solver = ShorSolver(N)
|
|
217
|
+
factors = solver.factor()
|
|
218
|
+
return {
|
|
219
|
+
"success": len(factors) > 0 and factors != [N],
|
|
220
|
+
"factors": factors,
|
|
221
|
+
"N": N,
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
elif algorithm == "qaoa":
|
|
225
|
+
from ..algorithms.qaoa import QAOA
|
|
226
|
+
import numpy as np
|
|
227
|
+
n = params.get("n_qubits", 4)
|
|
228
|
+
cost = np.ones((n, n)) * 0.5
|
|
229
|
+
qaoa = QAOA(n, cost, p=1)
|
|
230
|
+
opt_params, energy = qaoa.optimize(maxiter=50)
|
|
231
|
+
best, best_cost = qaoa.get_optimal_bitstring()
|
|
232
|
+
return {
|
|
233
|
+
"success": True,
|
|
234
|
+
"energy": energy,
|
|
235
|
+
"bitstring": best,
|
|
236
|
+
"cost": best_cost,
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
elif algorithm == "vqe":
|
|
240
|
+
from ..algorithms.vqe import VQE
|
|
241
|
+
h2 = VQE.h2_hamiltonian()
|
|
242
|
+
vqe = VQE(4, h2, ansatz_type="he", n_layers=1)
|
|
243
|
+
energy, state = vqe.optimize(maxiter=50)
|
|
244
|
+
return {
|
|
245
|
+
"success": True,
|
|
246
|
+
"energy": energy,
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
else:
|
|
250
|
+
return {"success": False, "error": f"Unknown algorithm: {algorithm}"}
|
|
251
|
+
|
|
252
|
+
except Exception as e:
|
|
253
|
+
return {"success": False, "error": str(e)}
|
|
254
|
+
|
|
255
|
+
def _explain_result(self, llm, result: dict) -> Optional[str]:
|
|
256
|
+
"""Use LLM to explain quantum results in natural language."""
|
|
257
|
+
if llm is None:
|
|
258
|
+
return str(result)
|
|
259
|
+
|
|
260
|
+
prompt = f"""Explain the following quantum computation result in simple terms:
|
|
261
|
+
Result: {result}
|
|
262
|
+
|
|
263
|
+
Keep it concise (2-3 sentences)."""
|
|
264
|
+
|
|
265
|
+
try:
|
|
266
|
+
response = llm.invoke(prompt)
|
|
267
|
+
return response.content.strip()
|
|
268
|
+
except Exception:
|
|
269
|
+
return str(result)
|
|
270
|
+
|
|
271
|
+
def _adjust_params(self, algorithm: str, params: dict, result: dict) -> dict:
|
|
272
|
+
"""Adjust parameters based on failure feedback."""
|
|
273
|
+
if "n_qubits" in params:
|
|
274
|
+
params["n_qubits"] = min(params["n_qubits"] + 1, 20)
|
|
275
|
+
return params
|