Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@ This source code is licensed under the Apache License Version 2.0 <br/>

pyqpanda-algorithm 是由本源量子(Origin Quantum)开发的量子算法软件包,旨在为量子计算开发者提供一套标准化、模块化、高性能的基础算法库。该库集成了多种在金融、机器学习、组合优化、科学计算等领域广泛应用的量子算法,帮助用户快速实现从理论到代码的转化,提升开发效率并确保算法在不同量子平台上的可移植性。

软件包官网: [https://qcloud.originqc.com.cn/zh/programming/pyqpanda-algorithm]
软件包官网: [https://qcloud.originqc.com.cn/zh/programming/pyqpanda-algorithm]

### QSEncode-Insight

新增的 QSEncode-Insight 根据保真度预算、态制备兼容性和实际编译资源,
推荐压缩或明确拒绝无收益的压缩,同时保持原 `QSpare_Code` 接口不变。
该创新应用复用 PyQPanda3 已有态制备原语;原创贡献是误差预算、能力过滤、
编译资源审计、确定性选择、语义验证与拒绝压缩组成的完整工具链,
不宣称重新发明底层态制备算法。
使用说明、CLI、Notebook 与验证边界见
[QSEncode-Insight 文档](pyqpanda-algorithm/pyqpanda_alg/QSEncode/README.md)。

------

Expand Down
10 changes: 9 additions & 1 deletion README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@
## Introduction
pyqpanda-algorithm is a quantum algorithm software package developed by Origin Quantum, designed to provide quantum computing developers with a standardized, modular, and high-performance foundational algorithm library. This library integrates a variety of quantum algorithms widely used in finance, machine learning, combinatorial optimization, scientific computing, and other fields. It helps users quickly translate theories into code, improve development efficiency, and ensure algorithm portability across different quantum platforms.

Official Website: [https://qcloud.originqc.com.cn/zh/programming/pyqpanda-algorithm]
Official Website: [https://qcloud.originqc.com.cn/zh/programming/pyqpanda-algorithm]

### QSEncode-Insight

QSEncode-Insight uses a fidelity budget, preparation compatibility, and actual
compiled resources to recommend compression or explicitly refuse an
unprofitable compression. The existing `QSpare_Code` API remains unchanged.
See the [QSEncode-Insight guide](pyqpanda-algorithm/pyqpanda_alg/QSEncode/README.md)
for the CLI, notebook, evidence scope, and reproducible examples.

------

Expand Down
224 changes: 224 additions & 0 deletions pyqpanda-algorithm/example/QAlgBase/QSEncode_Insight_Demo.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# QSEncode-Insight: Resource-Aware State Preparation\n",
"\n",
"**Audience:** contest reviewers and PyQPanda users. **Prerequisites:** a source checkout with PyQPanda3, NumPy, and SciPy.\n",
"\n",
"**Goals:** compare a refusal with a compression recommendation, inspect candidates and resources, prepare a runnable program, and distinguish standard from audit verification."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Outline\n",
"\n",
"1. Load the sealed Gaussian N=8 example.\n",
"2. Compare Walsh refusal with Fourier compression.\n",
"3. Inspect candidates, resources, and the prepared artifact.\n",
"4. Run a five-repeat audit and check EvidenceScope."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"import sys\n",
"import numpy as np\n",
"\n",
"# Support Run All from the repository root or this example directory.\n",
"for root in (Path.cwd(), *Path.cwd().parents):\n",
" source_root = root / 'pyqpanda-algorithm'\n",
" if (source_root / 'pyqpanda_alg').is_dir():\n",
" sys.path.insert(0, str(source_root)); break\n",
" if (root / 'pyqpanda_alg').is_dir():\n",
" sys.path.insert(0, str(root)); break\n",
"\n",
"from pyqpanda_alg.QSEncode import QSEncodeInsight\n",
"\n",
"probabilities = np.array([\n",
" 0.0006917643261373052, 0.015724004731018214,\n",
" 0.1261730210273901, 0.3574112099154543,\n",
" 0.3574112099154544, 0.1261730210273902,\n",
" 0.01572400473101823, 0.0006917643261373052,\n",
"])\n",
"float(probabilities.sum()), len(probabilities)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Walsh mode refuses compression\n",
"\n",
"A smaller transformed representation is not automatically a cheaper compiled program."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"walsh_engine = QSEncodeInsight(basis='walsh')\n",
"walsh_result = walsh_engine.analyze(probabilities)\n",
"{'decision': walsh_result.selection.decision.value,\n",
" 'k_star': walsh_result.error_budget.k_star,\n",
" 'baseline_2q': walsh_result.selection.baseline_resource.compiled_two_qubit_gates,\n",
" 'baseline_depth': walsh_result.selection.baseline_resource.compiled_depth}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Fourier mode selects sparse preparation\n",
"\n",
"The basis is explicit; v1 does not compare Walsh and Fourier automatically."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fourier_engine = QSEncodeInsight(basis='fourier')\n",
"fourier_result = fourier_engine.analyze(probabilities)\n",
"{'decision': fourier_result.selection.decision.value,\n",
" 'k_star': fourier_result.error_budget.k_star,\n",
" 'winner': fourier_result.selection.selected_candidate_id,\n",
" 'method': fourier_result.selection.method.value}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Candidate table and resource attribution\n",
"\n",
"Incompatible candidates remain visible. Only k=4 is displayed to keep output small."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"candidate_table = []\n",
"for candidate in fourier_result.candidates:\n",
" if candidate.k == 4:\n",
" audit = candidate.resource_audit\n",
" candidate_table.append({\n",
" 'candidate': candidate.candidate_id,\n",
" 'compatible': candidate.capability.compatible,\n",
" 'eligible': candidate.eligible,\n",
" '2q': None if audit is None else audit.compiled_two_qubit_gates,\n",
" 'depth': None if audit is None else audit.compiled_depth,\n",
" 'reason': candidate.eligibility_reason})\n",
"candidate_table"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"attr = fourier_result.attribution\n",
"{'2q_total_truncation_preparation': (attr.total_two_qubit_difference, attr.truncation_two_qubit_difference, attr.preparation_two_qubit_difference),\n",
" 'depth_total_truncation_preparation': (attr.total_depth_difference, attr.truncation_depth_difference, attr.preparation_depth_difference)}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Prepare a runnable program\n",
"\n",
"InsightResult remains JSON-safe; the QProg lives in a separate artifact."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"artifact = fourier_engine.prepare(probabilities, result=fourier_result)\n",
"{'candidate': artifact.selected_candidate_id, 'k': artifact.k,\n",
" 'output_qubits': artifact.output_qubits, 'ancillas': artifact.ancillas,\n",
" 'verification': artifact.verification_status}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Audit verification and EvidenceScope\n",
"\n",
"Standard does not claim compiled semantic certification. Audit reuses the five compiled attempts and requires 5/5 passes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"audit_result = QSEncodeInsight(basis='fourier', verification='audit').analyze(probabilities)\n",
"{'status': audit_result.semantic_verification.status,\n",
" 'attempts': len(audit_result.semantic_verification.attempts),\n",
" 'minimum_fidelity': audit_result.semantic_verification.minimum_fidelity,\n",
" 'evidence_scope': audit_result.evidence_scope.status.value}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise\n",
"\n",
"Predict the EvidenceScope status for `fidelity_target=0.98`. The answer scaffold below avoids extra compilation during the default Run All; uncomment the analysis when you want to verify it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# outside = QSEncodeInsight(basis='walsh', fidelity_target=0.98).analyze(probabilities)\n",
"# outside.evidence_scope.status.value, outside.evidence_scope.reasons\n",
"expected_status = 'outside_validated_scope'\n",
"expected_status"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Limitations\n",
"\n",
"- These are compiled-resource results, not hardware speedup evidence.\n",
"- The preregistered validation scope is N<=64; Dirichlet inputs were weaker.\n",
"- v1 has no automatic cross-basis selector.\n",
"- Large OriginIR, statevectors, and Locked benchmark artifacts are intentionally not embedded."
]
}
],
"metadata": {
"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
"language_info": {"name": "python", "version": "3.14"}
},
"nbformat": 4,
"nbformat_minor": 5
}
57 changes: 57 additions & 0 deletions pyqpanda-algorithm/pyqpanda_alg/QSEncode/BENCHMARK_EVIDENCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# QSEncode-Insight benchmark evidence

