cqlib-qml 0.1.0b1__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 (91) hide show
  1. cqlib_qml-0.1.0b1/LICENSE +201 -0
  2. cqlib_qml-0.1.0b1/MANIFEST.in +16 -0
  3. cqlib_qml-0.1.0b1/PKG-INFO +131 -0
  4. cqlib_qml-0.1.0b1/README.en.md +92 -0
  5. cqlib_qml-0.1.0b1/README.md +92 -0
  6. cqlib_qml-0.1.0b1/cqlib_qml/__init__.py +58 -0
  7. cqlib_qml-0.1.0b1/cqlib_qml/_configuration.py +53 -0
  8. cqlib_qml-0.1.0b1/cqlib_qml/_numerics.py +31 -0
  9. cqlib_qml-0.1.0b1/cqlib_qml/algorithms/HQNN_classification.py +265 -0
  10. cqlib_qml-0.1.0b1/cqlib_qml/algorithms/QKM.py +362 -0
  11. cqlib_qml-0.1.0b1/cqlib_qml/algorithms/QNN_classification.py +245 -0
  12. cqlib_qml-0.1.0b1/cqlib_qml/algorithms/QSVM.py +340 -0
  13. cqlib_qml-0.1.0b1/cqlib_qml/algorithms/VQC.py +578 -0
  14. cqlib_qml-0.1.0b1/cqlib_qml/algorithms/__init__.py +3 -0
  15. cqlib_qml-0.1.0b1/cqlib_qml/ansatz/BasicQNN.py +153 -0
  16. cqlib_qml-0.1.0b1/cqlib_qml/ansatz/CRADL.py +133 -0
  17. cqlib_qml-0.1.0b1/cqlib_qml/ansatz/CRAML.py +177 -0
  18. cqlib_qml-0.1.0b1/cqlib_qml/ansatz/HE_ansatz.py +239 -0
  19. cqlib_qml-0.1.0b1/cqlib_qml/ansatz/__init__.py +45 -0
  20. cqlib_qml-0.1.0b1/cqlib_qml/ansatz/ansatz.py +1209 -0
  21. cqlib_qml-0.1.0b1/cqlib_qml/data/__init__.py +63 -0
  22. cqlib_qml-0.1.0b1/cqlib_qml/data/data.py +286 -0
  23. cqlib_qml-0.1.0b1/cqlib_qml/data/data_preprocess.py +315 -0
  24. cqlib_qml-0.1.0b1/cqlib_qml/differentiator/__init__.py +47 -0
  25. cqlib_qml-0.1.0b1/cqlib_qml/differentiator/adjoint.py +509 -0
  26. cqlib_qml-0.1.0b1/cqlib_qml/differentiator/parameter_shift.py +284 -0
  27. cqlib_qml-0.1.0b1/cqlib_qml/encoder/FRQI.py +404 -0
  28. cqlib_qml-0.1.0b1/cqlib_qml/encoder/NEQR.py +163 -0
  29. cqlib_qml-0.1.0b1/cqlib_qml/encoder/QubitLattice.py +127 -0
  30. cqlib_qml-0.1.0b1/cqlib_qml/encoder/ZZFeature.py +159 -0
  31. cqlib_qml-0.1.0b1/cqlib_qml/encoder/__init__.py +56 -0
  32. cqlib_qml-0.1.0b1/cqlib_qml/encoder/amplitude.py +162 -0
  33. cqlib_qml-0.1.0b1/cqlib_qml/encoder/angle.py +121 -0
  34. cqlib_qml-0.1.0b1/cqlib_qml/encoder/basis.py +93 -0
  35. cqlib_qml-0.1.0b1/cqlib_qml/encoder/image_encoder.py +131 -0
  36. cqlib_qml-0.1.0b1/cqlib_qml/layer/__init__.py +56 -0
  37. cqlib_qml-0.1.0b1/cqlib_qml/layer/activation.py +438 -0
  38. cqlib_qml-0.1.0b1/cqlib_qml/layer/layer.py +297 -0
  39. cqlib_qml-0.1.0b1/cqlib_qml/layer/linear.py +328 -0
  40. cqlib_qml-0.1.0b1/cqlib_qml/loss.py +407 -0
  41. cqlib_qml-0.1.0b1/cqlib_qml/models/HQNN.py +171 -0
  42. cqlib_qml-0.1.0b1/cqlib_qml/models/QNN.py +154 -0
  43. cqlib_qml-0.1.0b1/cqlib_qml/models/__init__.py +44 -0
  44. cqlib_qml-0.1.0b1/cqlib_qml/models/module.py +397 -0
  45. cqlib_qml-0.1.0b1/cqlib_qml/optimizer.py +684 -0
  46. cqlib_qml-0.1.0b1/cqlib_qml/scheduler.py +614 -0
  47. cqlib_qml-0.1.0b1/cqlib_qml/utils/__init__.py +37 -0
  48. cqlib_qml-0.1.0b1/cqlib_qml/utils/grad_matrix.py +29 -0
  49. cqlib_qml-0.1.0b1/cqlib_qml.egg-info/PKG-INFO +131 -0
  50. cqlib_qml-0.1.0b1/cqlib_qml.egg-info/SOURCES.txt +89 -0
  51. cqlib_qml-0.1.0b1/cqlib_qml.egg-info/dependency_links.txt +1 -0
  52. cqlib_qml-0.1.0b1/cqlib_qml.egg-info/requires.txt +10 -0
  53. cqlib_qml-0.1.0b1/cqlib_qml.egg-info/top_level.txt +1 -0
  54. cqlib_qml-0.1.0b1/docs/tutorials/algorithms.md +859 -0
  55. cqlib_qml-0.1.0b1/docs/tutorials/ansatz.md +638 -0
  56. cqlib_qml-0.1.0b1/docs/tutorials/data.md +718 -0
  57. cqlib_qml-0.1.0b1/docs/tutorials/differentiator.md +602 -0
  58. cqlib_qml-0.1.0b1/docs/tutorials/encoder.md +641 -0
  59. cqlib_qml-0.1.0b1/docs/tutorials/layer.md +424 -0
  60. cqlib_qml-0.1.0b1/docs/tutorials/loss.md +502 -0
  61. cqlib_qml-0.1.0b1/docs/tutorials/models.md +428 -0
  62. cqlib_qml-0.1.0b1/docs/tutorials/optimizer.md +559 -0
  63. cqlib_qml-0.1.0b1/docs/tutorials/scheduler.md +415 -0
  64. cqlib_qml-0.1.0b1/pyproject.toml +61 -0
  65. cqlib_qml-0.1.0b1/requirements-dev.txt +7 -0
  66. cqlib_qml-0.1.0b1/requirements.txt +10 -0
  67. cqlib_qml-0.1.0b1/scripts/release_check.sh +55 -0
  68. cqlib_qml-0.1.0b1/scripts/smoke_test.py +88 -0
  69. cqlib_qml-0.1.0b1/scripts/verify_sdist.py +34 -0
  70. cqlib_qml-0.1.0b1/scripts/verify_wheel.py +36 -0
  71. cqlib_qml-0.1.0b1/setup.cfg +4 -0
  72. cqlib_qml-0.1.0b1/tests/test_activation.py +142 -0
  73. cqlib_qml-0.1.0b1/tests/test_algorithms.py +580 -0
  74. cqlib_qml-0.1.0b1/tests/test_ansatz.py +254 -0
  75. cqlib_qml-0.1.0b1/tests/test_audit_regressions.py +443 -0
  76. cqlib_qml-0.1.0b1/tests/test_checkpoint_followup.py +148 -0
  77. cqlib_qml-0.1.0b1/tests/test_compatibility_recheck.py +267 -0
  78. cqlib_qml-0.1.0b1/tests/test_cqlib2_regressions.py +364 -0
  79. cqlib_qml-0.1.0b1/tests/test_data.py +94 -0
  80. cqlib_qml-0.1.0b1/tests/test_differentiator.py +225 -0
  81. cqlib_qml-0.1.0b1/tests/test_encoders.py +212 -0
  82. cqlib_qml-0.1.0b1/tests/test_extreme_numerical_contracts.py +102 -0
  83. cqlib_qml-0.1.0b1/tests/test_layer.py +101 -0
  84. cqlib_qml-0.1.0b1/tests/test_loss.py +193 -0
  85. cqlib_qml-0.1.0b1/tests/test_models.py +145 -0
  86. cqlib_qml-0.1.0b1/tests/test_module.py +151 -0
  87. cqlib_qml-0.1.0b1/tests/test_numerical_state_contracts.py +224 -0
  88. cqlib_qml-0.1.0b1/tests/test_optimizer.py +190 -0
  89. cqlib_qml-0.1.0b1/tests/test_release_contracts.py +627 -0
  90. cqlib_qml-0.1.0b1/tests/test_residual_regressions.py +84 -0
  91. cqlib_qml-0.1.0b1/tests/test_scheduler.py +215 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,16 @@
