diff --git a/doc/design/ext-index-skill-tools.md b/doc/design/ext-index-skill-tools.md index 2301843..a4f8b4c 100644 --- a/doc/design/ext-index-skill-tools.md +++ b/doc/design/ext-index-skill-tools.md @@ -6,7 +6,7 @@ | 日期 | 2026-11-06 | | 愿景 | [doc/next/012.md](../next/012.md)(手写真相源,本文不修改它) | | 范式长文 | [ext-skill-tools-paradigm.md](ext-skill-tools-paradigm.md)(布局、陷阱、验收清单、推广顺序) | -| 试点 | `ext/quantum/` | +| 试点 | `ext/quantum/`;[手册闭环与当前契约位置修正](ext-quantum-handbook.md) | | 相关 | [ext-abi.md](ext-abi.md) · [ext-quantum.md](ext-quantum.md) · [lib-code-as-docs.md](lib-code-as-docs.md) · [function-as-table-semantics.md](function-as-table-semantics.md) | --- @@ -26,7 +26,7 @@ | 代码 | 标记可执行;实现可薄委托 ABI / 兄弟模块 | | SKILL | `#` 下写清领域、何时用、**For AI agents → `marqdo call` 本文件** | | tools | `##` / `###` 即工具树;无旁路 schema | -| 版式 | **形参契约表紧贴标题下**;**返回契约表在体末**(返回标记前) | +| 版式 | **形参契约表紧贴标题下**;**返回契约表也在首条执行语句之前**(当前解析器只在此提取契约) | | 叙述 | 每个函数单元叙述占比 **≥ 50%**;公式与约定写进人话 | | 禁止 | `+` 清单当主表面;ABI 名罗列充文档;「内部文件免检」 | diff --git a/doc/design/ext-quantum-handbook.md b/doc/design/ext-quantum-handbook.md new file mode 100644 index 0000000..a4c08c7 --- /dev/null +++ b/doc/design/ext-quantum-handbook.md @@ -0,0 +1,71 @@ +# Quantum:从「拆分过的库」到可执行开发手册 + +| 项目 | 内容 | +|------|------| +| 日期 | 2026-11-08 | +| 使用与开发真相源 | [英文根入口](../../ext/quantum/index.mq.md) · [中文根入口](../../ext/quantum/量子/索引.mq.md) | +| 回归门禁 | [quantum_handbook.rs](../../tests/quantum_handbook.rs) | +| 思想来源 | [next/010](../next/010.md) · [next/011](../next/011.md) · [next/012](../next/012.md) | +| 本文定位 | 记录本次修正的原因与边界;日常使用无需先读本文 | + +上一轮把量子库拆成了模块树,也加入了 `call` 与叙述比例,但没有形成「只沿 index 就能使用和开发」的闭环。问题出在验收标准:目录、工具和叙述存在,并不能证明一个陌生开发者能完成实验、理解结果,再正确扩展它。 + +## 已确认的缺口 + +| 缺口 | 后果 | 本轮修正 | +|------|------|----------| +| `## For AI agents`、`## Package layout` 等说明标题 | 解析成无业务意义的真实函数,污染工具树 | 说明用自然段,标题保留给工具/对象 | +| 裸 `$qc`、缺会话或只有消费者没有生产者 | 照抄命令失效,Rust argv 测试发现不了 shell 展开 | 每页完整实验;引用和文本字面量用 shell 单引号 | +| 字符串 `kind="bitflip"` 的双引号被 shell 去掉 | CLI 拒绝未带字面量引号的文本 | 使用 `'kind="bitflip"'`,通过真实 shell 测试 | +| 默认值后紧贴英文标点,如容差后的问号 | 标点被叙述扫描器纳入默认值,number 变成 text | 标点与默认值分隔,实跑覆盖省略参数 | +| 旋转、自定义门应用、追加、矩阵导出藏在对象方法里 | 命令行只能走很窄的 Bell 演示路径 | 补齐自由工具,保留既有作者对象方法 | +| 重复「本方法返回句柄」等通用套话 | 满足比例却没有解释科学语义 | 移除旧填充,加入来源、单位、边界、预期和下一步 | +| 缺源码归属与验证方式 | AI 知道怎么调用,却不知道怎么开发 | 各模块写新增配方/原语的修改位置、镜像和既有金样 | + +## 同一个入口承担四个职责 + +使用路径是「打开根入口 → 根据科学问题选模块 → 复制完整实验 → 核对独立期望」。每个子入口也能单独冷启动,包括输入生产者、参数、结果形状、何时转到兄弟模块。 + +开发路径从最小必要变化开始:新实验组合已有工具;新酉矩阵使用 `gate.custom`;只有真实能力缺口才改原生实现。每个模块给出它负责的 Rust 文件、ABI 导出、中英镜像及应保留的测试。根入口的 `bell_analysis` 是这种开发方式的具体配方。 + +`bell_circuit` 返回可继续组合的电路;原有 `bell_phi_plus` / `贝尔态` 保留概率结果;新增 `bell_analysis` / `纠缠分析` 返回整体纯度、约化纯度、ZZ 关联和 Schmidt 数据。相同概率的经典混合不能冒充 Bell 纯态,所以不能只验证 00/11 概率。 + +工具入口继续是普通 `.mq.md` 函数。没有添加 Skill 编译器、MCP 包装、额外工具 manifest 或另一套 schema。符号与契约依靠现有解析和 `knowledge inspect`;符合 next/011 的简洁核心。 + +## 契约位置必须符合当前解析器 + +旧范式要求「返回表放在体末、返回标记前」,但 `src/parse/mod.rs::extract_function_contract` 只在首条可执行语句前提取参数与返回契约。放到 `cap.load` 之后的返回表会成为普通表,无法承担预期校验。 + +本轮以实现为准:参数表紧跟标题;返回表也位于首条执行语句之前;意图叙述仍可与后续执行步骤交错。对象构造器和方法同样补齐契约。叙述声明承载默认值,表说明类型和含义,不把 `any` 句柄伪装成新增的领域类型系统。 + +`check --narrative-ratio` 仍是最低门槛,但不再充当手册完成的唯一证据。测试同时检查每个可调用单元具有真正提取出的返回契约、参数无漂移,根符号只有三个实际实验工具。 + +## 只承诺已有能力 + +手册明确以下区别,而不把 next 的愿景写成已经实现的功能: + +- `call`、跨进程 journal 会话、双后端和稳定符号查询已有实现。 +- 状态向量默认 12 比特、硬上限 16;密度和 Schmidt 最多六比特。 +- 理想态与概率忽略教学噪声;只有 `run` 采样施噪。 +- 密度矩阵构造检查形状和厄米性,不认证半正定与归一化。 +- Schmidt 熵使用自然对数;局部纯度和关联需要结合整体态解释。 +- `draw_state` / `画态` 补上现有 qsphere、multibloch 能力;高级态图换肤仍是 Q8c 规划。 +- `call --effects plugin` 允许绘图返回 SVG,但宿主仍禁文件写入;实际落盘走作者程序的 `run`。 +- 插件 journal 重放可能重复插件效果;会话不是无副作用的永久对象仓库。 +- 智能体决定持久交互分支和复杂自我改进并非本轮实现。 + +## 验证与推广条件 + +先构建 `marqdo_plugin_quantum`,再执行: + +```bash +cargo test --locked --test quantum_handbook +cargo test --locked --test call_cli quantum_ +cargo test --locked --test gold ext_quantum -- --test-threads=1 +``` + +手册门禁直接提取双语源码中的 `sh` 围栏,经过 bash 执行原命令,逐次检查退出码与 JSON,不抄写另一份命令目录。作者程序也从 `marqdo` 围栏提取执行。两类示例都验证 Tree/Bytecode,并比较独立数学期望与中间结果;会话放在临时目录隔离。 + +组合工具另覆盖具名旋转门、矩阵导出、应用、追加和密度矩阵观察。既有 gold 继续覆盖公式、自定义门、噪声、振幅阻尼、作者方法与 SVG。 + +向其他扩展推广时,复用的是这些验证问题:陌生人能否独立启动、能否解释结果、能否找到修改归属、示例是否来自源码且持续执行。无需把 Quantum 的具体物理工具或新的模板套到每个库。 diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md index 8640c1b..f2bbd56 100644 --- a/doc/design/ext-quantum.md +++ b/doc/design/ext-quantum.md @@ -6,6 +6,7 @@ | 日期 | 2026-08-12(初版)· 2026-08-28(Q7 · Q8 viz) | | 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [ext-web.md](ext-web.md) · [view.md](view.md) · [stdlib-i18n.md](stdlib-i18n.md) · [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) | | 安装(目标) | `marqdo ext add quantum`(中英:`quantum` / `量子`) | +| 当前手册 | [根入口](../../ext/quantum/index.mq.md) · [中文入口](../../ext/quantum/量子/索引.mq.md) · [2026-11-08 优化记录](ext-quantum-handbook.md) | | 本文目的 | 锁定**作者面**、**模拟语义**、**view 可视化**与**分期**;指导 ABI 插件实现 | --- diff --git a/doc/design/ext-skill-tools-paradigm.md b/doc/design/ext-skill-tools-paradigm.md index 103b855..eae482e 100644 --- a/doc/design/ext-skill-tools-paradigm.md +++ b/doc/design/ext-skill-tools-paradigm.md @@ -88,7 +88,7 @@ ext/quantum/ |----|------| | 开篇叙述 | 领域是什么、何时打开本文件 | | For AI agents / 给智能体 | 可照抄的 `marqdo call`;缺能力时 **写明下一步打开哪个兄弟模块**(例如 circuit 造线后概率在 simulate) | -| `##` 工具 | 形参契约表紧贴标题下;返回契约表在返回标记前;叙述 ≥ 50% | +| `##` 工具 | 形参契约表紧贴标题下;返回契约表也在首条执行语句前(当前解析器边界);叙述 ≥ 50% | | `#` 对象(可选) | 作者链式 API;加载插件走 facade(如 `cap.load` / `能力.加载`),禁止作者面 `host_*` | 薄实现:工具体调用 ABI(`*> quantum_…*`)或转发兄弟模块即可,真相在叙述与契约表。 @@ -177,6 +177,8 @@ MARQDO_EXT_SOURCE=/path/to/repo/ext \ --- +Quantum 的完整实验、开发路线与源码示例门禁,见 [2026-11-08 手册修正](ext-quantum-handbook.md)。叙述比例是最低门槛,不能替代照抄执行与独立期望验证。 + ## 11. 开发验收清单 新扩展或把旧包迁到本范式时,逐项打勾: diff --git a/doc/roadmap/ext-quantum.md b/doc/roadmap/ext-quantum.md index f09c1d4..4510fbe 100644 --- a/doc/roadmap/ext-quantum.md +++ b/doc/roadmap/ext-quantum.md @@ -3,7 +3,7 @@ | | | |---|---| | 状态 | **Q0–Q7 完结 · Q8a/Q8b 完结 · Q8c 待做** | -| 日期 | 2026-08-28 | +| 日期 | 2026-08-28 · 2026-11-08 手册闭环 | | **锁定设计** | [design/ext-quantum.md](../design/ext-quantum.md) | | 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-math.md](../design/stdlib-math.md) · [view.md](../design/view.md) | | 安装 | `marqdo ext add quantum`(`quantum` / `量子`) | @@ -41,6 +41,8 @@ --- +2026-11-08:双语 index 已补完整实验、开发路线与真实契约;新增手册源示例的双后端测试。使用与开发从[根入口](../../ext/quantum/index.mq.md)开始,修改动机见[手册优化记录](../design/ext-quantum-handbook.md)。 + ## 3. 已收敛的原开放点 | 原疑问 | 锁定结论(见设计文) | @@ -48,7 +50,7 @@ | 并进 math? | **否**,独立 `ext/quantum` | | 电路表 | **要做**(Q3),与方法链等价 | | view 图 | 自绘 SVG;优先 `host_query("record_plot")`;不依赖 web | -| 自由函数面 | **不**与对象面并行 | +| 自由函数面 | 普通函数供 `call`,对象方法保留作者链;共用既有 ABI,见[手册修正](../design/ext-quantum-handbook.md) | --- diff --git a/ext/quantum/_capability/index.mq.md b/ext/quantum/_capability/index.mq.md index bb45a1d..19d883d 100644 --- a/ext/quantum/_capability/index.mq.md +++ b/ext/quantum/_capability/index.mq.md @@ -8,22 +8,25 @@ import: sys: lib/sys.mq.md --- -Capability +Native capability — diagnose plugin discovery, then return to a domain module. -This file is still a skill and a tool surface. It exists so the quantum package -can load the native ABI plugin once. Everyday author programs and agents should -call domain modules which invoke load for you. Reach for this page when checking -whether the plugin is installed, not when building a Bell state. +This boundary locates and loads the ABI v2 quantum library. Domain tools call +load themselves, so normal experiments do not need a separate setup call. +The Chinese capability file is an equivalent language facade of this boundary. -## For AI agents +```sh +marqdo call ext/quantum/_capability/index.mq.md load --effects plugin --json +``` -If you were given only this file, use it only to check the plugin. Day-to-day work -should call circuit or simulate modules instead. +Success returns null. Missing native libraries cause a nonzero exit with an +installation hint; this helper uses sys.exit, so callers must also inspect +process status instead of assuming every failure is a JSON envelope. Install +with marqdo ext add quantum, or build marqdo_plugin_quantum in the source repo. +MARQDO_QUANTUM_PLUGIN may point to a specific shared library for development. -Call example (plain text): - marqdo call ext/quantum/_capability/index.mq.md load --effects plugin --json - -*None* +Only this boundary imports lib/plugin. Do not add plugin loaders or host_* +operations to domain code. If discovery changes, validate both language roots +and tests/call_cli.rs before returning to [circuit](../circuit/index.mq.md). ## load diff --git a/ext/quantum/circuit/index.mq.md b/ext/quantum/circuit/index.mq.md index d24dd4a..cd6fd33 100644 --- a/ext/quantum/circuit/index.mq.md +++ b/ext/quantum/circuit/index.mq.md @@ -8,56 +8,65 @@ import: density: ext/quantum/density/index.mq.md --- -Circuit +Circuit building — start here when you need a reusable quantum program. -A circuit is an ordered list of gates on n wires, starting from the all-zero -ket. You can build it with method-style steps with author method chains on this file, or -call the tools here. A steps table is a readable program. Measurement rows mark -which bits simulate.run should report; they do not collapse the ideal state -vector used by probabilities. +A circuit begins in the all-zero state. Gates return a new circuit value; save +that return value to continue. Qubit zero is the rightmost basis bit. Gate +angles use radians. Width is 1–12 by default; MARQDO_QUANTUM_MAX_QUBITS can raise +or lower the limit, with a hard maximum of 16. State-vector memory grows as 2^n. -## For AI agents -If you were given only this file, you still know how to run it. Every ## heading -below is a tool. Execute with the shell. Always include --effects plugin. +Read → execute → observe -Create a two-qubit circuit and save it as qc: +This complete shell recipe creates a Bell pair and observes it through the +[simulation module](../simulate/index.mq.md). The two nonzero probabilities +should each be 0.5 within floating-point tolerance. Single quotes preserve the +session reference for Marqdo instead of letting the shell expand it. -Call example (plain text): - marqdo call ext/quantum/circuit/index.mq.md new qubits=2 --effects plugin --session s --toget qc --json +```sh +marqdo call ext/quantum/circuit/index.mq.md new qubits=2 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/circuit/index.mq.md hadamard 'circuit=$qc' qubit=0 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/circuit/index.mq.md cnot 'circuit=$qc' control=0 target=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$qc' --effects plugin --session handbook --json +``` -Apply Hadamard on qubit 0: +Which operation belongs here? -Call example (plain text): - marqdo call ext/quantum/circuit/index.mq.md hadamard circuit=$qc qubit=0 --effects plugin --session s --toget qc --json +Wires or a declarative steps table: use new; then simulate for results. -Apply CNOT from 0 to 1: +Superposition or basis/phase gates: use hadamard, x, y, z, s, t, i; then simulate.probabilities. -Call example (plain text): - marqdo call ext/quantum/circuit/index.mq.md cnot circuit=$qc control=0 target=1 --effects plugin --session s --toget qc --json +Continuous control: use rx, ry, rz; then theta is in radians. -If you were given only this file, probabilities are not a ## tool here. After the -CNOT line, call simulate on the same session (do not invent a probabilities -tool on this file): +Entangle or route: use cnot, cz, swap; then state.schmidt. -Call example (plain text): - marqdo call ext/quantum/simulate/index.mq.md probabilities circuit=$qc --effects plugin --session s --json +Compose fragments or custom gates: use append, apply; then gate.custom or gate.named supplies a gate. -Author programs may import this file and construct the circuit object named -circuit (method chain h, cx, …). Agents should prefer marqdo call on the ## -tools above, then simulate for amplitudes or probabilities. +Mark teaching layers or readout: use barrier, measure_mark; then viz.draw_circuit or simulate.run. -*None* +The author object circuit below offers the same operations as methods. Its +simulation, density and drawing methods remain conveniences; their full call +contracts live in the corresponding modules. Do not pass an object method to +call without an explicit receiver; use the free tools above the object. + +Development route + +A new circuit recipe belongs in the [root index](../index.mq.md), composed from +these tools. Add a native gate only when composition and gate.custom cannot +express it: update plugins/quantum/src/sim.rs and src/lib.rs, then add the free +tool and author method here and in the Chinese mirror. Validate both backends +and the existing tests/ext/quantum-steps-smoke.mq.md author example. ## new -Create a state-vector circuit of width `qubits`=1 by default. Optional -`steps`=None means no preloaded gates; when a table is provided it is parsed -like the author API. | 参数 | 类型 | 说明 | |------|------|------| | qubits | number | wire count | | steps | any | optional gate table or None | +Create a state-vector circuit of width `qubits`=1 by default. Optional +`steps`=None means no preloaded gates; when a table is provided it is parsed +like the author API. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | new circuit handle | @@ -66,14 +75,15 @@ like the author API. *> quantum_circuit_new qubits=`qubits` steps=`steps`* ## hadamard -Apply Hadamard on wire `qubit`=0 of an existing `circuit` by default. Prefer -this when an agent already holds a circuit from new or toget. | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | existing circuit | | qubit | number | target wire | +Apply Hadamard on wire `qubit`=0 of an existing `circuit` by default. Prefer +this when an agent already holds a circuit from new or toget. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | updated circuit | @@ -82,8 +92,6 @@ this when an agent already holds a circuit from new or toget. *> quantum_h circuit=`circuit` qubit=`qubit`* ## cnot -Controlled-NOT on `circuit` from `control`=0 to `target`=1 by default. Together -with hadamard this prepares a Bell pair on two wires. | 参数 | 类型 | 说明 | |------|------|------| @@ -91,6 +99,9 @@ with hadamard this prepares a Bell pair on two wires. | control | number | control wire | | target | number | target wire | +Controlled-NOT on `circuit` from `control`=0 to `target`=1 by default. Together +with hadamard this prepares a Bell pair on two wires. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | updated circuit | @@ -99,13 +110,14 @@ with hadamard this prepares a Bell pair on two wires. *> quantum_cx circuit=`circuit` control=`control` target=`target`* ## barrier -Insert a visual barrier on `circuit`. The state does not change; drawings show a -separator so lectures can mark logical layers. | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | existing circuit | +Insert a visual barrier on `circuit`. The state does not change; drawings show a +separator so lectures can mark logical layers. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | circuit with barrier recorded | @@ -114,15 +126,16 @@ separator so lectures can mark logical layers. *> quantum_barrier circuit=`circuit`* ## measure_mark -Mark computational-basis readout on `circuit` for later simulate.run. This does -not collapse the ideal state used by probabilities. Pass `qubits`=None to mark -every wire. | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | existing circuit | | qubits | any | wire list or None for all | +Mark computational-basis readout on `circuit` for later simulate.run. This does +not collapse the ideal state used by probabilities. Pass `qubits`=None to mark +every wire. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | circuit with measure markers | @@ -130,9 +143,284 @@ every wire. > cap.load *> quantum_measure circuit=`circuit` qubits=`qubits`* +## x + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0 (input). + +Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_x circuit=`circuit` qubit=`qubit`* + +## y + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0 (input). + +Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_y circuit=`circuit` qubit=`qubit`* + +## z + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0 (input). + +Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_z circuit=`circuit` qubit=`qubit`* + +## s + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0 (input). + +Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_s circuit=`circuit` qubit=`qubit`* + +## t + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0 (input). + +Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_t circuit=`circuit` qubit=`qubit`* + +## i + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0 (input). + +Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_i circuit=`circuit` qubit=`qubit`* + +## rx + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 | +| theta | number | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0, `theta` (input). + +Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_rx circuit=`circuit` qubit=`qubit` theta=`theta`* + +## ry + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 | +| theta | number | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0, `theta` (input). + +Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_ry circuit=`circuit` qubit=`qubit` theta=`theta`* + +## rz + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| qubit | number | Default 0 | +| theta | number | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `qubit`=0, `theta` (input). + +Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_rz circuit=`circuit` qubit=`qubit` theta=`theta`* + +## cz + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| control | number | Default 0 | +| target | number | Default 1 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `control`=0, `target`=1 (input). + +Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_cz circuit=`circuit` control=`control` target=`target`* + +## swap + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| a | number | Default 0 | +| b | number | Default 1 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `a`=0, `b`=1 (input). + +Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_swap circuit=`circuit` a=`a` b=`b`* + +## append + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| op | any | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `op` (input). + +Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_append circuit=`circuit` op=`op`* + +## apply + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Existing circuit; returns a new value | +| gate | any | Required | +| qubits | any | Default 0 (input) | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Updated circuit | + +Inputs: `gate`, `qubits`=0 (input). + +Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. + +Input `circuit` is preserved; save the returned value with --toget qc in the same session to continue. + +> cap.load +*> quantum_apply circuit=`circuit` gate=`gate` qubits=`qubits`* + # circuit - + `qubits`=1 - + `steps`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubits | number | Default 1 | +| steps | any | Default None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubits`=1, `steps`=None (input). State-vector circuit on n wires (default all-zero ket). Optional steps= preloads a gate table. Methods append gates and return a fresh handle for chaining. Agents should prefer the ## call tools above; authors use this object for readable method chains in programs. @@ -140,97 +428,214 @@ State-vector circuit on n wires (default all-zero ket). Optional steps= preloads *> quantum_circuit_new qubits=`qubits` steps=`steps`* ## h - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply the Hadamard gate on the chosen wire. This creates equal superposition from computational basis states and is the first step of Bell and GHZ recipes. Returns an updated circuit handle so authors can chain without in-place mutation. *> quantum_h circuit=`self` qubit=`qubit`* ## x - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. *> quantum_x circuit=`self` qubit=`qubit`* ## y - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. *> quantum_y circuit=`self` qubit=`qubit`* ## z - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. *> quantum_z circuit=`self` qubit=`qubit`* ## s - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. *> quantum_s circuit=`self` qubit=`qubit`* ## t - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. *> quantum_t circuit=`self` qubit=`qubit`* ## i - + `qubit`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0 (input). Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. *> quantum_i circuit=`self` qubit=`qubit`* ## rx - + `qubit`=0 - + `theta` + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | +| theta | number | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0, `theta` (input). Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. *> quantum_rx circuit=`self` qubit=`qubit` theta=`theta`* ## ry - + `qubit`=0 - + `theta` + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | +| theta | number | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0, `theta` (input). Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. *> quantum_ry circuit=`self` qubit=`qubit` theta=`theta`* ## rz - + `qubit`=0 - + `theta` + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | Default 0 | +| theta | number | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubit`=0, `theta` (input). Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. *> quantum_rz circuit=`self` qubit=`qubit` theta=`theta`* ## cx - + `control`=0 - + `target`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| control | number | Default 0 | +| target | number | Default 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `control`=0, `target`=1 (input). Apply CNOT from control to target. This is the standard entangling step in Bell and GHZ preparations. Returns the updated circuit handle for chaining. *> quantum_cx circuit=`self` control=`control` target=`target`* ## cz - + `control`=0 - + `target`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| control | number | Default 0 | +| target | number | Default 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `control`=0, `target`=1 (input). Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. *> quantum_cz circuit=`self` control=`control` target=`target`* ## swap - + `a`=0 - + `b`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| a | number | Default 0 | +| b | number | Default 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `a`=0, `b`=1 (input). Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. @@ -238,35 +643,75 @@ Exchange the two wires named by a and b. Useful when routing logical qubits in a ## barrier +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + Record a visual barrier only. The ideal state vector is unchanged; use barriers to separate lecture stages when drawing circuit rails. *> quantum_barrier circuit=`self`* ## measure - + `qubits`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubits | any | Default None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `qubits`=None (input). Mark computational-basis readout wires for later run sampling. This does not collapse the ideal state used by probabilities. Pass qubits=None to mark every wire. *> quantum_measure circuit=`self` qubits=`qubits`* ## append - + `op` + +| 参数 | 类型 | 说明 | +|------|------|------| +| op | any | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `op` (input). Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. *> quantum_append circuit=`self` op=`op`* ## apply - + `gate` - + `qubits`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| gate | any | Required | +| qubits | any | Default 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `gate`, `qubits`=0 (input). Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. *> quantum_apply circuit=`self` gate=`gate` qubits=`qubits`* ## noise - + `kind` - + `p` + +| 参数 | 类型 | 说明 | +|------|------|------| +| kind | any | Required | +| p | any | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | New circuit value; keep it to continue | + +Inputs: `kind`, `p` (input). Attach teaching noise of the given kind and strength for run trajectories. Ideal simulate and probabilities paths ignore this channel by design. @@ -274,35 +719,65 @@ Attach teaching noise of the given kind and strength for run trajectories. Ideal ## simulate +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | List of re/im amplitudes | + Return ideal state-vector amplitudes as re/im pairs for the current circuit. Teaching noise attached to the circuit is ignored on this ideal path. *> quantum_simulate circuit=`self`* ## state +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_state: qubits, dim, amplitudes | + Return the ideal state object with the same amplitudes as simulate. Prefer this when later fidelity or density tools expect a state handle rather than raw amplitudes. *> quantum_state circuit=`self`* ## probabilities +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Basis label to ideal probability | + Map basis labels to ideal probabilities. Labels treat qubit 0 as the rightmost bit. Teaching noise is ignored so results match the pure statevector story. *> quantum_probabilities circuit=`self`* ## run - + `shots`=1024 - + `seed`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| shots | number | Default 1024 | +| seed | number | Default 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Shot metadata and counts | + +Inputs: `shots`=1024, `seed`=1 (input). Sample computational-basis shots from this circuit. Defaults are shots=1024 and seed=1 for reproducible replays. Applies teaching noise when a noise channel was attached. *> quantum_run circuit=`self` shots=`shots` seed=`seed`* ## draw - + `path`=None - + `kind`=circuit - + `qubit`=0 - + `theme`=dark + +| 参数 | 类型 | 说明 | +|------|------|------| +| path | any | Default None | +| kind | any | Default circuit | +| qubit | number | Default 0 | +| theme | any | Default dark | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg with kind and svg | + +Inputs: `path`=None, `kind`="circuit", `qubit`=0, `theme`="dark" (input). Render an SVG figure for circuit rails, probability bars, Bloch spheres, or advanced density kinds. Theme tokens are dark, light, and bw. Optional path writes the file for CLI or view embedding. @@ -310,19 +785,41 @@ Render an SVG figure for circuit rails, probability bars, Bloch spheres, or adva ## density +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Density operator handle | + Build the pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulation of this circuit. Use density-module tools for mixed states and partial traces. *> quantum_density_from_state state=`self`* ## expect - + `obs` + +| 参数 | 类型 | 说明 | +|------|------|------| +| obs | any | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Scalar observation | + +Inputs: `obs` (input). Compute the expectation value of a Pauli string (left end = high bit) or an explicit matrix on this circuit’s ideal density. Teaching noise is ignored. *> quantum_density_expect density=`self` obs=`obs`* ## schmidt - + `cut`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| cut | number | Default 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Coefficients, subsystem bases and entropy | + +Inputs: `cut`=1 (input). Perform a bipartite Schmidt decomposition of the ideal state. The cut argument is the number of qubits in subsystem A counted from the low bits. diff --git a/ext/quantum/density/index.mq.md b/ext/quantum/density/index.mq.md index fb7f115..f1a816b 100644 --- a/ext/quantum/density/index.mq.md +++ b/ext/quantum/density/index.mq.md @@ -7,32 +7,53 @@ import: cap: ext/quantum/_capability/index.mq.md --- -Density +Density operators — inspect a subsystem or a mixed-state matrix. -A density operator describes pure and mixed states together. Pure states have -purity one; mixing lowers purity. Build rho from a circuit or state, or from an -explicit Hermitian matrix. Partial trace discards subsystems. Expectation values -take Pauli strings or matrices. +Build rho from an ideal circuit/state with from_state, or from a square +Hermitian 2^n matrix with from_matrix. Density operations and Schmidt support +at most six qubits. The matrix constructor checks shape and Hermiticity; it +does not certify positive semidefiniteness or trace one. For physical inputs, +check the trace and eig eigenvalues yourself before interpreting purity. -## For AI agents -If you were given only this file, build or inspect density operators with marqdo -call and --effects plugin. +An independent mixed-state check -Call example (plain text): - marqdo call ext/quantum/density/index.mq.md from_state state=$qc --effects plugin --toget rho --json - marqdo call ext/quantum/density/index.mq.md purity density=$rho --effects plugin --json +This one-qubit maximally mixed matrix has trace one, purity 0.5 and Z +expectation zero. The complete example needs no prior circuit or saved handle. +For entanglement, start from a Bell circuit, call from_state, then partial_trace +with keep=[0]; purity of that reduced density is also 0.5. -Author programs may use the density object on this file. +```sh +marqdo call ext/quantum/density/index.mq.md from_matrix 'matrix=[[0.5,0],[0,0.5]]' --effects plugin --session handbook --toget rho --json +marqdo call ext/quantum/density/index.mq.md purity 'density=$rho' --effects plugin --session handbook --json +marqdo call ext/quantum/density/index.mq.md expect 'density=$rho' 'obs="Z"' --effects plugin --session handbook --json +marqdo call ext/quantum/density/index.mq.md eig 'density=$rho' --effects plugin --session handbook --json +``` + +partial_trace keeps the listed zero-based wires and discards the others. +Pauli strings put the highest bit on the left; ZZ measures correlation on two +wires. matrix exports nested complex entries, and eig returns eigenvalues and +eigenvectors. Use [viz.draw_density](../viz/index.mq.md) for hinton, city, +density or paulivec plots. from_state ignores attached teaching noise, just +like the ideal simulator; it is not a noisy density evolution engine. + +Development route + +Add mixed-state mathematics to plugins/quantum/src/linalg.rs, export it through +src/lib.rs and update this file plus its Chinese mirror. Keep physical input +validation claims aligned with the constructor. Validate pure-state purity +one, Bell reduced purity one-half and observable expectations against +independent matrices in tests/ext/quantum-linalg-smoke.mq.md. ## from_state -Form rho as the outer product of a pure `state` (or the ideal state of a -circuit). Use this when you trust the pure-state picture and want mixed-state -tools without writing a matrix by hand. | 参数 | 类型 | 说明 | |------|------|------| | state | any | pure state or circuit | +Form rho as the outer product of a pure `state` (or the ideal state of a +circuit). Use this when you trust the pure-state picture and want mixed-state +tools without writing a matrix by hand. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | density handle | @@ -41,14 +62,15 @@ tools without writing a matrix by hand. *> quantum_density_from_state state=`state`* ## from_matrix -Build rho from an explicit Hermitian `matrix`. Pair with formula blocks in the -lecture so the matrix on the page is the matrix in the simulator. Size is -limited by the plugin. | 参数 | 类型 | 说明 | |------|------|------| | matrix | any | Hermitian matrix | +Build rho from an explicit Hermitian `matrix`. Pair with formula blocks in the +lecture so the matrix on the page is the matrix in the simulator. Size is +limited by the plugin. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | density handle | @@ -57,13 +79,14 @@ limited by the plugin. *> quantum_density_from_matrix matrix=`matrix`* ## purity -Compute the trace of rho squared for `density`. Values near one mean nearly -pure; lower values mean classical mixing or traced-out entanglement. | 参数 | 类型 | 说明 | |------|------|------| | density | any | density operator | +Compute the trace of rho squared for `density`. Values near one mean nearly +pure; lower values mean classical mixing or traced-out entanglement. + | 返回 | 类型 | 说明 | |------|------|------| | result | number | purity | @@ -72,15 +95,16 @@ pure; lower values mean classical mixing or traced-out entanglement. *> quantum_density_purity density=`density`* ## partial_trace -Keep listed qubits in `keep` and trace out the rest of `density`. Indices use -LSB equals zero. The result is generally mixed even when the joint state was -pure. | 参数 | 类型 | 说明 | |------|------|------| | density | any | joint density | | keep | any | qubit index list to keep | +Keep listed qubits in `keep` and trace out the rest of `density`. Indices use +LSB equals zero. The result is generally mixed even when the joint state was +pure. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | reduced density | @@ -89,14 +113,15 @@ pure. *> quantum_density_partial_trace density=`density` keep=`keep`* ## expect -Expectation of observable `obs` on `density`. Pauli strings use left equals -high bit. Pass a matrix when the observable is not a Pauli product. | 参数 | 类型 | 说明 | |------|------|------| | density | any | density operator | | obs | any | Pauli string or matrix | +Expectation of observable `obs` on `density`. Pauli strings use left equals +high bit. Pass a matrix when the observable is not a Pauli product. + | 返回 | 类型 | 说明 | |------|------|------| | result | number | expectation value | @@ -105,13 +130,14 @@ high bit. Pass a matrix when the observable is not a Pauli product. *> quantum_density_expect density=`density` obs=`obs`* ## eig -Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a -lecture needs the eigenbasis of rho. | 参数 | 类型 | 说明 | |------|------|------| | density | any | Hermitian density | +Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a +lecture needs the eigenbasis of rho. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | eigenvalues and eigenvectors | @@ -119,9 +145,35 @@ lecture needs the eigenbasis of rho. > cap.load *> quantum_density_eig density=`density`* +## matrix + +| 参数 | 类型 | 说明 | +|------|------|------| +| density | any | Density handle / 密度句柄 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Nested complex entries with re and im | + +Export the explicit nested complex matrix of `density`. Reading entries does not +change the density operator. Use the exported entries for an independent trace +check or further linear algebra; the caller remains responsible for physicality. + +> cap.load +*> quantum_density_matrix density=`density`* + # density - + `state`=None - + `matrix`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| state | any | Default None | +| matrix | any | Default None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Returned value | + +Inputs: `state`=None, `matrix`=None (input). Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=. Density operations support at most six qubits. Pure and mixed states share this object surface for purity, partial trace, and expectation. @@ -133,18 +185,35 @@ Construct a density operator from a pure state or circuit (state=) or from an ex ## matrix +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Nested complex entries with re and im | + Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package. *> quantum_density_matrix density=`self`* ## purity +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Scalar observation | + Compute Tr(ρ²). Values near one mean a pure state; mixed states are strictly less than one. Use this as a quick entanglement or decoherence check after a partial trace. *> quantum_density_purity density=`self`* ## partial_trace - + `keep` + +| 参数 | 类型 | 说明 | +|------|------|------| +| keep | any | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Density operator handle | + +Inputs: `keep` (input). Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks. @@ -152,20 +221,42 @@ Trace out every qubit except those listed in keep (LSB index 0). Returns the red ## eig +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | eigenvalues and eigenvectors | + Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors. Handy for lecture plots and for verifying that a constructed rho is physical. *> quantum_density_eig density=`self`* ## expect - + `obs` + +| 参数 | 类型 | 说明 | +|------|------|------| +| obs | any | Required | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | Scalar observation | + +Inputs: `obs` (input). Expectation value of observable obs on this density. obs may be a Pauli string with the left end as the high bit, or an explicit matrix matching the density dimension. *> quantum_density_expect density=`self` obs=`obs`* ## draw - + `path`=None - + `kind`=hinton + +| 参数 | 类型 | 说明 | +|------|------|------| +| path | any | Default None | +| kind | any | Default hinton | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg with kind and svg | + +Inputs: `path`=None, `kind`="hinton" (input). Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density. Optional path writes SVG; kind selects which visual metaphor the lecture uses. diff --git a/ext/quantum/gate/index.mq.md b/ext/quantum/gate/index.mq.md index 5991a77..019fa43 100644 --- a/ext/quantum/gate/index.mq.md +++ b/ext/quantum/gate/index.mq.md @@ -7,25 +7,44 @@ import: cap: ext/quantum/_capability/index.mq.md --- -Gate +Gates — define the operator before choosing the wires it acts on. -A gate is a unitary on one or more qubits. This skill writes the matrix in -lecture form, then builds a gate handle. Circuits apply gates; this page defines -what they are. Custom unitaries use the same path with a matrix argument from a -formula block or nested list. +Use named for I, X, Y, Z, H, S, T, Rx, Ry, Rz, CX, CZ or SWAP. Rotations +require theta in radians. A custom gate is a square 2^k matrix satisfying +U†U = I (construction tolerance 1e-6). Cells may be real numbers or maps with +re and im fields. JSON and a bound Markdown formula reach the same constructor. -## For AI agents -If you were given only this file, run tools with marqdo call and --effects plugin. -FUNCTION is the ## name. Example Hadamard gate handle: +A complete custom-gate experiment -Call example (plain text): - marqdo call ext/quantum/gate/index.mq.md hadamard --effects plugin --json +The matrix below swaps zero and one. matches must return true, and the final +probabilities must put all weight on basis one. This uses the +[circuit module](../circuit/index.mq.md) to apply the operator; constructing a +gate alone never changes a circuit. All references belong to the same session. -Custom unitary: pass matrix= as JSON or a prior toget. matches checks a gate -against a matrix. Author programs may also use the gate object constructor on -this file. +```sh +marqdo call ext/quantum/gate/index.mq.md custom 'matrix=[[0,1],[1,0]]' 'name="X-demo"' --effects plugin --session handbook --toget u --json +marqdo call ext/quantum/gate/index.mq.md matches 'gate=$u' 'matrix=[[0,1],[1,0]]' --effects plugin --session handbook --json +marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/circuit/index.mq.md apply 'circuit=$qc' 'gate=$u' qubits=0 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$qc' --effects plugin --session handbook --json +``` + +Choose hadamard, pauli_x, pauli_z or cnot for a familiar constant; named covers +the other built-ins, custom accepts a formula matrix, matrix exports entries, +and matches checks that the explanation agrees with the implemented operator. +Use [viz.draw_gate](../viz/index.mq.md) for a glyph or matrix heatmap. Prefer +circuit.cnot with explicit control and target for an entangling operation. + +Development route + +For a new user-defined unitary, use custom and an independent expected matrix; +no Rust or ABI change is necessary. For a new built-in, update +plugins/quantum/src/sim.rs::named_gate_matrix and its numerical tests before +exposing it here and in the Chinese mirror. Preserve tests/ext/quantum-custom-gate-smoke.mq.md, +which binds the Hadamard formula directly into the author gate constructor. ## hadamard + The Hadamard gate creates equal superposition from computational basis states. Its matrix in the computational basis is one over square-root two times the matrix with ones on the first row and one then minus one on the second row. @@ -42,6 +61,7 @@ This tool takes no parameters. *> quantum_gate_new name="H" theta=None matrix=None* ## pauli_x + Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and ket-one. Use it when a lecture needs an explicit NOT on the computational basis. @@ -55,6 +75,7 @@ This tool takes no parameters. *> quantum_gate_new name="X" theta=None matrix=None* ## pauli_z + Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone. Its diagonal matrix is the standard computational-basis Z. @@ -68,6 +89,7 @@ This tool takes no parameters. *> quantum_gate_new name="Z" theta=None matrix=None* ## cnot + The controlled-NOT on two qubits flips the target when the control is ket-one. Wire order and bit-endianness follow the package convention where qubit 0 is the rightmost label bit. Prefer applying via circuit tools with explicit control and @@ -83,15 +105,16 @@ This tool takes no parameters. *> quantum_gate_new name="CX" theta=None matrix=None* ## custom -Build a gate from an explicit unitary given as `matrix`. Authors usually bind a -formula matrix first, then pass that binding. Optional label `name`="U" marks -drawings when the caller omits a name. | 参数 | 类型 | 说明 | |------|------|------| | matrix | any | unitary matrix formula or list | | name | text | optional label defaulting to U | +Build a gate from an explicit unitary given as `matrix`. Authors usually bind a +formula matrix first, then pass that binding. Optional label `name`="U" marks +drawings when the caller omits a name. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | custom gate handle | @@ -100,9 +123,6 @@ drawings when the caller omits a name. *> quantum_gate_new name=`name` theta=None matrix=`matrix`* ## matches -Teaching check: does `gate` match expected `matrix` within absolute tolerance -`tol`=0.000000001? Use after defining a formula so the lecture and the simulator -cannot drift apart. | 参数 | 类型 | 说明 | |------|------|------| @@ -110,6 +130,10 @@ cannot drift apart. | matrix | any | expected unitary | | tol | number | absolute tolerance | +Teaching check: does `gate` match expected `matrix` within absolute tolerance +`tol`=0.000000001 ? Use after defining a formula so the lecture and the simulator +cannot drift apart. + | 返回 | 类型 | 说明 | |------|------|------| | result | bool | True when matrices match | @@ -117,10 +141,54 @@ cannot drift apart. > cap.load *> quantum_gate_matches_matrix gate=`gate` matrix=`matrix` tol=`tol`* +## named + +| 参数 | 类型 | 说明 | +|------|------|------| +| name | text | Built-in gate name | +| theta | any | Rotation angle or None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Gate handle for circuit.apply | + +Construct built-in `name`="H" with optional `theta`=None . Rx, Ry and Rz require +a numeric angle in radians. The returned gate can be passed to circuit.apply; +creating it never changes a circuit. Supported names are listed above. + +> cap.load +*> quantum_gate_new name=`name` theta=`theta` matrix=None* + +## matrix + +| 参数 | 类型 | 说明 | +|------|------|------| +| gate | any | Gate handle | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Nested complex entries with re and im | + +Export the explicit unitary of `gate`. Each complex entry has re and im fields. +Use this to compare a formula with independent expected entries. Reading a gate +matrix neither modifies its handle nor applies the operator to any circuit. + +> cap.load +*> quantum_gate_matrix gate=`gate`* + # gate - + `name`=None - + `theta`=None - + `matrix`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| name | any | Default None | +| theta | number | Default None | +| matrix | any | Default None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Gate handle for circuit.apply | + +Inputs: `name`=None, `theta`=None, `matrix`=None (input). Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence). Custom gates may set name= (default U). Authors and call-style tools share this object surface. @@ -129,21 +197,43 @@ Named built-in gate (name=H) or a custom unitary defined by matrix= (nested list ## matrix +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Nested complex entries with re and im | + Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula. *> quantum_gate_matrix gate=`self`* ## matches_matrix - + `matrix` - + `tol`=0.000000001 + +| 参数 | 类型 | 说明 | +|------|------|------| +| matrix | any | Required | +| tol | any | Default 0.000000001 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | bool | Match within absolute tolerance | + +Inputs: `matrix`, `tol`=0.000000001 (input). Check whether this gate matches the given matrix within absolute tolerance tol. Typical after building a custom gate from a Markdown formula fence in a lecture notebook. *> quantum_gate_matches_matrix gate=`self` matrix=`matrix` tol=`tol`* ## draw - + `path`=None - + `kind`=gate + +| 参数 | 类型 | 说明 | +|------|------|------| +| path | any | Default None | +| kind | any | Default gate | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg with kind and svg | + +Inputs: `path`=None, `kind`="gate" (input). Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix). Optional path writes SVG to disk; plots also enter view/CLI through record_plot for the session. diff --git a/ext/quantum/index.mq.md b/ext/quantum/index.mq.md index 910ba4c..1bb84b8 100644 --- a/ext/quantum/index.mq.md +++ b/ext/quantum/index.mq.md @@ -1,193 +1,289 @@ --- markup: occlusion title: ext/quantum -description: >- - Quantum package root skill. Read this file first. Every tool runs with marqdo call. +description: Executable quantum handbook and experiment tools. import: state: ext/quantum/state/index.mq.md - gate: ext/quantum/gate/index.mq.md circuit: ext/quantum/circuit/index.mq.md simulate: ext/quantum/simulate/index.mq.md density: ext/quantum/density/index.mq.md - viz: ext/quantum/viz/index.mq.md --- -This file is the root skill for the Marqdo quantum package. If you are an AI -agent (or any program) with no other Marqdo context, follow Choose a path, then -How to execute any tool. Do not invent MCP tools, Python wrappers, or a second -API. The Markdown ## headings in these files are the tools. +Quantum handbook — read this index, execute an experiment, then open only the +module responsible for the next question. This is the package's actual program +and developer guide. The callable headings below are the tools; the surrounding +prose explains how and why to use them. No separate skill manifest is required. -## Choose a path +Start with a verifiable result -Pick one row. Do not mix English and Chinese tool names or file trees. (Do not -write Marqdo branch lines here; this table is narration only.) +These commands are independent and need no session. The Bell probabilities have +00 and 11 near 0.5. bell_analysis adds ZZ correlation near one, reduced purity +near one-half and Schmidt entropy near ln(2). Compare numbers within 1e-9, +rather than comparing a floating-point JSON string with literal 0.5. -| If you need | Do this | -|-------------|---------| -| Only a Bell result | Run `bell_phi_plus` on this file (command in the next section). Stop. | -| Circuit handles to continue (draw, noise, more gates) | Copy the stepwise circuit then simulate calls under circuit module below. Keep one `--session` and `--toget qc`. | -| Chinese tool names | Open `ext/quantum/量子/索引.mq.md` instead and stay in that tree. | +```sh +marqdo call ext/quantum/index.mq.md bell_phi_plus --effects plugin --json +marqdo call ext/quantum/index.mq.md bell_analysis --effects plugin --json +``` -English paths stay under `ext/quantum/` (this tree). Agents should use `##` -tools via `marqdo call`. The `# circuit` / `# gate` objects on module files are -for author programs that import the module, not the default agent path. +Choose the next question -*None* +For a circuit to continue editing, call bell_circuit on this file and save its +return with --session and --toget. For a different initial program open +[circuit](circuit/index.mq.md): new, x/y/z/s/t/i, hadamard, rx/ry/rz, cnot/cz/swap, +apply, append, barrier and measure_mark cover construction and composition. -## How to execute any tool +For a named or formula-defined operator open [gate](gate/index.mq.md). It +constructs gates and exposes matrix comparison. For exact amplitudes, states, +probabilities or noisy shots open [simulate](simulate/index.mq.md). -Marqdo runs one function from a Markdown file with this shell command shape. -Copy it literally. Replace FILE, FUNCTION, and arguments. +For tensor products, fidelity and Schmidt cuts open [state](state/index.mq.md). +For mixed matrices, partial trace, expectations and spectra open +[density](density/index.mq.md). For SVG rails, probabilities, Bloch, qsphere, multibloch, matrix and +density figures open [viz](viz/index.mq.md). Each module starts with a complete +experiment, input/output conventions and a concrete development route. -Call example (plain text): - marqdo call FILE FUNCTION name=value name=value --effects plugin --json +Use [the Chinese index](量子/索引.mq.md) for Chinese tool and parameter names. +The two trees share one native plugin and are tested against the same numerical +expectations. [_capability](_capability/index.mq.md) is the plugin diagnostic +boundary, not a prerequisite for every experiment. -FILE is always a path under ext/quantum/, usually ending in index.mq.md. -FUNCTION is the exact ## heading name in that file (for example new, hadamard, -probabilities). Nested ### headings use a dotted path like parent.child. -Always pass --effects plugin because the simulator is a native plugin; without -this flag marqdo call refuses the tool. Pass --json when you need the envelope -with ok and result fields. To keep a return value for the next command, add ---session some-id and --toget name (or put toget name at the end). Later -arguments may use circuit=$name. Plugin handles are rebuilt from the session -journal. Argument values may be numbers, quoted text, True, False, None, JSON -starting with [ or {, or $name session refs. Do not call ensure_plugin or any -host-star API; domain files load the plugin themselves. +Install and locate the source -Minimal first command to verify the package (no tool arguments): +These commands assume the package source tree is visible from the current +working directory. For an installed package replace the first FILE argument by +its actual installed path (by default ~/.marqdo/ext/quantum/index.mq.md). +Imports inside the package resolve through the extension search roots. -Call example (plain text): - marqdo call ext/quantum/index.mq.md bell_phi_plus --effects plugin --json +```text +marqdo ext add quantum +marqdo ext list +``` -*None* +For development in this repository, build the local native plugin first. If +several versions are installed, set MARQDO_QUANTUM_PLUGIN to the absolute path +of target/debug/libquantum.so (or the platform's library filename). Never run +ext add with MARQDO_EXT pointing at the repository ext directory: installation +and source editing are different operations. -## Package layout +```text +source scripts/dev-env.sh +cargo build --locked -p marqdo_plugin_quantum +``` -Open only the module you need. Each module file is also a complete skill and -repeats how to marqdo call its tools. +What a call means -The path ext/quantum/index.mq.md is this root map and the Bell demo tool. -The path ext/quantum/circuit/index.mq.md builds wires, applies H and CNOT, and -defines the author object circuit. -The path ext/quantum/gate/index.mq.md holds gate matrices as formulas and named -or custom gates. -The path ext/quantum/simulate/index.mq.md returns amplitudes, probabilities, and -noisy shots. -The path ext/quantum/state/index.mq.md covers kron, fidelity, and Schmidt. -The path ext/quantum/density/index.mq.md covers density operators and partial -trace. -The path ext/quantum/viz/index.mq.md draws SVG figures. -The path ext/quantum/_capability/index.mq.md only loads the plugin for diagnostics. +The command shape is marqdo call FILE FUNCTION name=value --effects plugin +--json. FUNCTION is the exact callable heading; nested tools use parent.child. +A heading on an author object that reads self is an instance method and needs +an object receiver. Use this package's free tools for command-line work; import +the very same modules when writing an author program. -Author programs import the same paths in frontmatter, then call module.member. -Example: import circuit from ext/quantum/circuit/index.mq.md, then use -circuit.circuit for the object constructor, or circuit.new for the call-style -tool that agents use with marqdo call. +Arguments accept numbers, text, True/False/None, JSON lists/maps, or session +references. Protect text literals, JSON and every dollar reference with shell single quotes: +'name="H"' preserves the text quotes for the CLI value parser; +'circuit=$qc' sends a reference to Marqdo. Unquoted circuit=$qc would let the +shell expand an unrelated environment variable first. With --json, inspect both +the process exit status and ok before reading result. A failed call is not a +valid handle, even when stdout contains an error description. -*None* +A complete persistent experiment -## circuit module +All commands below use session handbook and can be executed in order. A call +stores only its return value under --toget; apply operations preserve the old +value, so save the new circuit after each step. Reading without --toget leaves +the binding unchanged. The final result must be near 0.5: a Bell pair is pure, +but either one-qubit subsystem is maximally mixed. -File path: ext/quantum/circuit/index.mq.md +```sh +marqdo call ext/quantum/index.mq.md bell_circuit --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$qc' --effects plugin --session handbook --json +marqdo call ext/quantum/density/index.mq.md from_state 'state=$qc' --effects plugin --session handbook --toget rho --json +marqdo call ext/quantum/density/index.mq.md partial_trace 'density=$rho' 'keep=[0]' --effects plugin --session handbook --toget reduced --json +marqdo call ext/quantum/density/index.mq.md purity 'density=$reduced' --effects plugin --session handbook --json +``` -Use this when you need a quantum circuit handle. Typical agent sequence for a -two-qubit Bell preparation (copy each line as its own shell command): +Session data lives under .marqdo/call-sessions unless MARQDO_CALL_SESSION_DIR +is set. Plugin calls are journaled and replayed across processes. Keep a session +short and use a new session id after changing source or plugin versions; replay +can repeat plugin effects such as plot output. Do not reconstruct a handle by +copying an implementation-specific JSON object into a new session. -Call example (plain text): - marqdo call ext/quantum/circuit/index.mq.md new qubits=2 --effects plugin --session s1 --toget qc --json - marqdo call ext/quantum/circuit/index.mq.md hadamard circuit=$qc qubit=0 --effects plugin --session s1 --toget qc --json - marqdo call ext/quantum/circuit/index.mq.md cnot circuit=$qc control=0 target=1 --effects plugin --session s1 --toget qc --json +Scientific conventions and limits -Main ## tools on that file: new, hadamard, cnot, barrier, measure_mark. The same -file also defines the author object circuit with methods such as h and cx. +Qubit zero is the least significant, rightmost basis bit; Pauli strings put the +highest bit on the left. Angles are radians. State-vector width defaults to 12, +with an environment-adjustable hard cap of 16. Density and Schmidt stop at six +qubits. Schmidt A owns the low cut bits and entropy is in natural-log nats. -*None* +Exact simulation, probabilities, fidelity and density-from-circuit ignore +teaching noise. Only sampled run uses the attached bitflip, depolarizing or +amplitude_damping channel. Measurement marks choose sampled wires without +collapsing the ideal state. Mixed-matrix construction verifies Hermiticity and +shape, not positivity or trace one. These boundaries determine which scientific +claims an experiment can support; module intros give concrete counterchecks. -## gate module +Author a program from the same knowledge -File path: ext/quantum/gate/index.mq.md +Save the following as bell.mq.md and run marqdo run bell.mq.md. The steps table +is the circuit specification; frontmatter imports the existing module. The two printed weights should be near 0.5. GFM +record tables begin with @; a comma-separated wire cell names control then target. +A formula can be bound before gate.custom or gate.gate in the same way. -Use this when you need a gate handle or a formula matrix check. +```marqdo +--- +markup: occlusion +import: + circuit: ext/quantum/circuit/index.mq.md +--- -Call example (plain text): - marqdo call ext/quantum/gate/index.mq.md hadamard --effects plugin --json - marqdo call ext/quantum/gate/index.mq.md cnot --effects plugin --json +# main -Main ## tools: hadamard, pauli_x, pauli_z, cnot, custom, matches. +`steps` = -*None* +| @ | gate | qubits | +|---|------|--------| +| 1 | H | 0 | +| 2 | CX | "0,1" | -## simulate module +**qc = circuit.circuit qubits=2 steps=`steps`** +**p = > `qc`.probabilities** +**p00 = access(p, "00")** +**p11 = access(p, "11")** +> print text=`p00` +> print text=`p11` +``` -File path: ext/quantum/simulate/index.mq.md +Develop without creating another API -Use this when you already have a circuit handle and want amplitudes, -probabilities, or sampled shots. +A new experiment normally belongs in this index as a small orchestration of +existing modules. State its physical question, inputs, expected values and +limitations beside the executable steps, as bell_analysis does below. A new +unitary normally belongs in gate.custom; it needs no new native export. -Call example (plain text): - marqdo call ext/quantum/simulate/index.mq.md probabilities circuit=$qc --effects plugin --session s1 --json +A genuinely new primitive belongs in its domain module. Read that module's +development route, add its free tool, preserve the existing author method, and +update the Chinese mirror. Native evolution is in plugins/quantum/src/sim.rs, +algebra in linalg.rs, SVG in draw.rs, and ABI registration in src/lib.rs there. +Keep loading confined to the capability boundary. If adding a new file, update +the package file list in src/ext_cli.rs so installation includes it. -Main ## tools: simulate, state, probabilities, run, noise. Ideal probabilities -ignore teaching noise; run applies noise when set. +Use prose declarations for parameter defaults, a parameter contract immediately +after the heading, and a return contract before any executable statement. +Current extract_function_contract reads both only before the first statement; +a return table placed after cap.load is documentation, not an enforced contract. +Use number/text/bool/any from the current type vocabulary; describe handle shape +and origin in prose instead of inventing a type checker. Interleave intent and +operations. Do not pad the narrative ratio with repeated generic sentences. -*None* +Ordinary section titles must stay prose: ## creates an actual callable symbol. +Only executable tools and object methods should appear in the tool tree. For +navigation use source links and the existing knowledge inspect/resolve commands; +stable symbols are compiler output, not a handwritten tool catalog. -## state module +```text +marqdo knowledge ext/quantum --json inspect bell_analysis +marqdo check --narrative-ratio ext/quantum/index.mq.md +cargo test --locked --test quantum_handbook +cargo test --locked --test call_cli quantum_ +cargo test --locked --test gold ext_quantum -- --test-threads=1 +``` -File path: ext/quantum/state/index.mq.md +The handbook test executes the sh blocks and author examples directly from both +language trees, compares independent scientific expectations, and checks both +Tree and Bytecode. An example that cannot be copied and run is a broken public +interface even if the narration ratio is high. Existing quantum golds preserve +noise, formula, SVG and author-object behavior. No network or LLM is needed. +This implements the small call-based core described in next/010–012; richer +self-modifying agents and persistent interactive branches remain future work, +not extra promises of this package. -Use this for Kronecker product, fidelity, and Schmidt decomposition. +Failure recovery -Call example (plain text): - marqdo call ext/quantum/state/index.mq.md fidelity a=$psi b=$phi --effects plugin --json +A missing plugin: inspect _capability, build/install quantum, then retry the +small Bell command. An unknown session binding: keep one session id and rerun +its producer before its consumer. Unexpected ideal results under noise: use run +for noisy samples. A width/shape error: use the limits and matrix conventions +above instead of silently reducing the scientific problem. Never treat an +error envelope as an empty successful result. -Main ## tools: kron, fidelity, schmidt. - -*None* - -## density module - -File path: ext/quantum/density/index.mq.md - -Use this for mixed states. - -Call example (plain text): - marqdo call ext/quantum/density/index.mq.md from_state state=$qc --effects plugin --toget rho --json - marqdo call ext/quantum/density/index.mq.md purity density=$rho --effects plugin --json - -*None* - -## viz module - -File path: ext/quantum/viz/index.mq.md - -Use this to draw SVG. Pass a circuit or density handle and optional path. - -Call example (plain text): - marqdo call ext/quantum/viz/index.mq.md draw_circuit circuit=$qc path="bell.svg" --effects plugin --session s1 --json - -Main ## tools: draw_circuit, draw_probs, draw_bloch, draw_density, draw_gate. - -*None* - -## bell_phi_plus - -One-shot orchestration tool on this index file. It takes no parameters. It builds -the Bell Phi-plus state with Hadamard on qubit 0 and CNOT from 0 to 1, then -returns ideal basis probabilities. Use this when you only need the demo result. -Use the stepwise circuit and simulate calls above when you need intermediate -handles. +## bell_circuit | 返回 | 类型 | 说明 | |------|------|------| -| result | any | map of basis label to probability | +| result | any | Two-qubit circuit for simulation, density or drawing | -Exact command to run this tool: +Prepare a Bell Phi-plus circuit with no arguments, starting from 00. +First create equal superposition on the low wire, then use that wire to +control the other. The resulting amplitudes correlate 00 with 11. +Return the circuit so a caller can apply another gate, attach noise, draw it +or independently test entanglement. Every step keeps the returned new value. -Call example (plain text): - marqdo call ext/quantum/index.mq.md bell_phi_plus --effects plugin --json +**qc = circuit.new qubits=2 steps=None** -**qc = > circuit.new qubits=2 steps=None** -**qc = > circuit.hadamard circuit=`qc` qubit=0** -**qc = > circuit.cnot circuit=`qc` control=0 target=1** +Make two equal paths on the low wire, then propagate the path label to the other wire. + +**qc = circuit.hadamard circuit=`qc` qubit=0** +*> circuit.cnot circuit=`qc` control=0 target=1* + +## bell_phi_plus + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Basis probabilities; 00 and 11 each near 0.5 | + +This no-argument demonstration reuses the preparation on this page and +returns only ideal probabilities. Expect equal weights on 00 and 11 and zero +elsewhere. Computational-basis correlation alone does not prove entanglement; +use bell_analysis for reduced purity, ZZ expectation and Schmidt evidence. + +**qc = > bell_circuit** *> simulate.probabilities circuit=`qc`* + +## bell_analysis + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | probabilities, purity, reduced_purity, zz, schmidt; no file output | + +This no-argument experiment cross-checks the joint system, one subsystem +and their correlation from the same prepared circuit. Both language entries +return the same scientific field names. Callers need no native export names +or persistent session for the intermediate observations. Expect joint purity +one, reduced purity one-half, ZZ one and Schmidt entropy ln(2), within 1e-9. +All paths here describe ideal evolution rather than noisy trajectory averages. + +**qc = > bell_circuit** +**probs = simulate.probabilities circuit=`qc`** + +Build the joint density and compute purity. A pure joint state need not +have pure subsystems. Keep only the low wire and test the mixedness that +appears when information about the other wire is discarded. + +**rho = density.from_state state=`qc`** +**whole = density.purity density=`rho`** +`kept` = + +| qubit | +|-------| +| 0 | + +**reduced = density.partial_trace density=`rho` keep=`kept`** +**local = density.purity density=`reduced`** + +ZZ measures correlation and is not an entanglement witness by itself. +The Schmidt decomposition supplies pure-state coefficients and entropy. +Together these observations distinguish a Bell pure state from a classical +mixture with identical basis probabilities. Keep the measured values in the +return table rather than hiding them behind a pass label with an implicit threshold. + +**correlation = density.expect density=`rho` obs="ZZ"** +**split = state.schmidt state=`qc` cut=1** + +`report` = + +| probabilities | purity | reduced_purity | zz | schmidt | +|---------------|--------|----------------|----|---------| +| `probs` | `whole` | `local` | `correlation` | `split` | + +*report* diff --git a/ext/quantum/simulate/index.mq.md b/ext/quantum/simulate/index.mq.md index 1a1b519..4c0f352 100644 --- a/ext/quantum/simulate/index.mq.md +++ b/ext/quantum/simulate/index.mq.md @@ -7,32 +7,57 @@ import: cap: ext/quantum/_capability/index.mq.md --- -Simulate +Simulation — choose the observable before choosing the execution path. -Simulation answers what a circuit does. Ideal paths (simulate, state, -probabilities) ignore teaching noise. The run tool draws computational-basis -shots and applies circuit noise when noise was attached. The simulator refuses -circuits wider than the plugin limit instead of silently truncating. +What are the amplitudes? Use simulate (noise: no); returns list of maps with re, im. -## For AI agents +Need a state for tensor/fidelity work? Use state (noise: no); returns quantum_state with qubits, dim, amplitudes. -If you were given only this file, you need a circuit handle from -ext/quantum/circuit/index.mq.md (usually via --toget). Then: +What are the exact basis weights? Use probabilities (noise: no); returns basis label → probability. -Call example (plain text): - marqdo call ext/quantum/simulate/index.mq.md probabilities circuit=$qc --effects plugin --session s --json +What would repeated readout produce? Use run (noise: yes); returns qubits, shots, seed, counts, measure; noise when set. -Other tools: simulate, state, run, noise. Always --effects plugin. +Attach one teaching noise channel Use noise (noise: later in run); returns new circuit. + +Noise is bitflip, depolarizing or amplitude_damping, with probability in [0,1]. +It acts after each unitary on that operation's participating wires. Attaching +noise replaces the previous channel; it does not append a gate or change the +ideal state. This is a teaching trajectory model, not a hardware backend. +Measurement marks select sampled wires without collapsing ideal amplitudes. + +A complete noise experiment + +First create a circuit through the [circuit module](../circuit/index.mq.md). +The ideal state after X is one. Full bit-flip noise after X makes every sampled +outcome zero; exact probabilities still describe one. Repeating run with the +same circuit, seed and shots is deterministic for this simulator version. + +```sh +marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/circuit/index.mq.md x 'circuit=$qc' --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/simulate/index.mq.md noise 'circuit=$qc' 'kind="bitflip"' p=1 --effects plugin --session handbook --toget noisy --json +marqdo call ext/quantum/simulate/index.mq.md probabilities 'circuit=$noisy' --effects plugin --session handbook --json +marqdo call ext/quantum/simulate/index.mq.md run 'circuit=$noisy' shots=32 seed=7 --effects plugin --session handbook --json +``` + +Development route + +Put new readouts here rather than duplicating circuit construction. Numerical +evolution and seeded sampling live in plugins/quantum/src/sim.rs; exports live +in src/lib.rs beside it. Preserve ideal/noisy separation in both language trees +and validate tests/ext/quantum-noise-smoke.mq.md plus amplitude-damping golds. +For entanglement go to [state](../state/index.mq.md); for mixed states use +[density](../density/index.mq.md), which currently describes ideal evolution. ## simulate -Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise -channels attached to the circuit are ignored here. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to evolve | +Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise +channels attached to the circuit are ignored here. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | amplitude list | @@ -42,13 +67,13 @@ channels attached to the circuit are ignored here. ## state -Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state -object. Prefer this when later fidelity or density tools expect a state handle. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to evolve | +Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state +object. Prefer this when later fidelity or density tools expect a state handle. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | ideal state | @@ -58,13 +83,13 @@ object. Prefer this when later fidelity or density tools expect a state handle. ## probabilities -Map basis label to probability for the ideal state of `circuit`. Labels use -qubit 0 as the rightmost bit. Noise is ignored. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to read | +Map basis label to probability for the ideal state of `circuit`. Labels use +qubit 0 as the rightmost bit. Noise is ignored. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | probability map | @@ -74,15 +99,15 @@ qubit 0 as the rightmost bit. Noise is ignored. ## run -Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024 -and `seed`=1 so replays are deterministic. Teaching noise is applied when set. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to sample | | shots | number | sample count | | seed | number | RNG seed | +Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024 +and `seed`=1 so replays are deterministic. Teaching noise is applied when set. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | counts or shot result | @@ -92,16 +117,16 @@ and `seed`=1 so replays are deterministic. Teaching noise is applied when set. ## noise -Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal -simulate and probability tools ignore it. Keep p small unless demonstrating -decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to annotate | | kind | text | noise family name | | p | number | strength in the unit interval | +Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal +simulate and probability tools ignore it. Keep p small unless demonstrating +decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | circuit with noise metadata | diff --git a/ext/quantum/state/index.mq.md b/ext/quantum/state/index.mq.md index 80358bc..f56abac 100644 --- a/ext/quantum/state/index.mq.md +++ b/ext/quantum/state/index.mq.md @@ -7,39 +7,58 @@ import: cap: ext/quantum/_capability/index.mq.md --- -State +Pure states — compare, combine or partition a quantum state. -A pure quantum state on n qubits is a unit vector in a complex space of size -two to the n. In this package each amplitude is a map with re and im fields. -Qubit 0 is the rightmost bit in basis labels. Ideal simulation ignores teaching -noise; sampled trajectories live under the simulate skill. +Obtain a state with simulate.state. A state is a map with qubits, dim and a +list of amplitudes, each carrying re and im. A raw amplitude list from +simulate.simulate is not a state handle. fidelity and schmidt also accept a +circuit and evolve its ideal state. kron requires two state handles for the +state-vector branch; convert circuits with simulate.state first. -States often arrive as the result of simulate tools on a circuit. This module -answers state-to-state questions: tensor products, fidelity, and Schmidt cuts. +A self-contained tensor experiment -## For AI agents +Two zero states make a two-qubit zero state. Its fidelity with itself is one. +The first factor is the high-bit subsystem of the tensor product; the second +factor occupies the low bits. For Schmidt, cut counts the low bits in A. -If you were given only this file, run state tools with marqdo call and --effects -plugin. Example fidelity: +```sh +marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/simulate/index.mq.md state 'circuit=$qc' --effects plugin --session handbook --toget psi --json +marqdo call ext/quantum/state/index.mq.md kron 'a=$psi' 'b=$psi' --effects plugin --session handbook --toget product --json +marqdo call ext/quantum/state/index.mq.md fidelity 'a=$product' 'b=$product' --effects plugin --session handbook --json +marqdo call ext/quantum/state/index.mq.md schmidt 'state=$product' cut=1 --effects plugin --session handbook --json +``` -Call example (plain text): - marqdo call ext/quantum/state/index.mq.md fidelity a=$psi b=$phi --effects plugin --json +fidelity is squared absolute overlap of equal-size pure states. schmidt returns +coeffs, ua, ub, entropy, cut and qubits. Entropy uses natural logarithms (nats); +a Bell pair has two coefficients near 1/√2 and entropy ln(2). Schmidt currently +shares the density solver's six-qubit limit and requires 0 < cut < qubits. +kron also accepts matrix factors and returns a matrix-bearing handle; this is +an operator product, not an automatic conversion into a normalized pure state. -Tools: kron, fidelity, schmidt. +Development route + +Keep pure-state algebra here and mixed-state operations in +[density](../density/index.mq.md). Mathematical implementations and independent +numerical tests belong in plugins/quantum/src/linalg.rs, with exports in +src/lib.rs. Add both language contracts and preserve tests/ext/quantum-linalg-smoke.mq.md. +Use known orthogonal/product/entangled states as checks instead of comparing a +new implementation only with itself. Draw a single wire through +[viz.draw_bloch](../viz/index.mq.md) using its source circuit. ## kron -The Kronecker product of `a` and `b` builds a larger space from two smaller -ones. For state vectors this writes product states; for matrices it enlarges -operators. - | 参数 | 类型 | 说明 | |------|------|------| | a | any | left factor state or matrix | | b | any | right factor state or matrix | -Pass handles the plugin already understands. Circuit and density objects may -participate through their registered ABI shapes when the simulator accepts them. +The Kronecker product of `a` and `b` builds a larger space from two smaller +ones. For state vectors this writes product states; for matrices it enlarges +operators. + +Pass handles the plugin already understands. For a pure-state product, convert circuits with simulate.state first. Matrix +factors take the operator branch; raw amplitude lists are not accepted as states. | 返回 | 类型 | 说明 | |------|------|------| @@ -50,16 +69,16 @@ participate through their registered ABI shapes when the simulator accepts them. ## fidelity -Pure-state fidelity between `a` and `b` is the squared absolute overlap. It is -one when the states coincide and zero when they are orthogonal. You may pass a -circuit handle; the plugin uses the ideal simulated state. Teaching noise is -ignored. - | 参数 | 类型 | 说明 | |------|------|------| | a | any | first pure state or circuit | | b | any | second pure state or circuit | +Pure-state fidelity between `a` and `b` is the squared absolute overlap. It is +one when the states coincide and zero when they are orthogonal. You may pass a +circuit handle; the plugin uses the ideal simulated state. Teaching noise is +ignored. + | 返回 | 类型 | 说明 | |------|------|------| | result | number | fidelity in the unit interval | @@ -69,15 +88,15 @@ ignored. ## schmidt -Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest -`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show -entanglement across the bipartition. - | 参数 | 类型 | 说明 | |------|------|------| | state | any | pure state or circuit | | cut | number | qubits in subsystem A low bits | +Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest +`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show +entanglement across the bipartition. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | singular values and factors | diff --git a/ext/quantum/viz/index.mq.md b/ext/quantum/viz/index.mq.md index ebd3666..16267f7 100644 --- a/ext/quantum/viz/index.mq.md +++ b/ext/quantum/viz/index.mq.md @@ -7,32 +7,71 @@ import: cap: ext/quantum/_capability/index.mq.md --- -Visualization +Visualization — turn a scientific result into an inspectable SVG. -Drawings turn a circuit or density into SVG for view mode or a path on disk. -Pick a kind for the figure and a theme for colors. Themes dark (default), light, -and bw share geometry so lectures can switch style without rewriting the -circuit. Start with circuit and probs kinds when unsure. +From circuit, use draw_circuit for gate rails. -## For AI agents +From circuit, use draw_probs for ideal probability bars. -If you were given only this file, draw with marqdo call and --effects plugin. -You need a circuit or density handle from another module (toget). +From circuit, use draw_bloch for one wire's reduced Bloch vector. -Call example (plain text): - marqdo call ext/quantum/viz/index.mq.md draw_probs circuit=$qc path="out.svg" --effects plugin --session s --json +From density, use draw_density for hinton, city, density, paulivec. + +From gate, use draw_gate for gate glyph or matrix heatmap. + +From circuit, use draw_state for qsphere or multibloch. + +Circuit figures accept dark, light and bw themes. Gate and density drawing +have no theme parameter on the current public API. Every tool returns a +quantum_svg map including svg and kind. Under call, use path=None to return +and record SVG; --effects plugin permits loading and drawing but the current +call host denies filesystem writes. To save a file, draw in an author program +executed with marqdo run. + +A complete drawing experiment + +Create the circuit first instead of assuming a handle already exists. The +probability result's svg field must contain an SVG document and kind must be +probs; the next results are qsphere and multibloch. Omitting path means None. +To save a file, append the following line to the root index's author example +before running it: + +```text +**img = > `qc`.draw path="bell.svg"** +``` + +Relative paths resolve against the source document's directory. A call with a nonempty path fails under the current host policy. + +```sh +marqdo call ext/quantum/circuit/index.mq.md new qubits=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/circuit/index.mq.md hadamard 'circuit=$qc' --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/viz/index.mq.md draw_probs 'circuit=$qc' 'theme="light"' --effects plugin --session handbook --json +marqdo call ext/quantum/viz/index.mq.md draw_state 'circuit=$qc' path=None --effects plugin --session handbook --json +marqdo call ext/quantum/viz/index.mq.md draw_state 'circuit=$qc' 'kind="multibloch"' path=None --effects plugin --session handbook --json +``` + +Development route + +Rendering belongs in plugins/quantum/src/draw.rs and the record_plot bridge +in src/lib.rs. Add a named choice to this page and its +Chinese mirror without mixing filesystem work into circuit algebra. Verify SVG +structure and numerical labels, not a screenshot alone. Preserve + tests/ext/quantum-draw-smoke.mq.md and quantum-viz-advanced-smoke.mq.md. +For input preparation follow [circuit](../circuit/index.mq.md), +[gate](../gate/index.mq.md) or [density](../density/index.mq.md). ## draw_circuit -Rail diagram of gates and barriers for `circuit`. Theme `theme`="dark" by -default. Optional `path` writes SVG for CLI or view embedding. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to render | | path | any | optional output path or None | | theme | text | dark light or bw | +Render `circuit` as gate rails and barriers. Choose `theme`="dark" by default; +light and bw preserve the same geometry. Optional `path`=None returns SVG +without a file. A nonempty path is available to author programs under run. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | @@ -42,15 +81,16 @@ default. Optional `path` writes SVG for CLI or view embedding. ## draw_probs -Probability bars for the ideal state of `circuit`. Same theme tokens as the -rail diagram. Uses `theme`="dark" when omitted. Optional `path` for file output. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit to render | | path | any | optional output path or None | | theme | text | dark light or bw | +Plot ideal basis probabilities of `circuit`. Default `theme`="dark" supports +light and bw alternatives. Optional `path`=None returns SVG without a file. +The bars ignore teaching noise, just like simulate.probabilities. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | @@ -60,9 +100,6 @@ rail diagram. Uses `theme`="dark" when omitted. Optional `path` for file output. ## draw_bloch -Bloch sphere for one wire of `circuit`. Default `qubit`=0. Optional `path` and -`theme`="dark". Multi-qubit circuits still render one qubit reduced picture. - | 参数 | 类型 | 说明 | |------|------|------| | circuit | any | circuit source | @@ -70,6 +107,10 @@ Bloch sphere for one wire of `circuit`. Default `qubit`=0. Optional `path` and | qubit | number | which wire | | theme | text | dark light or bw | +Show the reduced Bloch sphere of wire `qubit`=0 from `circuit`. Default +`theme`="dark"; optional `path`=None returns SVG without a file. A multi-qubit +circuit still produces one reduced wire picture, not a joint-state sphere. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | @@ -79,15 +120,16 @@ Bloch sphere for one wire of `circuit`. Default `qubit`=0. Optional `path` and ## draw_density -Plot density operator `density`. Default `kind`="hinton". Optional `path`. -Choose city, density, or paulivec when the lecture uses those metaphors. - | 参数 | 类型 | 说明 | |------|------|------| | density | any | density operator | | path | any | optional output path or None | | kind | text | hinton city density or paulivec | +Plot `density` using `kind`="hinton" by default. Alternatives are city, +density and paulivec. Optional `path`=None returns SVG without a file. +Use the density module to construct the mixed-state input before drawing. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | @@ -97,18 +139,41 @@ Choose city, density, or paulivec when the lecture uses those metaphors. ## draw_gate -Glyph or matrix heatmap for `gate`. Use `kind`="gate" by default, or matrix -when checking a custom unitary. Optional `path`. - | 参数 | 类型 | 说明 | |------|------|------| | gate | any | gate handle | | path | any | optional output path or None | | kind | text | gate or matrix | +Plot `gate` using `kind`="gate" by default. Choose matrix for a complex-entry +heatmap. Optional `path`=None returns SVG without a file. This observes the +operator rather than applying it or changing any circuit. + | 返回 | 类型 | 说明 | |------|------|------| | result | any | drawing result | > cap.load *> quantum_gate_draw gate=`gate` path=`path` kind=`kind`* + +## draw_state + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | Circuit evolved ideally | +| kind | text | qsphere or multibloch | +| path | any | SVG output path or None | + +Observe the ideal state of `circuit` as a basis-amplitude/phase sphere or one +reduced Bloch sphere per wire. Default `kind`="qsphere"; use multibloch for the +per-wire picture. Default `path`=None avoids explicit file output. A set of +local Bloch vectors alone cannot certify joint entanglement. Both advanced +figures currently use fixed styling; theme support remains Q8c work and is +not offered as a nonfunctional parameter here. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg with kind and svg | + +> cap.load +*> quantum_draw_circuit circuit=`circuit` path=`path` kind=`kind` qubit=0 theme="dark"* diff --git a/ext/quantum/量子/可视化/索引.mq.md b/ext/quantum/量子/可视化/索引.mq.md index ce531f1..584cb0b 100644 --- a/ext/quantum/量子/可视化/索引.mq.md +++ b/ext/quantum/量子/可视化/索引.mq.md @@ -6,27 +6,65 @@ import: 能力: ext/quantum/量子/能力/索引.mq.md --- -把电路或密度画成 SVG。选择 kind 与主题。主题 dark(默认)、light、bw 几何一致。 +可视化:把科学结果变成可检查的 SVG。 -## 给智能体 +输入为电路时,用画电路绘制门轨线。 -若你只拿到本文件,需要其它模块给出的电路或密度句柄(toget)。 +输入为电路时,用画概率绘制理想概率条。 -调用示例(纯文本): - marqdo call ext/quantum/量子/可视化/索引.mq.md 画概率 电路=$qc 路径="out.svg" --effects plugin --session s --json +输入为电路时,用画布洛赫绘制单线约化布洛赫矢量。 -*None* +输入为密度时,用画密度绘制hinton、city、density、paulivec。 + +输入为门时,用画门绘制 gate 门符号或 matrix 热图。 + +输入为电路时,用画态绘制 qsphere 或 multibloch。 + +电路图支持 dark、light、bw;当前门和密度绘图没有主题参数。 +结果为含 svg、kind 的 quantum_svg 映射。命令行 call 使用 路径=None,只返回并记录 +SVG;--effects plugin 允许加载与绘图,但当前 call 宿主禁止文件写入。 +需要落盘时,在作者程序中使用绘图方法,并通过 marqdo run 执行。 + +完整的绘图实验 + +先创建电路,不假设已经存在句柄。画概率的 svg 必须包含 SVG 文档,kind 为 probs; +后两步分别得到 qsphere、multibloch。省略路径等同于 None。 +要保存图片,在根索引的作者程序中追加以下行,再运行该程序: + +```text +**img = > `qc`.绘图 路径="bell.svg"** +``` + +相对路径按源文档目录解析,不一定是 shell 工作目录。 + +```sh +marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 '电路=$qc' --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/可视化/索引.mq.md 画概率 '电路=$qc' '主题="light"' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/可视化/索引.mq.md 画态 '电路=$qc' 路径=None --effects plugin --session handbook --json +marqdo call ext/quantum/量子/可视化/索引.mq.md 画态 '电路=$qc' '种类="multibloch"' 路径=None --effects plugin --session handbook --json +``` + +开发路线 + +渲染实现位于 plugins/quantum/src/draw.rs 和 src/lib.rs 中的 +record_plot 桥接。新增图类时同步本页和英文入口,别把文件系统操作混入电路代数。 +核对 SVG 结构及数值标签,截图不能代替数值校验。保留 + tests/ext/quantum-draw-smoke.mq.md 与 quantum-viz-advanced-smoke.mq.md。 +输入准备见[电路](../电路/索引.mq.md)、[门](../门/索引.mq.md)、[密度](../密度/索引.mq.md)。 ## 画电路 -`电路` 的轨线图。默认 `主题`="dark"。可选 `路径` 落盘。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路 | | 路径 | any | 可选输出路径或 None | | 主题 | text | dark light 或 bw | +把 `电路` 的门和屏障画成轨线。默认 `主题`="dark",也可选择 light 或 bw。 +可选 `路径`=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。 +主题选择只改变配色,不改变线路几何与计算含义。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | @@ -36,14 +74,16 @@ import: ## 画概率 -`电路` 理想态概率条。默认 `主题`="dark"。可选 `路径` 落盘。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路 | | 路径 | any | 可选路径或 None | | 主题 | text | dark light 或 bw | +绘制 `电路` 的理想基矢概率条。默认 `主题`="dark",可改为 light 或 bw。 +可选 `路径`=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致, +忽略已附加的教学噪声,不能用它替代含噪采样结果。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | @@ -53,8 +93,6 @@ import: ## 画布洛赫 -`电路` 上单线布洛赫球。默认 `比特`=0、`主题`="dark"。可选 `路径` 落盘。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路 | @@ -62,6 +100,10 @@ import: | 比特 | number | 哪一根线 | | 主题 | text | dark light 或 bw | +绘制 `电路` 上 `比特`=0 的约化布洛赫球。默认 `主题`="dark"。 +可选 `路径`=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态, +不能把这张图解释为整个多比特纯态的完整表示。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | @@ -71,14 +113,16 @@ import: ## 画密度 -绘制密度算符 `密度`。默认 `种类`="hinton"。可选 `路径` 落盘。 - | 参数 | 类型 | 说明 | |------|------|------| | 密度 | any | 密度算符 | | 路径 | any | 可选路径或 None | | 种类 | text | hinton city density 或 paulivec | +绘制 `密度`,默认 `种类`="hinton",也可选 city、density 或 paulivec。 +可选 `路径`=None 只返回 SVG,不写文件。先在密度模块构造或约化输入, +再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | @@ -88,17 +132,39 @@ import: ## 画门 -绘制单个 `门`。默认 `种类`="gate"。可选 `路径` 落盘。 - | 参数 | 类型 | 说明 | |------|------|------| | 门 | any | 门句柄 | | 路径 | any | 可选路径或 None | | 种类 | text | gate 或 matrix | +绘制 `门`,默认 `种类`="gate",选择 matrix 可观察复数矩阵热图。 +可选 `路径`=None 只返回 SVG,不写文件。图形用于观察算符, +不会把门作用到任何电路,也不会改变算符的数值条目。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 绘图结果 | > 能力.加载 *> quantum_gate_draw gate=`门` path=`路径` kind=`种类`* + +## 画态 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 源电路,作理想演化 | +| 种类 | text | qsphere 或 multibloch | +| 路径 | any | SVG 输出路径或 None | + +从 `电路` 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。 +默认 `种类`="qsphere",可改为 multibloch;默认 `路径`=None,不显式落盘。 +qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。 +这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg,含 kind 和 svg | + +> 能力.加载 +*> quantum_draw_circuit circuit=`电路` path=`路径` kind=`种类` qubit=0 theme="dark"* diff --git a/ext/quantum/量子/密度/索引.mq.md b/ext/quantum/量子/密度/索引.mq.md index 071a299..8270a93 100644 --- a/ext/quantum/量子/密度/索引.mq.md +++ b/ext/quantum/量子/密度/索引.mq.md @@ -6,25 +6,43 @@ import: 能力: ext/quantum/量子/能力/索引.mq.md --- -密度算符同时描述纯态与混合态。可从态/电路或显式厄米矩阵构造,再做纯度、 -部分迹与期望。 +密度算符:观察子系统或显式混合态矩阵。 -## 给智能体 -若你只拿到本文件: +从态工具将理想电路或纯态转成密度;从矩阵接受 2^n 阶厄米方阵。密度操作与施密特 +最多支持六比特。矩阵构造器只检查形状和厄米性,不保证半正定或迹为 1。 +解释物理纯度前,应核对迹并用本征工具检查本征值。 -调用示例(纯文本): - marqdo call ext/quantum/量子/密度/索引.mq.md 从态 态=$qc --effects plugin --toget rho --json - marqdo call ext/quantum/量子/密度/索引.mq.md 纯度 密度=$rho --effects plugin --json +独立的混合态校验 -*None* +以下最大混合单比特矩阵迹为 1、纯度为 0.5、Z 期望为 0,无需已有电路或会话。 +研究纠缠时,从贝尔电路经过从态,再以 保留=[0] 求部分迹,约化纯度也应为 0.5。 + +```sh +marqdo call ext/quantum/量子/密度/索引.mq.md 从矩阵 '矩阵=[[0.5,0],[0,0.5]]' --effects plugin --session handbook --toget rho --json +marqdo call ext/quantum/量子/密度/索引.mq.md 纯度 '密度=$rho' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/密度/索引.mq.md 期望 '密度=$rho' '可观测量="Z"' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effects plugin --session handbook --json +``` + +部分迹保留列表指定的零起始比特并消去其余。泡利串左端表示高位,ZZ 表示两线关联。 +矩阵工具导出复数嵌套条目,本征返回 eigenvalues 与 eigenvectors。 +[可视化](../可视化/索引.mq.md)画密度支持 hinton、city、density、paulivec。 +从态与理想模拟一样忽略已附加教学噪声,不应当作含噪密度演化。 + +开发路线 + +新增混合态数学放入 plugins/quantum/src/linalg.rs,通过同目录 src/lib.rs 导出, +同步本页与英文镜像。构造器描述必须与真实校验能力相符。用纯态纯度 1、贝尔约化 +纯度 0.5、独立矩阵的期望检验 tests/ext/quantum-linalg-smoke.mq.md。 ## 从态 -由纯态或电路句柄 `态` 的理想态构造 rho。 | 参数 | 类型 | 说明 | |------|------|------| | 态 | any | 纯态或电路 | +由纯态或电路句柄 `态` 的理想态构造 rho。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 密度句柄 | @@ -33,12 +51,13 @@ import: *> quantum_density_from_state state=`态`* ## 从矩阵 -由显式厄米 `矩阵` 构造 rho。 | 参数 | 类型 | 说明 | |------|------|------| | 矩阵 | any | 厄米矩阵 | +由显式厄米 `矩阵` 构造 rho。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 密度句柄 | @@ -47,12 +66,13 @@ import: *> quantum_density_from_matrix matrix=`矩阵`* ## 纯度 -计算 `密度` 的 Tr(rho^2)。 | 参数 | 类型 | 说明 | |------|------|------| | 密度 | any | 密度算符 | +计算 `密度` 的 Tr(rho^2)。 + | 返回 | 类型 | 说明 | |------|------|------| | result | number | 纯度 | @@ -61,13 +81,14 @@ import: *> quantum_density_purity density=`密度`* ## 部分迹 -对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。 | 参数 | 类型 | 说明 | |------|------|------| | 密度 | any | 联合密度 | | 保留 | any | 保留的比特下标列表 | +对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 约化密度 | @@ -76,13 +97,14 @@ import: *> quantum_density_partial_trace density=`密度` keep=`保留`* ## 期望 -`密度` 上可观测量 `可观测量` 的期望值。 | 参数 | 类型 | 说明 | |------|------|------| | 密度 | any | 密度算符 | | 可观测量 | any | 泡利串或矩阵 | +`密度` 上可观测量 `可观测量` 的期望值。 + | 返回 | 类型 | 说明 | |------|------|------| | result | number | 期望值 | @@ -91,12 +113,13 @@ import: *> quantum_density_expect density=`密度` obs=`可观测量`* ## 本征 -`密度` 的厄米谱。 | 参数 | 类型 | 说明 | |------|------|------| | 密度 | any | 密度算符 | +`密度` 的厄米谱。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 本征值与本征矢 | @@ -104,10 +127,34 @@ import: > 能力.加载 *> quantum_density_eig density=`密度`* +## 矩阵 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 密度 | any | Density handle / 密度句柄 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 复数矩阵条目,每项含 re 与 im | + +导出 `密度` 的显式复数嵌套矩阵。观察条目不会改变密度算符, +可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。 + +> 能力.加载 +*> quantum_density_matrix density=`密度`* # 密度 - + `态`=None - + `矩阵`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| 态 | any | 默认 None | +| 矩阵 | any | 默认 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 返回结果 | + +输入:`态`=None, `矩阵`=None。 由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。 @@ -119,52 +166,79 @@ import: ## 矩阵 -返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 复数矩阵条目,每项含 re 与 im | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。 *> quantum_density_matrix density=`self`* ## 纯度 -计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 标量观察值 | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。 *> quantum_density_purity density=`self`* ## 部分迹 - + `保留` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 保留 | any | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 密度算符句柄 | + +输入:`保留`。 保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_density_partial_trace density=`self` keep=`保留`* ## 本征 -计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | eigenvalues 与 eigenvectors | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。 *> quantum_density_eig density=`self`* ## 期望 - + `可观测量` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 可观测量 | any | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 标量观察值 | + +输入:`可观测量`。 可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_density_expect density=`self` obs=`可观测量`* ## 绘图 - + `路径`=None - + `种类`=hinton + +| 参数 | 类型 | 说明 | +|------|------|------| +| 路径 | any | 默认 None | +| 种类 | any | 默认 hinton | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg,含 kind 与 svg | + +输入:`路径`=None, `种类`="hinton"。 绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_density_draw density=`self` path=`路径` kind=`种类`* diff --git a/ext/quantum/量子/态/索引.mq.md b/ext/quantum/量子/态/索引.mq.md index 22970b9..4c0ae39 100644 --- a/ext/quantum/量子/态/索引.mq.md +++ b/ext/quantum/量子/态/索引.mq.md @@ -6,29 +6,47 @@ import: 能力: ext/quantum/量子/能力/索引.mq.md --- -纯态是复空间中的单位向量。本包振幅用含 re、im 的映射表示。基矢标签里比特 0 在 -最右侧。理想模拟忽略教学噪声;采样轨迹见模拟模块。 +纯态:比较、组合或划分一个量子态。 -## 给智能体 +用模拟模块的态工具取得含 qubits、dim、amplitudes 的句柄。每个振幅是 re、im 映射; +模拟工具返回的裸振幅列表不是态句柄。保真度与施密特分解也接受电路并作理想演化。 +张量积的态分支要求两个态句柄,必须先把电路转换为态。 -若你只拿到本文件,用 marqdo call 调用下面的 ## 工具,并务必加 --effects plugin。 +完整的张量积实验 -调用示例(纯文本): - marqdo call ext/quantum/量子/态/索引.mq.md 保真度 a=$psi b=$phi --effects plugin --json +两个零态得到两比特零态,自身保真度为 1。张量积第一个因子占高位,第二个占低位。 +施密特分割相反地按低位数定义 A,不要把这两个约定混淆。 -工具名:张量积、保真度、施密特分解。 +```sh +marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 态 '电路=$qc' --effects plugin --session handbook --toget psi --json +marqdo call ext/quantum/量子/态/索引.mq.md 张量积 'a=$psi' 'b=$psi' --effects plugin --session handbook --toget product --json +marqdo call ext/quantum/量子/态/索引.mq.md 保真度 'a=$product' 'b=$product' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/态/索引.mq.md 施密特分解 '态=$product' 分割=1 --effects plugin --session handbook --json +``` -*None* +保真度是等维纯态重叠绝对值的平方。施密特返回 coeffs、ua、ub、entropy、cut、qubits; +entropy 单位为自然对数 nats,贝尔态为 ln(2),两个系数各约 1/√2。 +施密特沿用密度求解器的六比特上限,要求 0 < 分割 < 比特数。 +张量积也支持矩阵因子并返回含矩阵的句柄,此时表示算符积,不自动保证归一化纯态。 + +开发路线 + +纯态代数放在本页,混合态操作放在[密度](../密度/索引.mq.md)。数学实现和独立数值 +测试位于 plugins/quantum/src/linalg.rs,导出位于同目录 src/lib.rs。同步双语契约, +保留 tests/ext/quantum-linalg-smoke.mq.md。用已知正交态、积态、纠缠态作独立期望, +不要仅与实现自身比较。单线布洛赫图通过[可视化](../可视化/索引.mq.md)画布洛赫 +并传入源电路。 ## 张量积 -将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。 - | 参数 | 类型 | 说明 | |------|------|------| | a | any | 左因子 | | b | any | 右因子 | +将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 张量积结果 | @@ -38,14 +56,14 @@ import: ## 保真度 -纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 -教学噪声忽略。 - | 参数 | 类型 | 说明 | |------|------|------| | a | any | 第一态或电路 | | b | any | 第二态或电路 | +纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 +教学噪声忽略。 + | 返回 | 类型 | 说明 | |------|------|------| | result | number | 保真度 | @@ -55,13 +73,13 @@ import: ## 施密特分解 -对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。 - | 参数 | 类型 | 说明 | |------|------|------| | 态 | any | 纯态或电路 | | 分割 | number | 子系统 A 比特数 | +对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 施密特数据 | diff --git a/ext/quantum/量子/模拟/索引.mq.md b/ext/quantum/量子/模拟/索引.mq.md index 03a4f2f..c2db2d0 100644 --- a/ext/quantum/量子/模拟/索引.mq.md +++ b/ext/quantum/量子/模拟/索引.mq.md @@ -6,28 +6,52 @@ import: 能力: ext/quantum/量子/能力/索引.mq.md --- -模拟回答「这条电路会怎样」。理想路径(模拟、态、概率)忽略教学噪声。运行工具 -做计算基采样,并在已附着噪声时应用噪声。超宽电路会被插件拒绝,不会静默截断。 +模拟:先确定要观察什么,再选择执行路径。 -## 给智能体 +振幅是多少:使用 模拟,施噪:否,返回 re、im 映射列表。 -若你只拿到本文件,需要先有电路句柄(通常来自电路模块的 toget)。然后: +需要张量积或保真度输入:使用 态,施噪:否,返回 quantum_state,含 qubits、dim、amplitudes。 -调用示例(纯文本): - marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 电路=$qc --effects plugin --session s --json +精确基矢权重:使用 概率,施噪:否,返回 基矢标签到概率。 -其它工具:模拟、态、运行、噪声。一律 --effects plugin。 +重复读出会怎样:使用 运行,施噪:是,返回 qubits、shots、seed、counts、measure,按需含 noise。 -*None* +设置一个教学噪声通道:使用 噪声,施噪:运行时施加,返回 新电路。 + +噪声族为 bitflip、depolarizing、amplitude_damping,概率范围 [0,1]。 +每个酉操作后在该操作涉及的线上施噪;重复设置会替换旧通道,不是追加一扇门。 +这是教学轨迹模型。测量标记仅选择采样线,不坍缩理想振幅。 + +完整的噪声实验 + +先从[电路模块](../电路/索引.mq.md)取得电路。X 后理想态为 1;概率为 1 的比特翻转 +在 X 后把每次采样变为 0,但精确概率仍描述理想态 1。同一模拟器版本下,电路、 +种子与采样数相同时,运行结果可复现。 + +```sh +marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/电路/索引.mq.md 泡利X '电路=$qc' --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 噪声 '电路=$qc' '种类="bitflip"' 强度=1 --effects plugin --session handbook --toget noisy --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$noisy' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 运行 '电路=$noisy' 次数=32 种子=7 --effects plugin --session handbook --json +``` + +开发路线 + +新读出方式放在本模块,复用电路构造。数值演化和种子采样位于 +plugins/quantum/src/sim.rs,导出位于同目录 src/lib.rs。保持中英理想/含噪边界, +验证 tests/ext/quantum-noise-smoke.mq.md 和振幅阻尼金样。纠缠分析转到 +[态](../态/索引.mq.md),混合态转到[密度](../密度/索引.mq.md);从电路构造密度 +目前仍走理想演化,不是噪声密度引擎。 ## 模拟 -返回 `电路` 的理想态矢量振幅。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 待演化电路 | +返回 `电路` 的理想态矢量振幅。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 振幅列表 | @@ -37,12 +61,12 @@ import: ## 态 -与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 待演化电路 | +与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 理想态 | @@ -52,12 +76,12 @@ import: ## 概率 -`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 待读取电路 | +`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 概率映射 | @@ -67,14 +91,14 @@ import: ## 运行 -对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 待采样电路 | | 次数 | number | 采样次数 | | 种子 | number | 随机种子 | +对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 计数或采样结果 | @@ -84,14 +108,14 @@ import: ## 噪声 -在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。 - | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路 | | 种类 | text | 噪声族名 | | 强度 | number | 单位区间强度 | +在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 带噪声元数据的电路 | diff --git a/ext/quantum/量子/电路/索引.mq.md b/ext/quantum/量子/电路/索引.mq.md index 2351591..b3efdce 100644 --- a/ext/quantum/量子/电路/索引.mq.md +++ b/ext/quantum/量子/电路/索引.mq.md @@ -7,46 +7,56 @@ import: 密度: ext/quantum/量子/密度/索引.mq.md --- -电路是 n 条线上的有序门列,初态为全零。可用本页 ## 工具逐步构造,或用对象 -「电路」的方法链。测量标记只影响采样,不坍缩理想概率所用的态矢量。 +电路构造:需要保留并继续操作一个量子程序时,从这里开始。 -## 给智能体 -若你只拿到本文件,每个 ## 都是工具。一律加 --effects plugin。 +初态为全零态,每次施加都返回新电路,必须接住返回值才能继续。比特 0 对应基矢标签 +最右位,角度单位为弧度。默认支持 1–12 比特;MARQDO_QUANTUM_MAX_QUBITS 可调整 +限制,硬上限 16。态矢量内存按 2^n 增长,密度和施密特另有限制。 -创建两比特电路并保存为 qc: +读懂 → 执行 → 观察 -调用示例(纯文本): - marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=2 --effects plugin --session s --toget qc --json +下面的完整 shell 实验造出贝尔态,再交给[模拟模块](../模拟/索引.mq.md)观察。 +00 和 11 的概率应各约 0.5。单引号保护会话引用,避免 shell 提前展开变量。 +所有命令使用同一会话 handbook,每一步覆盖 qc 绑定,不改动旧电路值。 -在比特 0 上施加哈达玛: +```sh +marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=2 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 '电路=$qc' 比特=0 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/电路/索引.mq.md 控非 '电路=$qc' 控制=0 目标=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects plugin --session handbook --json +``` -调用示例(纯文本): - marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 电路=$qc 比特=0 --effects plugin --session s --toget qc --json +创建线路或预载步骤表:使用 新建,下一步为 模拟模块取结果。 -控非 0→1: +叠加、基态与相位操作:使用 哈达玛、泡利X、泡利Y、泡利Z、相位S、相位T、单位,下一步为 概率。 -调用示例(纯文本): - marqdo call ext/quantum/量子/电路/索引.mq.md 控非 电路=$qc 控制=0 目标=1 --effects plugin --session s --toget qc --json +连续控制:使用 绕X、绕Y、绕Z,下一步为 参数单位为弧度。 -若你只拿到本文件,这里没有「概率」这个 ## 工具。控非之后请在同一会话调用模拟模块 -(不要在本文件上发明概率工具): +纠缠与路由:使用 控非、控相、交换,下一步为 态模块施密特分解。 -调用示例(纯文本): - marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 电路=$qc --effects plugin --session s --json +组合片段、自定义门:使用 追加、施加,下一步为 门模块提供门。 -作者程序可导入本文件并使用对象电路(方法如哈达玛、控非)。智能体优先用上面的 -marqdo call,再调模拟取振幅或概率。 +教学分层或读出:使用 屏障、测量标记,下一步为 可视化或运行采样。 -*None* +下方电路对象保留作者方法链;其模拟、密度和绘图方法是便利入口,完整工具契约在 +对应模块。不要尝试无接收者调用实例方法,直接调用对象之前的自由工具即可。 + +开发路线 + +新电路配方优先在[根索引](../索引.mq.md)组合已有工具。只有组合与自定义门都无法 +表达时才扩原生能力:修改 plugins/quantum/src/sim.rs 和同目录 src/lib.rs,随后 +同步本页自由工具、作者方法及英文镜像。验证两个后端,并保留 + tests/ext/quantum-steps-smoke.mq.md 的作者步骤表行为。 ## 新建 -创建宽度为 `比特数`=1 的态矢量电路。可选 `步骤`=None 表示不预载门表。 | 参数 | 类型 | 说明 | |------|------|------| | 比特数 | number | 线宽 | | 步骤 | any | 可选门表或 None | +创建宽度为 `比特数`=1 的态矢量电路。可选 `步骤`=None 表示不预载门表。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 新电路句柄 | @@ -55,13 +65,14 @@ marqdo call,再调模拟取振幅或概率。 *> quantum_circuit_new qubits=`比特数` steps=`步骤`* ## 哈达玛 -对已有 `电路` 的 `比特`=0 施加哈达玛。 | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路句柄 | | 比特 | number | 目标线 | +对已有 `电路` 的 `比特`=0 施加哈达玛。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | @@ -70,7 +81,6 @@ marqdo call,再调模拟取振幅或概率。 *> quantum_h circuit=`电路` qubit=`比特`* ## 控非 -对 `电路` 从 `控制`=0 到 `目标`=1 施加控非。 | 参数 | 类型 | 说明 | |------|------|------| @@ -78,6 +88,8 @@ marqdo call,再调模拟取振幅或概率。 | 控制 | number | 控制位 | | 目标 | number | 目标位 | +对 `电路` 从 `控制`=0 到 `目标`=1 施加控非。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 更新后的电路 | @@ -86,12 +98,13 @@ marqdo call,再调模拟取振幅或概率。 *> quantum_cx circuit=`电路` control=`控制` target=`目标`* ## 屏障 -在 `电路` 上记录可视化屏障(不改态)。 | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路句柄 | +在 `电路` 上记录可视化屏障(不改态)。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 带屏障的电路 | @@ -100,13 +113,14 @@ marqdo call,再调模拟取振幅或概率。 *> quantum_barrier circuit=`电路`* ## 测量标记 -为后续运行在 `电路` 上标记计算基读出。`比特`=None 表示全部线。不坍缩理想态。 | 参数 | 类型 | 说明 | |------|------|------| | 电路 | any | 电路句柄 | | 比特 | any | 线列表或 None | +为后续运行在 `电路` 上标记计算基读出。`比特`=None 表示全部线。不坍缩理想态。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 带测量标记的电路 | @@ -114,255 +128,684 @@ marqdo call,再调模拟取振幅或概率。 > 能力.加载 *> quantum_measure circuit=`电路` qubits=`比特`* +## 泡利X + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0。 + +对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_x circuit=`电路` qubit=`比特`* + +## 泡利Y + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0。 + +对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_y circuit=`电路` qubit=`比特`* + +## 泡利Z + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0。 + +对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_z circuit=`电路` qubit=`比特`* + +## 相位S + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0。 + +对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_s circuit=`电路` qubit=`比特`* + +## 相位T + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0。 + +对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_t circuit=`电路` qubit=`比特`* + +## 单位 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0。 + +对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_i circuit=`电路` qubit=`比特`* + +## 绕X + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | +| 参数 | number | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0, `参数`。 + +绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_rx circuit=`电路` qubit=`比特` theta=`参数`* + +## 绕Y + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | +| 参数 | number | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0, `参数`。 + +绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_ry circuit=`电路` qubit=`比特` theta=`参数`* + +## 绕Z + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特 | any | 默认 0 | +| 参数 | number | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特`=0, `参数`。 + +绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_rz circuit=`电路` qubit=`比特` theta=`参数`* + +## 控相 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 控制 | number | 默认 0 | +| 目标 | number | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`控制`=0, `目标`=1。 + +在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_cz circuit=`电路` control=`控制` target=`目标`* + +## 交换 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 比特甲 | any | 默认 0 | +| 比特乙 | any | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`比特甲`=0, `比特乙`=1。 + +交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_swap circuit=`电路` a=`比特甲` b=`比特乙`* + +## 追加 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 操作 | any | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`操作`。 + +把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_append circuit=`电路` op=`操作`* + +## 施加 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 已有电路;返回新值 | +| 门 | any | 必填 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +输入:`门`, `比特`=0。 + +把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 + +电路输入为 `电路`,返回新值;使用同一会话的 --toget qc 接住它。 + +> 能力.加载 +*> quantum_apply circuit=`电路` gate=`门` qubits=`比特`* # 电路 - + `比特数`=1 - + `步骤`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特数 | number | 默认 1 | +| 步骤 | any | 默认 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特数`=1, `步骤`=None。 状态向量电路,初态为全零。可选步骤表预载门列。方法追加门并返回新句柄,供作者链式写法;智能体更宜用上方 ## 工具配合 marqdo call。测量标记只影响采样,不坍缩概率所用的理想态。 -本构造返回可供链式调用的句柄,与同文件 ## 工具共用能力.加载 路径。作者程序写对象方法链;智能体优先 marqdo call 上方工具。 - > 能力.加载 *> quantum_circuit_new qubits=`比特数` steps=`步骤`* ## 哈达玛 - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加哈达玛,把计算基变成等权叠加,是贝尔态与 GHZ 制备的第一步。返回更新后的电路句柄,便于继续链式写法而不原地突变。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_h circuit=`self` qubit=`比特`* ## 泡利X - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_x circuit=`self` qubit=`比特`* ## 泡利Y - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_y circuit=`self` qubit=`比特`* ## 泡利Z - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_z circuit=`self` qubit=`比特`* ## 相位S - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_s circuit=`self` qubit=`比特`* ## 相位T - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_t circuit=`self` qubit=`比特`* ## 单位 - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0。 对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_i circuit=`self` qubit=`比特`* ## 绕X - + `比特`=0 - + `参数` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | +| 参数 | number | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0, `参数`。 绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_rx circuit=`self` qubit=`比特` theta=`参数`* ## 绕Y - + `比特`=0 - + `参数` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | +| 参数 | number | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0, `参数`。 绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_ry circuit=`self` qubit=`比特` theta=`参数`* ## 绕Z - + `比特`=0 - + `参数` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 0 | +| 参数 | number | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=0, `参数`。 绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_rz circuit=`self` qubit=`比特` theta=`参数`* ## 控非 - + `控制`=0 - + `目标`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 控制 | number | 默认 0 | +| 目标 | number | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`控制`=0, `目标`=1。 从控制位到目标位施加控非。贝尔态与 GHZ 制备中的标准纠缠步骤。返回更新后的电路句柄以便继续链式调用。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_cx circuit=`self` control=`控制` target=`目标`* ## 控相 - + `控制`=0 - + `目标`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 控制 | number | 默认 0 | +| 目标 | number | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`控制`=0, `目标`=1。 在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_cz circuit=`self` control=`控制` target=`目标`* ## 交换 - + `比特甲`=0 - + `比特乙`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特甲 | any | 默认 0 | +| 比特乙 | any | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特甲`=0, `比特乙`=1。 交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_swap circuit=`self` a=`比特甲` b=`比特乙`* ## 屏障 -仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。 *> quantum_barrier circuit=`self`* ## 测量 - + `比特`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特 | any | 默认 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`比特`=None。 为后续运行标记计算基读出线。不坍缩概率所用的理想态。比特=None 表示标记全部线。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_measure circuit=`self` qubits=`比特`* ## 追加 - + `操作` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 操作 | any | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`操作`。 把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_append circuit=`self` op=`操作`* ## 施加 - + `门` - + `比特`=0 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 门 | any | 必填 | +| 比特 | any | 默认 0 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`门`, `比特`=0。 把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_apply circuit=`self` gate=`门` qubits=`比特`* ## 噪声 - + `种类` - + `概率` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 种类 | any | 必填 | +| 概率 | any | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新的电路值,接住返回值以继续 | + +输入:`种类`, `概率`。 附着给定种类与强度的教学噪声,供运行轨迹使用。理想模拟与概率路径按设计会忽略该通道。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_noise circuit=`self` kind=`种类` p=`概率`* ## 模拟 -返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | re、im 振幅列表 | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。 *> quantum_simulate circuit=`self`* ## 态 -返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_state,含 qubits、dim、amplitudes | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。 *> quantum_state circuit=`self`* ## 概率 -基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 基矢标签到理想概率 | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。 *> quantum_probabilities circuit=`self`* ## 运行 - + `次数`=1024 - + `种子`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 次数 | number | 默认 1024 | +| 种子 | number | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 采样信息与 counts | + +输入:`次数`=1024, `种子`=1。 对本电路做计算基采样。默认次数=1024、种子=1,便于复现。若已附着教学噪声则在轨迹中启用。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_run circuit=`self` shots=`次数` seed=`种子`* ## 绘图 - + `路径`=None - + `种类`=circuit - + `比特`=0 - + `主题`=dark + +| 参数 | 类型 | 说明 | +|------|------|------| +| 路径 | any | 默认 None | +| 种类 | any | 默认 circuit | +| 比特 | any | 默认 0 | +| 主题 | any | 默认 dark | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg,含 kind 与 svg | + +输入:`路径`=None, `种类`="circuit", `比特`=0, `主题`="dark"。 绘制电路轨线、概率条、布洛赫或高级密度图种的 SVG。主题为 dark、light、bw。可选路径落盘供 CLI 或 view 嵌入。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特` theme=`主题`* ## 密度 -对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 密度算符句柄 | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。 *> quantum_density_from_state state=`self`* ## 期望 - + `可观测量` + +| 参数 | 类型 | 说明 | +|------|------|------| +| 可观测量 | any | 必填 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 标量观察值 | + +输入:`可观测量`。 在本电路理想密度上计算泡利串(左端=高比特)或矩阵的期望值。忽略教学噪声。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_density_expect density=`self` obs=`可观测量`* ## 施密特 - + `分割`=1 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 分割 | number | 默认 1 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 系数、两侧基与熵 | + +输入:`分割`=1。 对理想态做二分施密特分解。分割为子系统 A 的比特数,从低位起算。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_schmidt state=`self` cut=`分割`* diff --git a/ext/quantum/量子/索引.mq.md b/ext/quantum/量子/索引.mq.md index 0d33b68..8746ac0 100644 --- a/ext/quantum/量子/索引.mq.md +++ b/ext/quantum/量子/索引.mq.md @@ -1,159 +1,244 @@ --- markup: occlusion title: ext/quantum/量子 -description: 量子扩展根 skill。请先读本文件。每个工具用 marqdo call 执行。 +description: 量子库可执行开发手册与实验工具。 import: 态: ext/quantum/量子/态/索引.mq.md - 门: ext/quantum/量子/门/索引.mq.md 电路: ext/quantum/量子/电路/索引.mq.md 模拟: ext/quantum/量子/模拟/索引.mq.md 密度: ext/quantum/量子/密度/索引.mq.md - 可视化: ext/quantum/量子/可视化/索引.mq.md --- -本文件是 Marqdo 量子扩展的中文根 skill。若你是没有其它 Marqdo 上下文的智能体, -请先读「选哪条路」,再按「如何执行任意工具」操作。不要发明 MCP、Python 封装或 -第二套 API。这些文件里的 ## 标题就是工具。 +量子库开发手册:先读本索引,运行一个可核对的实验,再打开负责下一问题的模块。 +本文件既是包的真实程序,也是使用与开发指引。下方可调用标题就是工具,周围叙述解释 +何时、为何使用它们,不需要另一份 skill manifest。 -## 选哪条路 +从可核对的结果开始 -只选一行。不要混用中英工具名或目录树。(下表是叙述,不要写成 Marqdo 分支行。) +以下命令互相独立,不需要会话。贝尔态 00、11 概率应各约 0.5;纠缠分析还返回 +ZZ 关联约 1、约化纯度约 0.5、施密特熵约 ln(2)。以 1e-9 容差比较数值, +不要把浮点 JSON 字符串与字面量 0.5 作精确文本比较。 -| 若你需要 | 这样做 | -|----------|--------| -| 只要贝尔态结果 | 对本文件调用 `贝尔态`(下节命令)。到此结束。 | -| 电路句柄以便继续(画图、噪声、再施门) | 照抄下方「电路模块」里的分步电路再模拟调用。全程同一 `--session`,并用 `--toget qc`。 | -| 英文工具名 | 改开 `ext/quantum/index.mq.md`,并留在英文树。 | +```sh +marqdo call ext/quantum/量子/索引.mq.md 贝尔态 --effects plugin --json +marqdo call ext/quantum/量子/索引.mq.md 纠缠分析 --effects plugin --json +``` -中文路径留在 `ext/quantum/量子/`(本树)。智能体请用 `##` 工具配 -`marqdo call`。各模块文件里的 `# 电路` / `# 门` 对象面向作者程序导入,不是 -默认的智能体路径。 +根据下一问题导航 -*None* +需要继续编辑电路,调用本页贝尔电路并通过会话保存返回值。需要其他初始程序,打开 +[电路](电路/索引.mq.md):新建、哈达玛、泡利X/Y/Z、相位S/T、单位、绕X/Y/Z、 +控非、控相、交换、施加、追加、屏障、测量标记覆盖构造和组合。 -## 如何执行任意工具 +定义具名或公式算符,打开[门](门/索引.mq.md),那里还有矩阵导出与比较。 +观察精确振幅、纯态、概率或含噪采样,打开[模拟](模拟/索引.mq.md)。 +计算张量积、保真度、施密特分割,打开[态](态/索引.mq.md)。混合态、部分迹、 +期望与本征谱在[密度](密度/索引.mq.md),SVG 轨线、概率、布洛赫、qsphere、multibloch 和矩阵图在 +[可视化](可视化/索引.mq.md)。每个子入口都给出完整实验、输入输出约定和开发路线。 -Marqdo 用下面的 shell 命令形状,从 Markdown 文件里运行一个函数。请原样复制, -再替换 FILE、FUNCTION 与参数。 +英文工具见[英文根索引](../index.mq.md)。双语目录共用一个插件并用相同科学期望验证, +选好一棵树后按对应参数名调用。[能力](能力/索引.mq.md)用于诊断插件,不是实验的 +前置手动步骤;日常工具会自行加载。 -调用示例(纯文本): - marqdo call FILE FUNCTION 名=值 名=值 --effects plugin --json +安装与定位源码 -FILE 总是 ext/quantum/量子/ 下的路径,通常以 索引.mq.md 结尾。FUNCTION 是该文件中 ## -标题的精确名字(例如 新建、哈达玛、概率)。嵌套的 ### 用 parent.child 路径。 -本包必须加 --effects plugin,因为模拟器是原生插件;不加会被拒绝。需要机器可读 -结果时加 --json。若要在下一步复用返回值,加 --session 某id 与 --toget 名字 -(或在命令末尾写 toget 名字)。之后参数可用 电路=$名字。插件句柄靠会话日志 -跨进程重建。参数值可以是数字、引号文本、True/False/None、以 [ 或 { 开头的 JSON、 -或 $名字。不要调用 确保插件 或任何 host 星号 API;领域文件会自行加载插件。 +下面示例以当前目录能看见包源码为前提。安装用户把命令第一个文件参数换为实际 +安装路径,默认 ~/.marqdo/ext/quantum/量子/索引.mq.md。包内导入通过扩展搜索根解析。 -验证本包可用的最小命令(无工具参数): +```text +marqdo ext add quantum +marqdo ext list +``` -调用示例(纯文本): - marqdo call ext/quantum/量子/索引.mq.md 贝尔态 --effects plugin --json +在本仓库开发时先构建本地插件。安装过多版本时,将 MARQDO_QUANTUM_PLUGIN 指向 + target/debug/libquantum.so 的绝对路径,其他平台使用对应动态库名。不要把 +MARQDO_EXT 指向仓库 ext 后执行 ext add;安装产物与编辑源码各有自己的位置。 -*None* +```text +source scripts/dev-env.sh +cargo build --locked -p marqdo_plugin_quantum +``` -## 包布局 +理解一次调用 -只打开你需要的模块。每个模块文件本身也是完整 skill,并重复说明如何 marqdo call。 +基本形式为 marqdo call 文件 函数 名=值 --effects plugin --json。函数名取真实可调用 +标题;嵌套工具使用 parent.child。作者对象内读取 self 的标题是实例方法,需要接收者, +命令行直接使用本包自由工具;写作者程序时导入同一模块即可。 -路径 ext/quantum/量子/索引.mq.md 是本根地图与贝尔演示工具。 -路径 ext/quantum/量子/电路/索引.mq.md 造线、施加哈达玛与控非,并定义作者对象「电路」。 -路径 ext/quantum/量子/门/索引.mq.md 用公式写酉门,并构造具名或自定义门。 -路径 ext/quantum/量子/模拟/索引.mq.md 给出振幅、概率与含噪采样。 -路径 ext/quantum/量子/态/索引.mq.md 做张量积、保真度、施密特分解。 -路径 ext/quantum/量子/密度/索引.mq.md 做密度算符与部分迹。 -路径 ext/quantum/量子/可视化/索引.mq.md 画 SVG。 -路径 ext/quantum/量子/能力/索引.mq.md 仅加载插件,供排查用。 +参数支持数字、文本、True/False/None、JSON 列表或映射、会话引用。给文本字面量、JSON 和美元引用 +加 shell 单引号:'名="H"' 保留 CLI 所需的文本引号;'电路=$qc' 才是发送给 Marqdo 的引用;裸写 电路=$qc 会先被 shell +展开。带 --json 时,同时检查退出码与 ok,再读取 result;失败说明不是有效句柄。 -作者程序在 frontmatter 用「导入」引入相同路径,再写 模块.成员。例如导入电路: -ext/quantum/量子/电路/索引.mq.md,然后用 电路.电路 构造对象,或用 电路.新建 供智能体 -marqdo call。 +完整的持久实验 -*None* +以下命令可按顺序执行,都使用 handbook 会话。--toget 只保存当前调用返回值。 +施门保留旧值,所以每步必须接住新电路;不带 --toget 的观察不会覆盖已有绑定。 +最后结果应约 0.5:贝尔整体是纯态,任一单比特子系统却是最大混合态。 -## 电路模块 +```sh +marqdo call ext/quantum/量子/索引.mq.md 贝尔电路 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/密度/索引.mq.md 从态 '态=$qc' --effects plugin --session handbook --toget rho --json +marqdo call ext/quantum/量子/密度/索引.mq.md 部分迹 '密度=$rho' '保留=[0]' --effects plugin --session handbook --toget reduced --json +marqdo call ext/quantum/量子/密度/索引.mq.md 纯度 '密度=$reduced' --effects plugin --session handbook --json +``` -文件路径:ext/quantum/量子/电路/索引.mq.md +会话默认保存在 .marqdo/call-sessions,MARQDO_CALL_SESSION_DIR 可改变目录。 +跨进程插件调用通过 journal 重放。保持会话短小,修改源码或插件版本后换新会话, +重放可能重复绘图输出等插件效果。不要复制某个实现版本的 JSON 来手工伪造句柄。 -需要电路句柄时用本模块。两比特贝尔态典型智能体序列(每行一条 shell 命令): +科学约定与边界 -调用示例(纯文本): - marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=2 --effects plugin --session s1 --toget qc --json - marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 电路=$qc 比特=0 --effects plugin --session s1 --toget qc --json - marqdo call ext/quantum/量子/电路/索引.mq.md 控非 电路=$qc 控制=0 目标=1 --effects plugin --session s1 --toget qc --json +比特 0 在基矢最右位,泡利串最高位在左;角度用弧度。态矢量默认上限 12,比特 +限制可由环境调整但硬上限为 16;密度与施密特上限六比特。施密特 A 占低位分割数, +熵单位为自然对数 nats。 -该文件主要 ## 工具:新建、哈达玛、控非、屏障、测量标记。同文件还有作者对象电路。 +精确模拟、概率、保真度、从电路构造密度都忽略教学噪声。只有运行采样使用已附加的 +bitflip、depolarizing、amplitude_damping 通道。测量标记选择采样线,不坍缩理想态。 +混合矩阵构造只核对厄米性与形状,不保证半正定或迹为 1。实验的科学解释必须遵循 +这些边界,各模块入口提供独立反向校验。 -*None* +用同一份知识写作者程序 -## 门模块 +把以下内容存为 bell.mq.md,执行 marqdo run bell.mq.md。步骤表就是线路规格, +程序打印的两个权重应各约 0.5。frontmatter 导入已有模块;GFM 记录表首列为 @,逗号分隔的线号依次表示控制与目标。 +公式也可以绑定后交给门的自定义工具或作者构造器,不必再翻译为另一套结构。 -文件路径:ext/quantum/量子/门/索引.mq.md +```marqdo +--- +markup: occlusion +导入: + 电路: ext/quantum/量子/电路/索引.mq.md +--- -调用示例(纯文本): - marqdo call ext/quantum/量子/门/索引.mq.md 哈达玛 --effects plugin --json +# main -主要 ## 工具:哈达玛、泡利X、泡利Z、控非门、自定义、匹配。 +`步骤` = -*None* +| @ | 门 | 比特 | +|---|----|------| +| 1 | H | 0 | +| 2 | CX | "0,1" | -## 模拟模块 +**qc = 电路.电路 比特数=2 步骤=`步骤`** +**p = > `qc`.概率** +**p00 = 取(p, "00")** +**p11 = 取(p, "11")** +> 打印 内容=`p00` +> 打印 内容=`p11` +``` -文件路径:ext/quantum/量子/模拟/索引.mq.md +开发时复用现有能力 -调用示例(纯文本): - marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 电路=$qc --effects plugin --session s1 --json +新增实验通常只需在本索引组合模块,并把问题、输入、期望和局限写在步骤旁。 +下方纠缠分析展示这种编排。新增酉算符通常使用门的自定义工具,无需新增 ABI。 -主要 ## 工具:模拟、态、概率、运行、噪声。 +确实需要新原语时,先读归属模块的开发路线,再增加自由工具、保留作者方法,并同步 +英文镜像。数值演化位于 plugins/quantum/src/sim.rs,代数在 linalg.rs,SVG 在 draw.rs, +ABI 注册在同目录 src/lib.rs。插件加载只经过能力边界。新增文件还需更新 +src/ext_cli.rs 的包文件列表,让安装用户能得到它。 -*None* +参数默认值写进叙述,参数契约紧跟标题,返回契约也必须放在首条执行语句之前。 +当前 extract_function_contract 只读取该区域,cap.load 或能力.加载 之后的返回表只是 +说明而非生效契约。类型使用现有 number/text/bool/any;句柄的来源与形状用叙述交代, +不要声称新增了领域类型检查器。把具体意图与操作交错书写,不能靠重复套话凑叙述比例。 -## 态模块 +普通说明节名保持纯叙述:## 会生成真实可调用符号。工具树中只出现可执行工具和 +对象方法。导航使用源码链接与已有 knowledge inspect/resolve,稳定符号由编译器 +产生,不手工维护第二份工具目录。 -文件路径:ext/quantum/量子/态/索引.mq.md +```text +marqdo knowledge ext/quantum --json inspect 纠缠分析 +marqdo check --narrative-ratio ext/quantum/量子/索引.mq.md +cargo test --locked --test quantum_handbook +cargo test --locked --test call_cli quantum_ +cargo test --locked --test gold ext_quantum -- --test-threads=1 +``` -调用示例(纯文本): - marqdo call ext/quantum/量子/态/索引.mq.md 保真度 a=$psi b=$phi --effects plugin --json +手册测试直接执行双语文档的 sh 围栏与作者程序,对照独立科学期望,并验证 Tree 与 +Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高也不能替代。既有量子 +金样继续约束噪声、公式、SVG 与对象方法,验证不需要网络或 LLM。 +本轮采用 next/010–012 中由 call 自然派生的简洁能力;更复杂的自我改进智能体和 +持久交互分支仍是未来规划,不作为当前量子库已经具备的承诺。 -主要 ## 工具:张量积、保真度、施密特分解。 +失败后如何恢复 -*None* +插件缺失:检查能力入口,构建或安装 quantum,再重试最小贝尔命令。会话绑定不存在: +使用同一个会话名,先重跑生产者,再运行消费者。设置噪声后理想概率未变:用运行 +观察含噪采样。维数或形状失败:按上面的边界修正输入,不要静默缩小科学问题。 +错误信封不能当作空的成功结果继续传递。 -## 密度模块 - -文件路径:ext/quantum/量子/密度/索引.mq.md - -调用示例(纯文本): - marqdo call ext/quantum/量子/密度/索引.mq.md 从态 态=$qc --effects plugin --toget rho --json - -*None* - -## 可视化模块 - -文件路径:ext/quantum/量子/可视化/索引.mq.md - -调用示例(纯文本): - marqdo call ext/quantum/量子/可视化/索引.mq.md 画电路 电路=$qc 路径="bell.svg" --effects plugin --session s1 --json - -*None* - -## 贝尔态 - -本索引上的一键编排工具,无参数。在比特 0 上哈达玛再控非 0→1,返回理想基矢概率。 -只要演示结果时用本工具;需要中间句柄时用上面的分步 call。 +## 贝尔电路 | 返回 | 类型 | 说明 | |------|------|------| -| result | any | 基矢标签到概率的映射 | +| result | any | 两比特电路,可交给模拟、密度或绘图 | -精确命令: +无参数制备贝尔 Φ+ 线路,初态为 00。先在最低位制造等权叠加, +再由该位控制另一位翻转,把振幅关联到 00 和 11。 +工具返回线路而非概率,便于继续施门、设置噪声或独立验证纠缠。 +每一步接住新电路值,原值不被隐式修改。 -调用示例(纯文本): - marqdo call ext/quantum/量子/索引.mq.md 贝尔态 --effects plugin --json +**qc = 电路.新建 比特数=2 步骤=None** -**qc = > 电路.新建 比特数=2 步骤=None** -**qc = > 电路.哈达玛 电路=`qc` 比特=0** -**qc = > 电路.控非 电路=`qc` 控制=0 目标=1** +先让最低位具有两条等权路径,再把路径信息传播给第二条线。 + +**qc = 电路.哈达玛 电路=`qc` 比特=0** +*> 电路.控非 电路=`qc` 控制=0 目标=1* + +## 贝尔态 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 基矢概率映射;00、11 各约 0.5 | + +无参数演示工具,复用本页贝尔电路的真实制备步骤,只返回理想概率。 +00 和 11 各约一半,其余基矢为零;这是计算基关联,单靠概率还不能证明纠缠, +因此需要纠缠证据时继续调用本页纠缠分析,对照约化纯度与 ZZ 期望。 + +**qc = > 贝尔电路** *> 模拟.概率 电路=`qc`* + +## 纠缠分析 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | probabilities、purity、reduced_purity、zz、schmidt;不写文件 | + +无参数实验,从同一条贝尔线路交叉观察整体、子系统与关联。 +字段保留插件的科学命名,双语入口具有相同结果形状,便于机器比较。 +这是一份可复用实验配方,调用者无需了解原生导出名,也不需要保存中间会话。 +整体纯度应为 1,约化纯度应为 0.5,ZZ 应为 1,施密特熵为 ln(2)。 +所有数值按 1e-9 容差核对;纯态概率与密度构造均使用理想演化。 + +**qc = > 贝尔电路** +**probs = 模拟.概率 电路=`qc`** + +先构造整体密度并计算纯度。整体纯不意味着每个局部也纯, +接着只保留最低位,检查丢弃另一个比特后出现的混合性。 + +**rho = 密度.从态 态=`qc`** +**whole = 密度.纯度 密度=`rho`** +`kept` = + +| 比特 | +|------| +| 0 | + +**reduced = 密度.部分迹 密度=`rho` 保留=`kept`** +**local = 密度.纯度 密度=`reduced`** + +ZZ 测量关联,不是单独的纠缠判据。施密特分解独立给出纯态两侧的 +系数与熵;联合这些观察才能解释为何这是贝尔纯态而非经典概率混合。 +返回表将各观察保留原值,便于调用者自行检查,而不是输出一个隐藏阈值的通过标签。 + +**correlation = 密度.期望 密度=`rho` 可观测量="ZZ"** +**split = 态.施密特分解 态=`qc` 分割=1** + +`report` = + +| probabilities | purity | reduced_purity | zz | schmidt | +|---------------|--------|----------------|----|---------| +| `probs` | `whole` | `local` | `correlation` | `split` | + +*report* diff --git a/ext/quantum/量子/能力/索引.mq.md b/ext/quantum/量子/能力/索引.mq.md index 4173cff..bffcb13 100644 --- a/ext/quantum/量子/能力/索引.mq.md +++ b/ext/quantum/量子/能力/索引.mq.md @@ -7,17 +7,22 @@ import: sys: lib/sys.mq.md --- -本文件仍是 skill 与工具面。它只负责加载原生 quantum 插件。日常作者程序与智能体 -应调用电路、门、模拟等模块(它们会替你加载)。仅在排查插件是否安装时打开本页。 +原生能力边界:诊断插件发现后,回到领域模块继续工作。 -## 给智能体 +本页定位并加载 ABI v2 量子动态库。领域工具自行调用加载,不需要每次先手动初始化。 +英文 _capability 是此边界的等价语言入口,领域代码不应再实现第二套加载过程。 -若你只拿到本文件,请用下面命令检查插件。日常工作请改调电路或模拟模块。 +```sh +marqdo call ext/quantum/量子/能力/索引.mq.md 加载 --effects plugin --json +``` -调用示例(纯文本): - marqdo call ext/quantum/量子/能力/索引.mq.md 加载 --effects plugin --json +成功返回 null。缺失动态库会提示安装并以非零状态退出;本工具使用 sys.exit,所以 +要同时检查进程状态,不能假定所有失败都有 JSON 信封。安装用 marqdo ext add quantum, +源码开发用 cargo build -p marqdo_plugin_quantum。MARQDO_QUANTUM_PLUGIN 可指定 +开发动态库的绝对路径。 -*None* +仅能力边界导入 lib/plugin,不向领域代码新增加载器或 host_*。修改发现流程时, +同时验证双语根工具与 tests/call_cli.rs,再回到[电路](../电路/索引.mq.md)。 ## 加载 diff --git a/ext/quantum/量子/门/索引.mq.md b/ext/quantum/量子/门/索引.mq.md index 81a06f5..9984115 100644 --- a/ext/quantum/量子/门/索引.mq.md +++ b/ext/quantum/量子/门/索引.mq.md @@ -6,20 +6,38 @@ import: 能力: ext/quantum/量子/能力/索引.mq.md --- -门是作用在一个或多个比特上的酉变换。本 skill 先写矩阵含义,再构造门句柄。 -电路施加门;本页定义门是什么。 +量子门:先定义算符,再选择它作用的线路。 -## 给智能体 -若你只拿到本文件,用 marqdo call 调用 ## 工具,必须加 --effects plugin。 +具名工具支持 I、X、Y、Z、H、S、T、Rx、Ry、Rz、CX、CZ、SWAP。旋转参数为弧度。 +自定义门必须是 2^k 阶方阵,并满足 U†U = I,构造容差为 1e-6。元素可为实数或 +含 re、im 的复数映射。JSON 与 Markdown 公式绑定使用同一个构造器。 -调用示例(纯文本): - marqdo call ext/quantum/量子/门/索引.mq.md 哈达玛 --effects plugin --json +完整的自定义门实验 -作者程序也可使用本文件中的对象「门」。 +下面矩阵交换零与一,匹配工具应返回 true,最终基矢 1 的概率应为 1。 +仅构造门不会改变电路;必须调用[电路模块](../电路/索引.mq.md)的施加工具。 +所有引用保存在同一会话,不需要手写或解析插件句柄。 -*None* +```sh +marqdo call ext/quantum/量子/门/索引.mq.md 自定义 '矩阵=[[0,1],[1,0]]' '名="X-demo"' --effects plugin --session handbook --toget u --json +marqdo call ext/quantum/量子/门/索引.mq.md 匹配 '门=$u' '矩阵=[[0,1],[1,0]]' --effects plugin --session handbook --json +marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=1 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/电路/索引.mq.md 施加 '电路=$qc' '门=$u' 比特=0 --effects plugin --session handbook --toget qc --json +marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects plugin --session handbook --json +``` + +哈达玛、泡利X、泡利Z、控非门提供常用常量,其余内置门使用具名;矩阵工具导出 +条目,匹配用于核对讲义公式与实现。[可视化](../可视化/索引.mq.md)的画门支持 +门符号与矩阵热图。需要纠缠操作时,优先使用控制、目标明确的电路控非工具。 + +开发路线 + +新增用户酉矩阵只需自定义与独立期望矩阵,不必修改 Rust 或 ABI。新增内置门时, +先更新 plugins/quantum/src/sim.rs::named_gate_matrix 及数值测试,再同步中英入口。 +保留 tests/ext/quantum-custom-gate-smoke.mq.md 中公式直接构造哈达玛门的例子。 ## 哈达玛 + 哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 本工具无参数。 @@ -32,6 +50,7 @@ import: *> quantum_gate_new name="H" theta=None matrix=None* ## 泡利X + 泡利 X 是比特翻转门。 本工具无参数。 @@ -44,6 +63,7 @@ import: *> quantum_gate_new name="X" theta=None matrix=None* ## 泡利Z + 泡利 Z 给 ket-one 乘上负号相位。 本工具无参数。 @@ -56,6 +76,7 @@ import: *> quantum_gate_new name="Z" theta=None matrix=None* ## 控非门 + 两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 本工具无参数。 @@ -68,13 +89,14 @@ import: *> quantum_gate_new name="CX" theta=None matrix=None* ## 自定义 -用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。 | 参数 | 类型 | 说明 | |------|------|------| | 矩阵 | any | 酉矩阵公式或列表 | | 名 | text | 可选标签,默认 U | +用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。 + | 返回 | 类型 | 说明 | |------|------|------| | result | any | 自定义门句柄 | @@ -83,7 +105,6 @@ import: *> quantum_gate_new name=`名` theta=None matrix=`矩阵`* ## 匹配 -检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。 | 参数 | 类型 | 说明 | |------|------|------| @@ -91,6 +112,8 @@ import: | 矩阵 | any | 期望酉矩阵 | | 容差 | number | 绝对容差 | +检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。 + | 返回 | 类型 | 说明 | |------|------|------| | result | bool | 匹配则为 True | @@ -98,43 +121,98 @@ import: > 能力.加载 *> quantum_gate_matches_matrix gate=`门` matrix=`矩阵` tol=`容差`* +## 具名 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 名 | text | 内置门名 | +| 参数 | any | 旋转角或 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 可交给施加工具的门句柄 | + +构造内置门 `名`="H";可选 `参数`=None,Rx、Ry、Rz 必须给出弧度角。 +返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。 + +> 能力.加载 +*> quantum_gate_new name=`名` theta=`参数` matrix=None* + +## 矩阵 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 门 | any | 门句柄 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 复数矩阵条目,每项含 re 与 im | + +导出 `门` 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较; +本工具仅观察算符,不改变句柄,也不把门应用到任何电路。 + +> 能力.加载 +*> quantum_gate_matrix gate=`门`* # 门 - + `名`=None - + `参数`=None - + `矩阵`=None + +| 参数 | 类型 | 说明 | +|------|------|------| +| 名 | any | 默认 None | +| 参数 | number | 默认 None | +| 矩阵 | any | 默认 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 可交给施加工具的门句柄 | + +输入:`名`=None, `参数`=None, `矩阵`=None。 具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。 -本构造返回可供链式调用的句柄,与同文件 ## 工具共用能力.加载 路径。作者程序写对象方法链;智能体优先 marqdo call 上方工具。 - > 能力.加载 *> quantum_gate_new name=`名` theta=`参数` matrix=`矩阵`* ## 矩阵 -返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。 +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 复数矩阵条目,每项含 re 与 im | -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 +返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。 *> quantum_gate_matrix gate=`self`* ## 匹配矩阵 - + `矩阵` - + `容差`=0.000000001 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 矩阵 | any | 必填 | +| 容差 | any | 默认 0.000000001 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | bool | 容差内匹配 | + +输入:`矩阵`, `容差`=0.000000001。 检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_gate_matches_matrix gate=`self` matrix=`矩阵` tol=`容差`* ## 绘图 - + `路径`=None - + `种类`=gate + +| 参数 | 类型 | 说明 | +|------|------|------| +| 路径 | any | 默认 None | +| 种类 | any | 默认 gate | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | quantum_svg,含 kind 与 svg | + +输入:`路径`=None, `种类`="gate"。 绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。 -本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 - *> quantum_gate_draw gate=`self` path=`路径` kind=`种类`* diff --git a/tests/README.md b/tests/README.md index 65600df..e198d86 100644 --- a/tests/README.md +++ b/tests/README.md @@ -8,6 +8,7 @@ | [`keywords/`](keywords/) | `print`、布尔与 `and`/`or`/`not` | | [`markup-v03/`](markup-v03/) | **Markup v0.3 草案金样例**(`#[ignore]` 至旗标落地;见目录 README) | | [`errors/`](errors/) | 期望失败(诊断文案) | +| [`quantum_handbook.rs`](quantum_handbook.rs) | 直接执行 Quantum 双语手册围栏,校验科学期望、真实契约及双后端;先构建量子插件 | | [`gold.rs`](gold.rs) | 集成测试:跑上述夹具并比对 stdout / stderr | ```bash diff --git a/tests/quantum_handbook.rs b/tests/quantum_handbook.rs new file mode 100644 index 0000000..f678050 --- /dev/null +++ b/tests/quantum_handbook.rs @@ -0,0 +1,538 @@ +//! The source documents are the examples under test, not a copied command catalog. +use serde_json::Value; +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, +}; + +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} +fn bin() -> &'static str { + env!("CARGO_BIN_EXE_marqdo") +} + +struct Scratch(PathBuf); +impl Scratch { + fn new(label: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "mq-quantum-handbook-{label}-{}", + std::process::id() + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn files(dir: &Path, out: &mut Vec) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + files(&path, out); + } else if path.to_string_lossy().ends_with(".mq.md") { + out.push(path); + } + } +} +fn fences(source: &str, language: &str) -> Vec { + let open = format!("```{language}"); + let mut current = None; + let mut result = Vec::new(); + for line in source.lines() { + if line == open { + current = Some(String::new()); + } else if line == "```" { + if let Some(block) = current.take() { + result.push(block); + } + } else if let Some(block) = current.as_mut() { + block.push_str(line); + block.push('\n'); + } + } + assert!(current.is_none(), "unclosed {language} fence"); + result +} +fn near(v: &Value, expected: f64) { + let actual = v + .as_f64() + .unwrap_or_else(|| panic!("expected number, got {v}")); + assert!((actual - expected).abs() < 1e-9, "{actual} != {expected}"); +} +fn bell(v: &Value) { + near(&v["00"], 0.5); + near(&v["11"], 0.5); + near( + &Value::from( + v.as_object() + .unwrap() + .values() + .map(|v| v.as_f64().unwrap()) + .sum::(), + ), + 1.0, + ); +} +fn report(v: &Value) { + bell(&v["probabilities"]); + near(&v["purity"], 1.0); + near(&v["reduced_purity"], 0.5); + near(&v["zz"], 1.0); + near(&v["schmidt"]["entropy"], 2.0_f64.ln()); + for coefficient in v["schmidt"]["coeffs"].as_array().unwrap() { + near(coefficient, 0.5_f64.sqrt()); + } +} +fn command(scratch: &Path) -> Command { + let mut command = Command::new(bin()); + command + .current_dir(root()) + .env("MARQDO_CALL_SESSION_DIR", scratch) + .env( + "MARQDO_QUANTUM_PLUGIN", + root() + .join("target/debug") + .join(if cfg!(target_os = "macos") { + "libquantum.dylib" + } else if cfg!(windows) { + "quantum.dll" + } else { + "libquantum.so" + }), + ) + .env("MARQDO_EXT", root().join("ext")) + .env("MARQDO_LIB", root().join("lib")); + command +} +fn call(scratch: &Path, backend: &str, file: &str, function: &str, args: &[&str]) -> Value { + let output = command(scratch) + .args([ + "call", + file, + function, + "--effects", + "plugin", + "--backend", + backend, + "--session", + "handbook", + "--json", + ]) + .args(args) + .output() + .unwrap(); + assert!( + output.status.success(), + "{file} {function}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let body: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(body["ok"], true, "{body}"); + body["result"].clone() +} + +#[test] +fn handbook_shell_and_author_examples_on_both_backends() { + let scratch = Scratch::new("examples"); + let mut paths = Vec::new(); + files(&root().join("ext/quantum"), &mut paths); + paths.sort(); + assert_eq!(paths.len(), 16); + let mut shell_calls = 0; + let mut author_examples = 0; + for (index, path) in paths.iter().enumerate() { + let source = fs::read_to_string(path).unwrap(); + let module = path + .parent() + .unwrap() + .file_name() + .unwrap() + .to_str() + .unwrap(); + let examples = fences(&source, "sh"); + assert!( + !examples.is_empty(), + "{} needs a standalone experiment", + path.display() + ); + let mut reference = Vec::new(); + for backend in ["tree", "bytecode"] { + let session_dir = scratch.0.join(format!("{index}-{backend}")); + fs::create_dir_all(&session_dir).unwrap(); + let mut observed = Vec::new(); + for (block_index, block) in examples.iter().enumerate() { + let mut results = Vec::new(); + for line in block.lines().filter(|line| !line.trim().is_empty()) { + assert!( + line.starts_with("marqdo call "), + "unsupported handbook command: {line}" + ); + // Use the actual shell: invoking Command with argv would miss broken quoting. + let invocation = line.replacen( + "marqdo call ", + &format!("\"{}\" call --backend {backend} ", bin()), + 1, + ); + let cmd = command(&session_dir); + // Keep the same isolated environment as non-shell calls. + let mut shell = Command::new("bash"); + shell + .env_remove("BASH_ENV") + .current_dir(root()) + .envs(cmd.get_envs().map(|(k, v)| (k, v.unwrap()))) + .args(["-euc", &invocation]); + let output = shell.output().unwrap(); + assert!( + output.status.success(), + "{} [{backend}] {line}\n{}\n{}", + path.display(), + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let body: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(body["ok"], true, "{}: {body}", path.display()); + results.push(body["result"].clone()); + shell_calls += 1; + } + let last = results.last().unwrap(); + match module { + "quantum" | "量子" => { + if block_index == 0 { + bell(&results[0]); + report(&results[1]); + } else { + near(last, 0.5); + } + } + "circuit" | "电路" => bell(last), + "gate" | "门" => { + assert_eq!(results[1], true); + near(&last["1"], 1.0); + } + "simulate" | "模拟" => { + near(&results[3]["1"], 1.0); + assert_eq!(last["counts"]["0"], 32); + } + "state" | "态" => { + assert_eq!(results[2]["qubits"], 2); + near(&results[3], 1.0); + near(&last["entropy"], 0.0); + } + "density" | "密度" => { + near(&results[1], 0.5); + near(&results[2], 0.0); + for v in last["eigenvalues"].as_array().unwrap() { + near(v, 0.5); + } + } + "viz" | "可视化" => { + for (value, kind) in + results[2..].iter().zip(["probs", "qsphere", "multibloch"]) + { + assert_eq!(value["kind"], kind); + assert!(value["svg"].as_str().unwrap().starts_with(" assert!(last.is_null()), + other => panic!("unverified module {other}"), + } + observed.extend(results); + } + if backend == "tree" { + reference = observed; + } else { + assert_eq!(observed, reference, "backend drift in {}", path.display()); + } + for (block_index, block) in fences(&source, "marqdo").iter().enumerate() { + let file = scratch + .0 + .join(format!("author-{index}-{block_index}.mq.md")); + fs::write(&file, block).unwrap(); + let output = command(&session_dir) + .args(["run", file.to_str().unwrap(), "--backend", backend]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{} author [{backend}]: {}", + path.display(), + String::from_utf8_lossy(&output.stderr) + ); + let printed = String::from_utf8(output.stdout).unwrap(); + let weights: Vec = printed.lines().map(|line| line.parse().unwrap()).collect(); + assert_eq!(weights.len(), 2, "{}: {printed}", path.display()); + for weight in weights { + near(&Value::from(weight), 0.5); + } + author_examples += 1; + } + } + } + eprintln!("Executed {shell_calls} shell calls directly from the handbooks"); + assert_eq!(author_examples, 4); +} + +#[test] +fn every_callable_has_a_real_contract_and_no_prose_placeholder() { + fn check(functions: &[marqdo::ast::Function], path: &Path) { + for function in functions { + let contract = function.contract.as_ref().unwrap_or_else(|| { + panic!("{}: {} missing contract", path.display(), function.name) + }); + assert!( + contract.returns.is_some(), + "{}: {} missing return contract", + path.display(), + function.name + ); + assert_eq!( + contract.params.len(), + function.params.len(), + "{}: {} parameter drift", + path.display(), + function.name + ); + check(&function.children, path); + } + } + let mut paths = Vec::new(); + files(&root().join("ext/quantum"), &mut paths); + for path in paths { + let module = marqdo::load::load_module(&path).unwrap(); + let diagnostics = marqdo::check::check_path(&path).unwrap(); + assert!( + diagnostics.is_empty(), + "{}: {diagnostics:?}", + path.display() + ); + assert!( + marqdo::narrative_ratio::check_file(&path) + .unwrap() + .is_empty(), + "{} narration ratio", + path.display() + ); + check(&module.functions, &path); + if matches!( + path.parent() + .unwrap() + .file_name() + .unwrap() + .to_str() + .unwrap(), + "quantum" | "量子" + ) { + assert_eq!( + module.functions.len(), + 3, + "root headings must be executable tools" + ); + } + } +} + +#[test] +fn free_tools_cover_gate_composition_and_matrix_observation() { + let scratch = Scratch::new("tools"); + for backend in ["tree", "bytecode"] { + for zh in [false, true] { + let circuit = if zh { + "ext/quantum/量子/电路/索引.mq.md" + } else { + "ext/quantum/circuit/index.mq.md" + }; + let gate = if zh { + "ext/quantum/量子/门/索引.mq.md" + } else { + "ext/quantum/gate/index.mq.md" + }; + let density = if zh { + "ext/quantum/量子/密度/索引.mq.md" + } else { + "ext/quantum/density/index.mq.md" + }; + call( + &scratch.0, + backend, + circuit, + if zh { "新建" } else { "new" }, + &["--toget", "qc"], + ); + call( + &scratch.0, + backend, + gate, + if zh { "具名" } else { "named" }, + &[ + if zh { "名=\"Rx\"" } else { "name=\"Rx\"" }, + if zh { + "参数=3.141592653589793" + } else { + "theta=3.141592653589793" + }, + "--toget", + "u", + ], + ); + let m = call( + &scratch.0, + backend, + gate, + if zh { "矩阵" } else { "matrix" }, + &[if zh { "门=$u" } else { "gate=$u" }], + ); + near(&m[0][0]["re"], 0.0); + near(&m[0][1]["im"], -1.0); + call( + &scratch.0, + backend, + circuit, + if zh { "施加" } else { "apply" }, + &[ + if zh { "电路=$qc" } else { "circuit=$qc" }, + if zh { "门=$u" } else { "gate=$u" }, + "--toget", + "qc", + ], + ); + call( + &scratch.0, + backend, + circuit, + if zh { "新建" } else { "new" }, + &["--toget", "fragment"], + ); + call( + &scratch.0, + backend, + circuit, + if zh { "绕X" } else { "rx" }, + &[ + if zh { + "电路=$fragment" + } else { + "circuit=$fragment" + }, + if zh { + "参数=3.141592653589793" + } else { + "theta=3.141592653589793" + }, + "--toget", + "fragment", + ], + ); + call( + &scratch.0, + backend, + circuit, + if zh { "追加" } else { "append" }, + &[ + if zh { "电路=$qc" } else { "circuit=$qc" }, + if zh { + "操作=$fragment" + } else { + "op=$fragment" + }, + "--toget", + "qc", + ], + ); + call( + &scratch.0, + backend, + density, + if zh { "从态" } else { "from_state" }, + &[if zh { "态=$qc" } else { "state=$qc" }, "--toget", "rho"], + ); + let rho = call( + &scratch.0, + backend, + density, + if zh { "矩阵" } else { "matrix" }, + &[if zh { "密度=$rho" } else { "density=$rho" }], + ); + near(&rho[0][0]["re"], 1.0); + near(&rho[1][1]["re"], 0.0); + } + } +} + +#[test] +fn drawing_returns_svg_in_call_and_saves_files_in_run() { + let scratch = Scratch::new("plot-host"); + for backend in ["tree", "bytecode"] { + call( + &scratch.0, + backend, + "ext/quantum/index.mq.md", + "bell_circuit", + &["--toget", "qc"], + ); + let forbidden = scratch.0.join(format!("denied-{backend}.svg")); + let path_arg = format!("path=\"{}\"", forbidden.display()); + let output = command(&scratch.0) + .args([ + "call", + "ext/quantum/viz/index.mq.md", + "draw_probs", + "circuit=$qc", + &path_arg, + "--effects", + "plugin", + "--backend", + backend, + "--session", + "handbook", + "--json", + ]) + .output() + .unwrap(); + assert!(!output.status.success()); + let body: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(body["ok"], false); + assert!( + body["error"]["message"] + .as_str() + .unwrap() + .contains("write_text denied"), + "{body}" + ); + assert!(!forbidden.exists()); + + for zh in [false, true] { + let file = scratch.0.join(format!("save-{backend}-{zh}.mq.md")); + let image = format!("saved-{backend}-{zh}.svg"); + let import = if zh { + "电路: ext/quantum/量子/电路/索引.mq.md" + } else { + "circuit: ext/quantum/circuit/index.mq.md" + }; + let constructor = if zh { + "电路.电路 比特数=1" + } else { + "circuit.circuit qubits=1" + }; + let draw = if zh { "绘图 路径" } else { "draw path" }; + fs::write(&file, format!("---\nmarkup: occlusion\nimport:\n {import}\n---\n\n# main\n\n**qc = {constructor}**\n**img = > `qc`.{draw}=\"{image}\"**\n")).unwrap(); + let output = command(&scratch.0) + .args(["run", file.to_str().unwrap(), "--backend", backend]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let svg = fs::read_to_string(scratch.0.join(image)).unwrap(); + assert!(svg.starts_with("")); + } + } +}