## Confirmatory design

The final generalization benchmark was preregistered before its Locked Test was
run. Its primary data comprised 60 independent distribution-design instances
across five equally weighted families, each evaluated at
`N={8,16,32,64}` and in Walsh and Fourier modes: 480 evaluation cells.

The primary product metric was `selector-all`: `do_not_compress` cells remained
in the analysis with zero resource gain. Walsh and Fourier were evaluated
separately; the benchmark did not test an automatic cross-basis selector.

## Locked Test result

All 480 cells completed under the frozen environment and analysis protocol.

A presentation-oriented view of the same frozen results, including dimension,
family, refusal, and attribution breakdowns, is available in
[BENCHMARK_VISUAL_SUMMARY.md](BENCHMARK_VISUAL_SUMMARY.md). It is descriptive
only and does not replace the preregistered aggregation below.

| Basis | Compiled 2q selector-all | Compiled depth selector-all | Gate |
|---|---:|---:|---|
| Walsh | 45.27% | 48.78% | strong pass |
| Fourier | 71.11% | 69.82% | strong pass |

There were 55 `do_not_compress` decisions among the 480 cells (11.46%). They
were not removed from the main statistic.

The preregistered hierarchical point estimate determined the gate. Cluster
bootstrap intervals described stability and did not replace the gate rule.