1
+ include LICENSE
2
+ include README.md
3
+ include README.en.md
4
+ include pyproject.toml
5
+ include requirements.txt
6
+ recursive-include cqlib_qml *.py
7
+ recursive-include docs/tutorials *.md
8
+ recursive-include scripts *.py *.sh
9
+ recursive-include tests *.py
10
+ include requirements-dev.txt
11
+
12
+ global-exclude __pycache__/*
13
+ global-exclude *.py[cod]
14
+ global-exclude .DS_Store
15
+ global-exclude *.c
16
+ global-exclude *.h
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: cqlib-qml
3
+ Version: 0.1.0b1
4
+ Summary: Quantum machine learning package based on Cqlib
5
+ Author-email: China Telecom Quantum Group Quantum Computing Team <tianyan@chinatelecom.cn>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://qc.zdxlz.com/
8
+ Project-URL: Documentation, https://qc.zdxlz.com/learn/#/resource/informationSpace
9
+ Project-URL: Repository, https://github.com/cq-lib/cqlib-qml
10
+ Project-URL: Issues, https://github.com/cq-lib/cqlib-qml/issues
11
+ Keywords: cqlib,quantum machine learning,quantum neural network,hybrid quantum classical,quantum kernel,quantum support vector machine,variational quantum classifier,quantum image encoding,quantum computing
12
+ Classifier: Environment :: Console
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Intended Audience :: Science/Research
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Topic :: Scientific/Engineering :: Physics
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: autograd>=1.8.0
29
+ Requires-Dist: cqlib>=2.0.0b3
30
+ Requires-Dist: numpy>=2.4.6
31
+ Requires-Dist: PyYAML>=6.0.3
32
+ Requires-Dist: scikit-learn>=1.7.0
33
+ Requires-Dist: scipy>=1.17.1
34
+ Requires-Dist: sympy>=1.14.0
35
+ Requires-Dist: torch>=2.9.1
36
+ Requires-Dist: torchvision>=0.24.1
37
+ Requires-Dist: tqdm>=4.67.1
38
+ Dynamic: license-file
39
+
40
+ # Cqlib-QML
41
+
42
+ 英文版见 [English version](README.en.md)。
43
+
44
+ 本项目是基于 **[Cqlib](https://github.com/cq-lib/cqlib)** 的量子机器学习 Python 工具包,提供经典数据量子编码、参数化量子线路、纯量子与混合量子—经典神经网络、量子核方法及模型训练组件。
45
+
46
+ ## 安装说明
47
+
48
+ 环境要求:Python 3.11 及以上版本,cqlib 2.0.0b3 及以上版本。
49
+
50
+ 从源码安装:
51
+
52
+ ```bash
53
+ git clone https://github.com/cq-lib/cqlib-qml.git
54
+ cd cqlib-qml
55
+ pip install .
56
+ ```
57
+
58
+ 发布到 PyPI 后,也可以直接安装:
59
+
60
+ ```bash
61
+ pip install cqlib-qml
62
+ ```
63
+
64
+ 开发环境安装:
65
+
66
+ ```bash
67
+ pip install -r requirements-dev.txt
68
+ pip install -e .
69
+ ```
70
+
71
+ ## 主要功能
72
+
73
+ - **encoder**:将经典向量和图像编码为量子线路,支持振幅编码、角度编码、基态编码、FRQI、NEQR、Qubit Lattice 和 ZZ Feature Map。
74
+ - **ansatz**:参数化量子线路,包含硬件高效线路、BasicQNN、CRADL 和 CRAML。
75
+ - **models**:纯量子神经网络 `QNN`、混合量子—经典神经网络 `HQNN`,以及用于组合量子与经典组件的 `Module`。
76
+ - **algorithms**:量子核方法 `QKM`、量子支持向量机 `QSVM` 和兼容 scikit-learn 接口的变分量子分类器 `VQC`。
77
+ - **differentiator**:伴随法和参数偏移法量子梯度计算。
78
+ - **layer**:全连接层与常用激活函数,用于构建混合模型的经典部分。
79
+ - **data**:数据集、批加载和图像数据预处理工具。
80
+ - **loss / optimizer / scheduler**:常用损失函数、参数优化器和学习率调度器。
81
+ - **utils**:量子门梯度矩阵等辅助工具。
82
+
83
+ ## 快速开始
84
+
85
+ 下面使用角度编码和量子核构造核矩阵:
86
+
87
+ ```python
88
+ import numpy as np
89
+
90
+ from cqlib_qml.algorithms import QKM
91
+ from cqlib_qml.encoder import AngleEncoder
92
+
93
+ encoder = AngleEncoder(mode="classical")
94
+ kernel = QKM(encoder=encoder)
95
+
96
+ samples = np.array([
97
+ [0.1, 0.2],
98
+ [0.3, 0.4],
99
+ [0.5, 0.6],
100
+ ])
101
+
102
+ kernel_matrix = kernel.kernel(samples)
103
+ print(kernel_matrix)
104
+ ```
105
+
106
+ 构建量子神经网络:
107
+
108
+ ```python
109
+ from cqlib_qml.ansatz import HEAnsatz
110
+ from cqlib_qml.models import QNN
111
+
112
+ ansatz = HEAnsatz(n_qubits=4, d=2, layers=["RY", "CX"])
113
+ ansatz.set_measurement(readouts=[0])
114
+ model = QNN(ansatz=ansatz)
115
+ ```
116
+
117
+ 更多说明参见 [`docs/tutorials`](docs/tutorials)。
118
+
119
+ ## 测试
120
+
121
+ ```bash
122
+ pytest
123
+ ```
124
+
125
+ ## License
126
+
127
+ Apache License 2.0,详见 [LICENSE](LICENSE)。
128
+
129
+ ## Contributing
130
+
131
+ 欢迎贡献!如需改进功能或修复缺陷,请提交 Issue 或发起 Pull Request。
@@ -0,0 +1,92 @@
1
+ # Cqlib-QML
2
+
3
+ See the [Chinese version](README.md).
4
+
5
+ Cqlib-QML is a quantum machine learning Python package based on **[Cqlib](https://github.com/cq-lib/cqlib)**. It provides quantum encoders for classical data, parameterized quantum circuits, quantum and hybrid quantum-classical neural networks, quantum kernel algorithms, and reusable model-training components.
6
+
7
+ ## Installation
8
+
9
+ Python 3.11 or later and cqlib 2.0.0b3 or later are required.
10
+
11
+ Install from source:
12
+
13
+ ```bash
14
+ git clone https://github.com/cq-lib/cqlib-qml.git
15
+ cd cqlib-qml
16
+ pip install .
17
+ ```
18
+
19
+ Once published on PyPI, install it directly with:
20
+
21
+ ```bash
22
+ pip install cqlib-qml
23
+ ```
24
+
25
+ For development:
26
+
27
+ ```bash
28
+ pip install -r requirements-dev.txt
29
+ pip install -e .
30
+ ```
31
+
32
+ ## Features
33
+
34
+ - **encoder**: Amplitude, angle, basis, FRQI, NEQR, Qubit Lattice, and ZZ Feature Map encoders for vectors and images.
35
+ - **ansatz**: Parameterized quantum circuits including hardware-efficient, BasicQNN, CRADL, and CRAML ansatzes.
36
+ - **models**: The pure quantum `QNN`, hybrid quantum-classical `HQNN`, and a `Module` container for composing quantum and classical components.
37
+ - **algorithms**: Quantum Kernel Method (`QKM`), Quantum Support Vector Machine (`QSVM`), and a scikit-learn-compatible Variational Quantum Classifier (`VQC`).
38
+ - **differentiator**: Adjoint and parameter-shift gradient methods.
39
+ - **layer**: Dense layers and common activation functions for hybrid models.
40
+ - **data**: Dataset, batching, and image preprocessing utilities.
41
+ - **loss / optimizer / scheduler**: Loss functions, optimizers, and learning-rate schedulers.
42
+ - **utils**: Helpers including quantum gate derivative matrices.
43
+
44
+ ## Quick Start
45
+
46
+ Create a quantum kernel matrix using angle encoding:
47
+
48
+ ```python
49
+ import numpy as np
50
+
51
+ from cqlib_qml.algorithms import QKM
52
+ from cqlib_qml.encoder import AngleEncoder
53
+
54
+ encoder = AngleEncoder(mode="classical")
55
+ kernel = QKM(encoder=encoder)
56
+
57
+ samples = np.array([
58
+ [0.1, 0.2],
59
+ [0.3, 0.4],
60
+ [0.5, 0.6],
61
+ ])
62
+
63
+ kernel_matrix = kernel.kernel(samples)
64
+ print(kernel_matrix)
65
+ ```
66
+
67
+ Build a quantum neural network:
68
+
69
+ ```python
70
+ from cqlib_qml.ansatz import HEAnsatz
71
+ from cqlib_qml.models import QNN
72
+
73
+ ansatz = HEAnsatz(n_qubits=4, d=2, layers=["RY", "CX"])
74
+ ansatz.set_measurement(readouts=[0])
75
+ model = QNN(ansatz=ansatz)
76
+ ```
77
+
78
+ See [`docs/tutorials`](docs/tutorials) for more information.
79
+
80
+ ## Testing
81
+
82
+ ```bash
83
+ pytest
84
+ ```
85
+
86
+ ## License
87
+
88
+ This project is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE).
89
+
90
+ ## Contributing
91
+
92
+ Contributions are welcome. Please open an issue or submit a pull request for improvements and bug fixes.
@@ -0,0 +1,92 @@
1
+ # Cqlib-QML
2
+
3
+ 英文版见 [English version](README.en.md)。
4
+
5
+ 本项目是基于 **[Cqlib](https://github.com/cq-lib/cqlib)** 的量子机器学习 Python 工具包,提供经典数据量子编码、参数化量子线路、纯量子与混合量子—经典神经网络、量子核方法及模型训练组件。
6
+
7
+ ## 安装说明
8
+
9
+ 环境要求:Python 3.11 及以上版本,cqlib 2.0.0b3 及以上版本。
10
+
11
+ 从源码安装:
12
+
13
+ ```bash
14
+ git clone https://github.com/cq-lib/cqlib-qml.git
15
+ cd cqlib-qml
16
+ pip install .
17
+ ```
18
+
19
+ 发布到 PyPI 后,也可以直接安装:
20
+
21
+ ```bash
22
+ pip install cqlib-qml
23
+ ```
24
+
25
+ 开发环境安装:
26
+
27
+ ```bash
28
+ pip install -r requirements-dev.txt
29
+ pip install -e .
30
+ ```
31
+
32
+ ## 主要功能
33
+
34
+ - **encoder**:将经典向量和图像编码为量子线路,支持振幅编码、角度编码、基态编码、FRQI、NEQR、Qubit Lattice 和 ZZ Feature Map。
35
+ - **ansatz**:参数化量子线路,包含硬件高效线路、BasicQNN、CRADL 和 CRAML。
36
+ - **models**:纯量子神经网络 `QNN`、混合量子—经典神经网络 `HQNN`,以及用于组合量子与经典组件的 `Module`。
37
+ - **algorithms**:量子核方法 `QKM`、量子支持向量机 `QSVM` 和兼容 scikit-learn 接口的变分量子分类器 `VQC`。
38
+ - **differentiator**:伴随法和参数偏移法量子梯度计算。
39
+ - **layer**:全连接层与常用激活函数,用于构建混合模型的经典部分。
40
+ - **data**:数据集、批加载和图像数据预处理工具。
41
+ - **loss / optimizer / scheduler**:常用损失函数、参数优化器和学习率调度器。
42
+ - **utils**:量子门梯度矩阵等辅助工具。
43
+
44
+ ## 快速开始
45
+
46
+ 下面使用角度编码和量子核构造核矩阵:
47
+
48
+ ```python
49
+ import numpy as np
50
+
51
+ from cqlib_qml.algorithms import QKM
52
+ from cqlib_qml.encoder import AngleEncoder
53
+
54
+ encoder = AngleEncoder(mode="classical")
55
+ kernel = QKM(encoder=encoder)
56
+
57
+ samples = np.array([
58
+ [0.1, 0.2],
59
+ [0.3, 0.4],
60
+ [0.5, 0.6],
61
+ ])
62
+
63
+ kernel_matrix = kernel.kernel(samples)
64
+ print(kernel_matrix)
65
+ ```
66
+
67
+ 构建量子神经网络:
68
+
69
+ ```python
70
+ from cqlib_qml.ansatz import HEAnsatz
71
+ from cqlib_qml.models import QNN
72
+
73
+ ansatz = HEAnsatz(n_qubits=4, d=2, layers=["RY", "CX"])
74
+ ansatz.set_measurement(readouts=[0])
75
+ model = QNN(ansatz=ansatz)
76
+ ```
77
+
78
+ 更多说明参见 [`docs/tutorials`](docs/tutorials)。
79
+
80
+ ## 测试
81
+
82
+ ```bash
83
+ pytest
84
+ ```
85
+
86
+ ## License
87
+
88
+ Apache License 2.0,详见 [LICENSE](LICENSE)。
89
+
90
+ ## Contributing
91
+
92
+ 欢迎贡献!如需改进功能或修复缺陷,请提交 Issue 或发起 Pull Request。
@@ -0,0 +1,58 @@
1
+ # cqlib_qml/__init__.py
2
+ """
3
+ Cqlib-QML: Quantum machine learning package based on Cqlib.
4
+
5
+ This package provides quantum machine learning building blocks on top of
6
+ the `cqlib <https://github.com/cq-lib/cqlib>`_ quantum computing library,
7
+ including data encoders, parameterized quantum circuits (ansatz),
8
+ differentiators, neural network models, and quantum algorithms.
9
+
10
+ Available Subpackages:
11
+ - algorithms: Quantum machine learning algorithms (QKM, QSVM, VQC).
12
+ - ansatz: Parameterized quantum circuits (HEAnsatz, BasicQNN, CRADL, CRAML).
13
+ - data: Classical data loading and preprocessing utilities.
14
+ - differentiator: Gradient computation strategies (adjoint, parameter-shift).
15
+ - encoder: Quantum data encoders (Amplitude, Angle, Basis, FRQI, NEQR).
16
+ - layer: Hybrid quantum-classical layers (Linear, activations).
17
+ - models: Quantum neural network models (QNN, HQNN).
18
+ - utils: Gradient matrix computation and other utilities.
19
+
20
+ Examples:
21
+ >>> import numpy as np
22
+ >>> from cqlib_qml.ansatz import HEAnsatz
23
+ >>> from cqlib_qml.models import QNN
24
+ >>>
25
+ >>> ansatz = HEAnsatz(n_qubits=4, d=2, layers=["RY", "CX"])
26
+ >>> ansatz.set_measurement(readouts=[0])
27
+ >>> model = QNN(ansatz=ansatz)
28
+ """
29
+
30
+ from . import algorithms, ansatz, data, differentiator, encoder, layer, models, utils
31
+ from .loss import BCELoss, CrossEntropy, HingeLoss, LossFun, MSELoss, SoftmaxCrossEntropy
32
+ from .optimizer import AdaGrad, Adam, OptimizerBase, OptimizerInitializer, RMSProp, SGD
33
+
34
+ __version__ = "0.1.0-beta.1"
35
+
36
+ __all__ = [
37
+ "algorithms",
38
+ "ansatz",
39
+ "data",
40
+ "differentiator",
41
+ "encoder",
42
+ "layer",
43
+ "models",
44
+ "utils",
45
+ "LossFun",
46
+ "HingeLoss",
47
+ "MSELoss",
48
+ "BCELoss",
49
+ "CrossEntropy",
50
+ "SoftmaxCrossEntropy",
51
+ "OptimizerBase",
52
+ "OptimizerInitializer",
53
+ "SGD",
54
+ "AdaGrad",
55
+ "RMSProp",
56
+ "Adam",
57
+ "__version__",
58
+ ]
@@ -0,0 +1,53 @@
1
+ """Parse constructor-like configuration without evaluating Python code."""
2
+ import ast
3
+ import inspect
4
+
5
+
6
+ def parse_configuration(value, registry, nested=None):
7
+ """Accept a registered name or keyword-only call with literal values.
8
+
9
+ Nested calls are restricted to the supplied scheduler registry. Attribute
10
+ access, positional arguments and expanded arguments are never evaluated.
11
+ """
12
+ try:
13
+ tree = ast.parse(value.strip(), mode='eval').body
14
+ except (SyntaxError, TypeError, AttributeError) as exc:
15
+ raise ValueError(f'Invalid configuration: {value!r}') from exc
16
+
17
+ def construct(node, constructors):
18
+ if isinstance(node, ast.Name):
19
+ name, keywords = node.id, []
20
+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and not node.args:
21
+ name, keywords = node.func.id, node.keywords
22
+ else:
23
+ raise ValueError('Configuration must be a registered name or keyword-only call')
24
+ constructor = constructors.get(name.casefold())
25
+ if constructor is None:
26
+ raise ValueError(f'Unsupported configuration name: {name}')
27
+ allowed = {key for key, parameter in inspect.signature(constructor).parameters.items()
28
+ if parameter.kind in (parameter.POSITIONAL_OR_KEYWORD, parameter.KEYWORD_ONLY)}
29
+ kwargs = {}
30
+ for keyword in keywords:
31
+ key = keyword.arg
32
+ if key not in allowed or key in kwargs:
33
+ raise ValueError(f'Unknown or duplicate parameter: {key}')
34
+ if isinstance(keyword.value, ast.Call) and key == 'lr_scheduler' and nested:
35
+ kwargs[key] = construct(keyword.value, nested)
36
+ else:
37
+ try:
38
+ kwargs[key] = ast.literal_eval(keyword.value)
39
+ except (ValueError, TypeError) as exc:
40
+ raise ValueError(f'Parameter {key} must be a literal') from exc
41
+ return constructor(**kwargs)
42
+
43
+ return construct(tree, registry)
44
+
45
+
46
+ def same_parameter_value(old, new):
47
+ """Compare scalar configurations without assuming array equality is scalar."""
48
+ if old is new:
49
+ return True
50
+ try:
51
+ return bool(old == new)
52
+ except (TypeError, ValueError):
53
+ return False
@@ -0,0 +1,31 @@
1
+ """Internal scaling helpers that avoid complex reciprocal overflow."""
2
+ import numpy as np
3
+
4
+
5
+ def scaled_vector(vector):
6
+ """Return a vector at unit component scale and its real scale factor.
7
+
8
+ Divide real and imaginary components separately: complex division can
9
+ overflow its reciprocal for a finite, subnormal real denominator.
10
+ Exact zero is returned unchanged with scale zero.
11
+ """
12
+ vector = np.asarray(vector)
13
+ if not np.isfinite(vector).all():
14
+ raise ValueError("Vector components must be finite.")
15
+ scale = max(np.max(np.abs(vector.real), initial=0.),
16
+ np.max(np.abs(vector.imag), initial=0.))
17
+ if scale == 0:
18
+ return vector.copy(), scale
19
+ if np.iscomplexobj(vector):
20
+ scaled = np.empty(vector.shape, dtype=np.complex128)
21
+ scaled.real = vector.real / scale
22
+ scaled.imag = vector.imag / scale
23
+ else:
24
+ scaled = vector / scale
25
+ return scaled, scale
26
+
27
+
28
+ def stable_norm(vector):
29
+ """Compute a Euclidean norm without squaring unscaled components."""
30
+ scaled, scale = scaled_vector(vector)
31
+ return scale * np.linalg.norm(scaled)