2 """Validation: bridge micro-validation matrix. 4 Validates the supported VQE-side density bridge on deterministic 1 to 3 qubit 5 microcases. The goal is not observable-threshold closure, but proof that the 6 required generated-`HEA` bridge surface lowers cleanly into the supported 7 `NoisyCircuit` vocabulary and remains execution-ready on small cases. 10 python benchmarks/density_matrix/bridge_scope/bridge_validation.py 13 from __future__
import annotations
19 from pathlib
import Path
23 REPO_ROOT = Path(__file__).resolve().parents[3]
24 if str(REPO_ROOT)
not in sys.path:
25 sys.path.insert(0, str(REPO_ROOT))
27 from examples.VQE.shot_noise_measurement
import generate_zz_xx_hamiltonian
28 from benchmarks.density_matrix.workflow_evidence.exact_density_vqe_validation
import (
34 build_software_metadata,
35 build_reference_bridge_metadata,
36 build_optimizer_config,
37 build_hamiltonian_metadata,
38 build_initial_parameters,
39 build_open_chain_topology,
41 from squander
import Variational_Quantum_Eigensolver
42 from squander.partitioning.noisy_planner
import (
44 PLANNER_OP_KIND_NOISE,
47 SUITE_NAME =
"bridge_micro_validation" 48 ARTIFACT_FILENAME =
"bridge_micro_validation_bundle.json" 49 ARTIFACT_CORE_FIELDS = (
59 MANDATORY_BRIDGE_MICROCASES = (
61 "case_name":
"bridge_1q_local_depolarizing_after_u3",
63 "purpose":
"Verify the generated-HEA bridge lowers a required U3-only microcase with local depolarizing noise.",
64 "required_gate_families": [
"U3"],
65 "required_noise_models": [
"local_depolarizing"],
68 "channel":
"local_depolarizing",
70 "after_gate_index": 0,
74 "requires_cnot":
False,
77 "case_name":
"bridge_1q_amplitude_damping_after_u3",
79 "purpose":
"Verify the generated-HEA bridge lowers a required U3-only microcase with amplitude damping noise.",
80 "required_gate_families": [
"U3"],
81 "required_noise_models": [
"amplitude_damping"],
84 "channel":
"amplitude_damping",
86 "after_gate_index": 0,
90 "requires_cnot":
False,
93 "case_name":
"bridge_1q_phase_damping_after_u3",
95 "purpose":
"Verify the generated-HEA bridge lowers a required U3-only microcase with phase damping noise.",
96 "required_gate_families": [
"U3"],
97 "required_noise_models": [
"phase_damping"],
100 "channel":
"phase_damping",
102 "after_gate_index": 0,
106 "requires_cnot":
False,
109 "case_name":
"bridge_2q_cnot_with_local_depolarizing",
111 "purpose":
"Verify the required CNOT bridge slice lowers cleanly on a 2-qubit anchor microcase.",
112 "required_gate_families": [
"U3",
"CNOT"],
113 "required_noise_models": [
"local_depolarizing"],
116 "channel":
"local_depolarizing",
118 "after_gate_index": 2,
122 "requires_cnot":
True,
125 "case_name":
"bridge_3q_mixed_local_noise_sequence",
127 "purpose":
"Verify mixed required local-noise insertion remains ordered and auditable on a 3-qubit bridge microcase.",
128 "required_gate_families": [
"U3",
"CNOT"],
129 "required_noise_models": [
130 "local_depolarizing",
136 "channel":
"local_depolarizing",
138 "after_gate_index": 0,
142 "channel":
"amplitude_damping",
144 "after_gate_index": 1,
148 "channel":
"phase_damping",
150 "after_gate_index": 2,
154 "requires_cnot":
True,
161 "source_type":
"generated_hea",
162 "required_gate_families": [
"U3",
"CNOT"],
163 "required_noise_models": [
164 "local_depolarizing",
168 "microcase_qubits": [1, 2, 3],
169 "required_pass_rate": 1.0,
170 "canonical_bridge_fields": [
171 "bridge_source_type",
172 "bridge_parameter_count",
173 "bridge_operation_count",
175 "bridge_noise_count",
191 vqe = Variational_Quantum_Eigensolver(
195 backend=PRIMARY_BACKEND,
196 density_noise=density_noise,
198 vqe.set_Ansatz(DEFAULT_ANSATZ)
199 vqe.Generate_Circuit(layers=DEFAULT_LAYERS, inner_blocks=DEFAULT_INNER_BLOCKS)
201 vqe.set_Optimized_Parameters(parameters)
202 return vqe, hamiltonian, topology, parameters
206 base_circuit = vqe.get_Qiskit_Circuit()
208 for noise_spec
in vqe.density_noise:
209 noise_by_gate.setdefault(noise_spec[
"after_gate_index"], []).append(noise_spec)
213 for gate_index, instruction
in enumerate(base_circuit.data):
214 qubit_indices = [base_circuit.find_bit(qubit).index
for qubit
in instruction.qubits]
215 gate_name = instruction.operation.name
220 "index": len(expected),
221 "kind": PLANNER_OP_KIND_GATE,
224 "source_gate_index": gate_index,
225 "target_qbit": qubit_indices[0],
226 "control_qbit":
None,
228 "param_start": param_start,
233 elif gate_name
in {
"cx",
"cnot"}:
236 "index": len(expected),
237 "kind": PLANNER_OP_KIND_GATE,
240 "source_gate_index": gate_index,
241 "target_qbit": qubit_indices[1],
242 "control_qbit": qubit_indices[0],
244 "param_start": param_start,
250 f
"Unsupported bridge micro-validation gate in expected bridge: {gate_name}" 253 for noise_spec
in noise_by_gate.get(gate_index, []):
256 "index": len(expected),
257 "kind": PLANNER_OP_KIND_NOISE,
258 "name": noise_spec[
"channel"],
260 "source_gate_index": gate_index,
261 "target_qbit": noise_spec[
"target"],
262 "control_qbit":
None,
264 "param_start": param_start,
265 "fixed_value": noise_spec[
"value"],
273 if len(actual_operations) != len(expected_operations):
276 for actual, expected
in zip(actual_operations, expected_operations):
288 if actual.get(key) != expected.get(key):
291 actual_fixed = actual.get(
"fixed_value")
292 expected_fixed = expected.get(
"fixed_value")
293 if expected_fixed
is None:
294 if actual_fixed
is not None:
296 elif actual_fixed
is None or not math.isclose(actual_fixed, expected_fixed, rel_tol=0.0, abs_tol=1e-12):
304 backend=PRIMARY_BACKEND,
305 qbit_num=case[
"qbit_num"],
307 density_noise=case[
"density_noise"],
312 "case_name": case[
"case_name"],
313 "case_kind":
"bridge_micro_validation",
314 "purpose": case[
"purpose"],
315 "required_gate_families": case[
"required_gate_families"],
316 "required_noise_models": case[
"required_noise_models"],
323 vqe, _, topology, parameters =
build_bridge_vqe(case[
"qbit_num"], case[
"density_noise"])
324 bridge = vqe.describe_density_bridge()
326 energy = float(vqe.Optimization_Problem(parameters))
328 gate_names = [op[
"name"]
for op
in bridge[
"operations"]
if op[
"kind"] ==
"gate"]
329 noise_names = [op[
"name"]
for op
in bridge[
"operations"]
if op[
"kind"] ==
"noise"]
330 source_pass = bridge[
"source_type"] ==
"generated_hea" 331 gate_pass =
"U3" in gate_names
and (
332 (
not case[
"requires_cnot"])
or (
"CNOT" in gate_names)
335 required_model
in noise_names
for required_model
in case[
"required_noise_models"]
338 bridge[
"operations"], expected_operations
340 execution_ready =
bool(np.isfinite(energy))
345 and operation_match_pass
352 "status":
"pass" if bridge_pass
else "fail",
353 "parameter_vector": parameters.tolist(),
354 "execution_energy": energy,
355 "execution_ready": execution_ready,
356 "source_pass": source_pass,
357 "gate_pass": gate_pass,
358 "noise_pass": noise_pass,
359 "operation_match_pass": operation_match_pass,
360 "expected_operation_count": len(expected_operations),
361 "expected_bridge_operations": expected_operations,
368 " {case_name:<46} q={qbit_num} ops={ops} noise={noise} status={status}".format(
369 case_name=result[
"case_name"],
370 qbit_num=result[
"qbit_num"],
371 ops=result[
"bridge_operation_count"],
372 noise=result[
"bridge_noise_count"],
373 status=result[
"status"].upper(),
383 except Exception
as exc:
389 "execution_ready":
False,
390 "source_pass":
False,
393 "operation_match_pass":
False,
394 "error_message": str(exc),
399 " {case_name:<46} q={qbit_num} ERROR {message}".format(
400 case_name=result[
"case_name"],
401 qbit_num=result[
"qbit_num"],
402 message=result[
"error_message"],
410 print(
" Bridge Micro-Validation [{}]".format(PRIMARY_BACKEND))
414 for case
in MANDATORY_BRIDGE_MICROCASES:
420 passed = sum(1
for result
in results
if result[
"status"] ==
"pass")
422 pass_rate = 0.0
if total == 0
else passed / total
424 "suite_name": SUITE_NAME,
425 "status":
"pass" if pass_rate == 1.0
else "fail",
426 "backend": PRIMARY_BACKEND,
430 "total_cases": total,
431 "passed_cases": passed,
432 "failed_cases": total - passed,
433 "pass_rate": pass_rate,
436 1
for result
in results
if result[
"qbit_num"] == qbit_num
438 for qbit_num
in sorted({case[
"qbit_num"]
for case
in MANDATORY_BRIDGE_MICROCASES})
448 missing_fields = [field
for field
in ARTIFACT_CORE_FIELDS
if field
not in bundle]
451 "Artifact bundle is missing required fields: {}".format(
452 ", ".join(missing_fields)
459 output_path.parent.mkdir(parents=
True, exist_ok=
True)
460 output_path.write_text(json.dumps(bundle, indent=2) +
"\n", encoding=
"utf-8")
464 print(
"\n" +
"=" * 78)
467 for result
in bundle[
"cases"]:
469 if not result.get(
"source_pass",
False):
470 details.append(
"source")
471 if not result.get(
"gate_pass",
False):
472 details.append(
"gate")
473 if not result.get(
"noise_pass",
False):
474 details.append(
"noise")
475 if not result.get(
"operation_match_pass",
False):
476 details.append(
"shape")
477 if not result.get(
"execution_ready",
False):
478 details.append(
"exec")
479 if "error_message" in result:
480 details.append(
"error")
483 " {case_name:<46} q={qbit_num} status={status}{detail_suffix}".format(
484 case_name=result[
"case_name"],
485 qbit_num=result[
"qbit_num"],
486 status=result[
"status"].upper(),
487 detail_suffix=
"" if not details
else " (" +
",".join(details) +
")",
491 print(
"\n" +
"-" * 78)
493 " Total: {passed}/{total} mandatory bridge microcases passed".format(
494 passed=bundle[
"summary"][
"passed_cases"],
495 total=bundle[
"summary"][
"total_cases"],
498 if bundle[
"status"] ==
"pass":
499 print(
"\n ALL TESTS PASSED - Bridge micro-validation gate is closed.")
501 print(
"\n Some mandatory bridge microcases failed - bridge micro-validation is not yet closed.")
506 parser = argparse.ArgumentParser(description=__doc__)
511 help=
"Optional directory for the bridge micro-validation JSON artifact bundle.",
513 args = parser.parse_args()
519 if args.output_dir
is not None:
522 if bundle[
"status"] !=
"pass":
526 if __name__ ==
"__main__":
def build_optimizer_config()
def build_open_chain_topology
def build_reference_bridge_metadata(vqe)
def _case_base(case, topology)
def build_requirement_metadata()
def validate_artifact_bundle(bundle)
def capture_bridge_microcase(case, verbose=True)
def build_artifact_bundle(results)
generate_zz_xx_hamiltonian
def validate_bridge_microcase(case, verbose=True)
def build_initial_parameters
def run_validation(verbose=True)
def build_software_metadata()
def write_artifact_bundle
def bridge_operations_match(actual_operations, expected_operations)
def build_hamiltonian_metadata()
def build_expected_bridge_operations(vqe)
def print_summary(bundle)