## Interpretation

The mechanisms differed by basis:

- Walsh two-qubit savings came predominantly from preparation-strategy choice;
- Fourier savings combined fidelity-budget truncation with an additional
preparation-strategy contribution.

The Dirichlet family was much weaker than Gaussian, bimodal, exponential, and
step families. This negative evidence is retained: QSEncode-Insight diagnoses
whether an input is worth compressing rather than claiming that every
distribution is compressible.

Candidate incompatibility was also common, particularly for DS preparation.
The final recommendation nevertheless required a compatible, correctness-
checked candidate and five successful compiled attempts. Capability filtering
and explicit refusal are therefore core behavior, not cosmetic reporting.

## Claim boundary

Within the preregistered N<=64 test scope, Walsh and Fourier modes both met the
predefined compiled-resource gate. These results do not establish quantum
advantage, hardware runtime acceleration, behavior at larger dimensions, or an
automatic best-basis selector.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# QSEncode-Insight benchmark visual summary

This page presents the already frozen Locked Generalization Test. It does not
rerun the benchmark, introduce a new metric, or replace the preregistered gate.
The main design contained 60 independent distribution-design instances and 480
evaluation cells across five equally weighted families, `N={8,16,32,64}`, and
separately selected Walsh and Fourier modes.

![Selector-all reductions by dimension](assets/benchmark_by_dimension.svg)

The dimension view is descriptive: each point is the median over the 60 cells
at that basis and dimension. It must not be substituted for the preregistered
instance → family → basis aggregation.

| Basis | N | Cells | `DO_NOT_COMPRESS` | Median 2q reduction | Median depth reduction |
|---|---:|---:|---:|---:|---:|
| Walsh | 8 | 60 | 15 | 0% | 10% |
| Walsh | 16 | 60 | 10 | 29% | 33% |
| Walsh | 32 | 60 | 4 | 75% | 73% |
| Walsh | 64 | 60 | 6 | 94% | 92% |
| Fourier | 8 | 60 | 18 | 4% | 6% |
| Fourier | 16 | 60 | 2 | 32% | 32% |
| Fourier | 32 | 60 | 0 | 70% | 66% |
| Fourier | 64 | 60 | 0 | 92% | 90% |

![Family-level selector-all heatmap](assets/benchmark_family_heatmap.svg)

The family values are the preregistered family medians. Dirichlet is retained
as negative evidence rather than removed from the pooled result.

| Basis / endpoint | Gaussian | Bimodal | Exponential | Step | Dirichlet |
|---|---:|---:|---:|---:|---:|
| Walsh 2q | 47.85% | 45.27% | 93.12% | 44.56% | 0.01% |
| Walsh depth | 48.78% | 49.31% | 94.46% | 45.80% | 0.61% |
| Fourier 2q | 90.64% | 89.24% | 71.11% | 39.27% | 12.28% |
| Fourier depth | 90.42% | 88.98% | 69.82% | 37.09% | 12.76% |

## Refusal and method mix

- `425/480` cells selected compression; `55/480` (`11.46%`) returned
`DO_NOT_COMPRESS` and contributed zero gain to `selector-all`.
- The 425 compressed winners comprised 134 `amplitude_encode`, 260
`sparse_isometry`, and 31 `ds_quantum_state_preparation` selections.
- Constructor incompatibilities were preserved and filtered before selection;
they were not counted as successful candidates.

## Attribution

Attribution is descriptive over compressed cells and uses `dense_full` as the
denominator. It separates fidelity-budget truncation from the incremental effect
of preparation-strategy choice.

| Basis / resource | Truncation mean | Preparation mean | Total mean |
|---|---:|---:|---:|
| Walsh compiled 2q | -0.07% | 48.76% | 48.69% |
| Walsh compiled depth | 4.79% | 46.34% | 51.13% |
| Fourier compiled 2q | 41.46% | 16.85% | 58.31% |
| Fourier compiled depth | 41.46% | 16.54% | 57.99% |

## Claim boundary

These results support compiled-resource decisions only within the frozen
Python 3.14.2 / PyQPanda3 0.3.5 environment, the five tested families,
`N<=64`, and explicitly selected Walsh or Fourier mode. They do not establish
quantum advantage, hardware runtime acceleration, behavior beyond the tested
scope, or an automatic cross-basis selector.
Loading