Download generate_dataset.py from greatkoko/quantum-metamorphic-testing: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/datasets/greatkoko/quantum-metamorphic-testing/resolve/main/generate_dataset.py
- Command line
-
hf download hf://datasets/greatkoko/quantum-metamorphic-testing/generate_dataset.py
-
curl -L -o generate_dataset.py https://huggingface.co/datasets/greatkoko/quantum-metamorphic-testing/resolve/main/generate_dataset.py
10.2 kB
| """ | |
| Quantum Metamorphic Testing Dataset ์์ฑ ์คํฌ๋ฆฝํธ | |
| TC1~TC6 ร {Depolarizing, Amplitude Damping, Phase Damping} ร {Z, X ๊ธฐ์ } ร ๋ ธ์ด์ฆ ๊ฐ๋ | |
| ์กฐํฉ์ Qiskit Aer๋ก ์๋ฎฌ๋ ์ด์ ํ๊ณ , ์ธก์ ๋น๋์ ํ๊ฐ ์งํ๋ฅผ CSV๋ก ์ ์ฅํฉ๋๋ค. | |
| ์ฌ์ฉ๋ฒ: | |
| pip install qiskit qiskit-aer numpy scipy pandas | |
| python generate_dataset.py # ๊ธฐ๋ณธ: seed 1234, shots 4096 | |
| python generate_dataset.py --seeds 1234 1 2 3 4 # ๋ฐ๋ณต ์คํ(์๋๋ณ ๋ณ๋์ฑ ๋ถ์์ฉ) | |
| python generate_dataset.py --max-noise 0.2 --step 0.005 --out data | |
| ์ถ๋ ฅ: | |
| <out>/results.csv : ์คํ 1ํ(์กฐ๊ฑด 1๊ฐ)๋น 1ํ | |
| <out>/test_cases.csv : ํ ์คํธ ์ผ์ด์ค ์ ์์ ์ด์์ ์ถ๋ ฅ ๋ถํฌ | |
| <out>/metadata.json : ์คํ ์ค์ ๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ฒ์ | |
| Reference: | |
| W.-Y. Hyun, D. Kang, "Generating Metamorphic Test Cases using 2-qubit Quantum | |
| Gate Combinations," JKSCI, 31(5), 1-9, 2026. doi:10.9708/jksci.2026.31.05.001 | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import platform | |
| import time | |
| import numpy as np | |
| import pandas as pd | |
| import qiskit | |
| import qiskit_aer | |
| import scipy | |
| from qiskit import QuantumCircuit, transpile | |
| from qiskit.quantum_info import Statevector | |
| from qiskit_aer import AerSimulator | |
| from qiskit_aer.noise import ( | |
| NoiseModel, | |
| amplitude_damping_error, | |
| depolarizing_error, | |
| phase_damping_error, | |
| ) | |
| from scipy.special import rel_entr | |
| from scipy.stats import chi2_contingency, chisquare | |
| STATES = ["00", "01", "10", "11"] | |
| EXPECTED = np.array([0.5, 0.0, 0.0, 0.5]) | |
| EPS = 1e-6 | |
| ONE_Q_GATES = ["h", "x", "y", "z", "s", "sdg", "t", "tdg"] | |
| TWO_Q_GATES = ["cx", "cz", "swap"] | |
| TEST_CASES = { | |
| "TC1": ("Base Combination", [("h", 0), ("cx", 0, 1)]), | |
| "TC2": ("Logical Equivalence", [("x", 0), ("h", 0), ("cx", 0, 1)]), | |
| "TC3": ("Single Phase Flip", [("z", 0), ("h", 0), ("cx", 0, 1)]), | |
| "TC4": ("Double Phase Flip", [("z", 0), ("z", 1), ("h", 0), ("cx", 0, 1)]), | |
| "TC5": ("Gate Invalidation", [("h", 0), ("cx", 0, 1), ("h", 0), ("h", 0)]), | |
| "TC6": ("Swap Operations", [("h", 1), ("cx", 1, 0)]), | |
| } | |
| NOISE_MODELS = { | |
| "depolarizing": "Depolarizing", | |
| "amplitude_damping": "Amplitude Damping", | |
| "phase_damping": "Phase Damping", | |
| } | |
| # ๋ ผ๋ฌธ ์ค์ : DepolarizingยทAD โ Z-๊ธฐ์ , PD โ X-๊ธฐ์ | |
| PAPER_BASIS = {"depolarizing": "Z", "amplitude_damping": "Z", "phase_damping": "X"} | |
| # --------------------------------------------------------------------------- | |
| def build_circuit(ops, basis="Z", measure=True): | |
| qc = QuantumCircuit(2, 2) | |
| for name, *qubits in ops: | |
| getattr(qc, name)(*qubits) | |
| if measure: | |
| if basis == "X": | |
| qc.barrier() | |
| qc.h([0, 1]) | |
| qc.measure([0, 1], [0, 1]) | |
| return qc | |
| def ops_to_str(ops): | |
| return " -> ".join(f"{n.upper()}({','.join('q%d' % q for q in qs)})" for n, *qs in ops) | |
| def ideal_probs(ops, basis="Z"): | |
| qc = build_circuit(ops, measure=False) | |
| if basis == "X": | |
| qc.h([0, 1]) | |
| d = Statevector.from_instruction(qc).probabilities_dict() | |
| return np.array([d.get(s, 0.0) for s in STATES]) | |
| def create_noise_model(kind, p): | |
| if p <= 0: | |
| return None | |
| if kind == "depolarizing": | |
| e1, e2 = depolarizing_error(p, 1), depolarizing_error(p, 2) | |
| elif kind == "amplitude_damping": | |
| e1 = amplitude_damping_error(p) | |
| e2 = e1.tensor(e1) | |
| elif kind == "phase_damping": | |
| e1 = phase_damping_error(p) | |
| e2 = e1.tensor(e1) | |
| else: | |
| raise ValueError(kind) | |
| nm = NoiseModel() | |
| nm.add_all_qubit_quantum_error(e1, ONE_Q_GATES) | |
| nm.add_all_qubit_quantum_error(e2, TWO_Q_GATES) | |
| return nm | |
| def simulate(qc, noise_model, shots, seed): | |
| backend = AerSimulator(noise_model=noise_model, seed_simulator=seed) | |
| tqc = transpile(qc, backend, optimization_level=0, seed_transpiler=seed) | |
| counts = backend.run(tqc, shots=shots, seed_simulator=seed).result().get_counts() | |
| return np.array([counts.get(s, 0) for s in STATES], dtype=float) | |
| # --------------------------------------------------------------------------- | |
| def chi_square_vs_expected(obs, expected=EXPECTED): | |
| pe = expected + EPS | |
| pe = pe / pe.sum() | |
| stat, p = chisquare(f_obs=obs, f_exp=pe * obs.sum()) | |
| return float(stat), float(p) | |
| def chi_square_vs_source(src, fol): | |
| table = np.vstack([src, fol]) | |
| table = table[:, table.sum(axis=0) > 0] | |
| if table.shape[1] < 2: | |
| return 0.0, 1.0 | |
| stat, p, _, _ = chi2_contingency(table, correction=False) | |
| return float(stat), float(p) | |
| def kl_divergence(expected, obs): | |
| q = obs / obs.sum() + EPS | |
| return float(np.sum(rel_entr(expected, q / q.sum()))) | |
| def cosine_similarity(expected, obs): | |
| q = obs / obs.sum() | |
| return float(np.dot(expected, q) / (np.linalg.norm(expected) * np.linalg.norm(q))) | |
| def judge(p): | |
| if p > 0.5: | |
| return "maintain" | |
| if p > 0.05: | |
| return "uncertain" | |
| return "collapse" | |
| # --------------------------------------------------------------------------- | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--max-noise", type=float, default=0.1) | |
| ap.add_argument("--step", type=float, default=0.01) | |
| ap.add_argument("--shots", type=int, default=4096) | |
| ap.add_argument("--seeds", type=int, nargs="+", default=[1234]) | |
| ap.add_argument("--bases", nargs="+", default=["Z", "X"], choices=["Z", "X"]) | |
| ap.add_argument("--out", default="data") | |
| # parse_known_args: Jupyter/Colab ์ ์์ ์คํํ ๋ ์ปค๋์ด ๋๊ธฐ๋ '-f ...' ์ธ์๋ฅผ ๋ฌด์ | |
| args, _ = ap.parse_known_args(argv) | |
| os.makedirs(args.out, exist_ok=True) | |
| n = int(round(args.max_noise / args.step)) | |
| levels = np.round(np.linspace(0, n * args.step, n + 1), 6) | |
| # ํ ์คํธ ์ผ์ด์ค ์ ์ ํ | |
| tc_rows = [] | |
| for tc, (name, ops) in TEST_CASES.items(): | |
| row = {"test_case": tc, "name": name, "circuit": ops_to_str(ops), | |
| "num_gates": len(ops), "num_2q_gates": sum(len(o) == 3 for o in ops)} | |
| for b in ["Z", "X"]: | |
| ip = ideal_probs(ops, b) | |
| row.update({f"ideal_{b}_p{s}": round(float(v), 6) for s, v in zip(STATES, ip)}) | |
| row[f"mr_valid_ideal_{b}"] = bool(np.allclose(ip, ideal_probs(TEST_CASES["TC1"][1], b), atol=1e-9)) | |
| tc_rows.append(row) | |
| pd.DataFrame(tc_rows).to_csv(os.path.join(args.out, "test_cases.csv"), index=False) | |
| rows = [] | |
| total = len(args.seeds) * len(NOISE_MODELS) * len(args.bases) * len(levels) * len(TEST_CASES) | |
| t0, done = time.time(), 0 | |
| src_ops = TEST_CASES["TC1"][1] | |
| for seed in args.seeds: | |
| for kind, kind_label in NOISE_MODELS.items(): | |
| for basis in args.bases: | |
| # ์ด ๊ธฐ์ ์์์ ๊ธฐ๋ ๋ถํฌ(TC1 ์ด์์ ๋ถํฌ). ZยทX ๋ชจ๋ |00>,|11> 50%. | |
| expected = ideal_probs(src_ops, basis) | |
| for p in levels: | |
| nm = create_noise_model(kind, float(p)) | |
| src_counts = simulate(build_circuit(src_ops, basis), nm, args.shots, seed) | |
| for tc, (name, ops) in TEST_CASES.items(): | |
| counts = (src_counts if tc == "TC1" | |
| else simulate(build_circuit(ops, basis), nm, args.shots, seed)) | |
| probs = counts / counts.sum() | |
| chi_e, p_e = chi_square_vs_expected(counts, expected) | |
| chi_s, p_s = chi_square_vs_source(src_counts, counts) | |
| rows.append({ | |
| "test_case": tc, | |
| "test_case_name": name, | |
| "noise_model": kind, | |
| "noise_model_label": kind_label, | |
| "basis": basis, | |
| "paper_setting": basis == PAPER_BASIS[kind], | |
| "noise_strength": float(p), | |
| "shots": args.shots, | |
| "seed": seed, | |
| **{f"count_{s}": int(c) for s, c in zip(STATES, counts)}, | |
| **{f"prob_{s}": round(float(v), 6) for s, v in zip(STATES, probs)}, | |
| "error_state_prob": round(float(probs[1] + probs[2]), 6), | |
| "chi2_expected": round(chi_e, 4), | |
| "pvalue_expected": p_e, | |
| "mr_expected": judge(p_e), | |
| "chi2_vs_tc1": round(chi_s, 4), | |
| "pvalue_vs_tc1": p_s, | |
| "mr_vs_tc1": judge(p_s), | |
| "kl_divergence": round(kl_divergence(expected, counts), 6), | |
| "cosine_similarity": round(cosine_similarity(expected, counts), 6), | |
| }) | |
| done += 1 | |
| print(f"[{done}/{total}] seed={seed} {kind_label} {basis}-basis done " | |
| f"({time.time() - t0:.1f}s)") | |
| df = pd.DataFrame(rows) | |
| path = os.path.join(args.out, "results.csv") | |
| df.to_csv(path, index=False) | |
| meta = { | |
| "description": "Metamorphic testing of 2-qubit gate combinations under quantum noise", | |
| "reference_doi": "10.9708/jksci.2026.31.05.001", | |
| "noise_levels": levels.tolist(), | |
| "shots": args.shots, | |
| "seeds": args.seeds, | |
| "bases": args.bases, | |
| "transpile_optimization_level": 0, | |
| "epsilon_for_zero_expected": EPS, | |
| "rows": len(df), | |
| "versions": { | |
| "python": platform.python_version(), | |
| "qiskit": qiskit.__version__, | |
| "qiskit_aer": qiskit_aer.__version__, | |
| "numpy": np.__version__, | |
| "scipy": scipy.__version__, | |
| "pandas": pd.__version__, | |
| }, | |
| "generated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), | |
| } | |
| with open(os.path.join(args.out, "metadata.json"), "w", encoding="utf-8") as f: | |
| json.dump(meta, f, ensure_ascii=False, indent=2) | |
| print(f"\nSaved {len(df)} rows -> {path}") | |
| print(df[df.paper_setting].groupby(["noise_model", "test_case"])["kl_divergence"].max().unstack().round(4)) | |
| if __name__ == "__main__": | |
| main() | |