deskmerc/ quantum

Byte protection / KINGSTON

Quantum Field Report

Four parity bits protect a byte

Use a shortened Hamming code to repair a measured bit error in A.

IBM job ID
dc0g13uq4uuc73a2ik50
Submitted
20 Nov 2026 · 20:23 CST
QPU charge
2 seconds
Backend
ibm_kingston
Sampling
256 shots per recorded setting/case
Provenance
Quantum Field Report, page 12.

The question

Use a shortened Hamming code to repair a measured bit error in A.

Circuit & method

Keep the original eight data paths, add four parity-bit paths and teleport all twelve codeword bits to Bob. Decode the measured string on the laptop.

PrepareState, codeword or problem instance
Run on KingstonRecorded physical circuit and settings
Measure & checkCounts, decoding and classical verification

Results

Raw A was exact on 178/256 shots. Decoding rescued 55 and spoiled 3, leaving 230/256 correct (89.8%). Five shots were flagged and 21 returned a wrong byte.

Measured outcomesAll-shot success; each bar runs from 0% to 100%.
Raw byte178/256 · 69.5%
Decoded byte230/256 · 89.8%

What this supports

This is classical decoding of measured bit strings. Preserving the phase of an arbitrary logical qubit requires a quantum code.

Percentages are rounded for reading. The original integer counts, physical layouts, settings and available uncertainty calculations remain in the records below. Sampling intervals do not account for drift or every systematic error.

Full experiment record

Every top-level field from the primary hardware JSON is reproduced below, including the complete saved measurement distributions where present. Field names and outcome strings retain their original order and spelling.

backend
ibm_kingston
input
A
codeword_positions_12_to_1
010010000100
data_positions_lsb_first
[
  3,
  5,
  6,
  7,
  9,
  10,
  11,
  12
]
triples_by_position
[
  [
    122,
    123,
    136
  ],
  [
    60,
    61,
    62
  ],
  [
    48,
    49,
    50
  ],
  [
    68,
    69,
    78
  ],
  [
    106,
    105,
    117
  ],
  [
    148,
    149,
    150
  ],
  [
    108,
    109,
    118
  ],
  [
    90,
    91,
    98
  ],
  [
    55,
    59,
    75
  ],
  [
    36,
    41,
    40
  ],
  [
    93,
    94,
    95
  ],
  [
    4,
    5,
    6
  ]
]
previous_byte_job
dc0fvnmq4uuc73a2iig0
fast_mid_measure
True
native_counts
{
  "rz": 144,
  "sx": 72,
  "cz": 24,
  "measure_2": 24,
  "if_else": 24,
  "measure": 12,
  "x": 3,
  "barrier": 1
}
policy
Flip position 1..12 on a matching syndrome. Flag 13..15 and count as unsuccessful.
stage
done
tag
hamming12-8-ascii-A-kingston-20261120
shots_per_circuit
256
job_id
dc0g13uq4uuc73a2ik50
counts
[
  {
    "010000001100000111001001111101111110": 1,
    "010010000100000110011000010111111010": 1,
    "010010100100011101011100101000000100": 1,
    "010011000100000110101101101111101001": 1,
    "000000000100011010001100001111100010": 1,
    "010010000100001000010011110110011100": 1,
    "010010000100001100000101000000101000": 1,
    "010010000100100001000110001010111110": 1,
    "010010001100000101001001000110010000": 1,
    "010010010100011001000101101100011101": 1,
    "010010000100011111000010011110001110": 1,
    "010110000100001001011111101101000100": 1,
    "010010000100110010110101100010111010": 1,
    "010010000100100101011101101110010000": 1,
    "010010000100001010110000011100101101": 1,
    "010010000100101100000010110010110110": 1,
    "000000000100011011100010110110111001": 1,
    "010000000100100011001101000010000100": 1,
    "010010000100001000101100110000111111": 1,
    "010010000100000000011111100110010000": 1,
    "010010000101111100001111011010001001": 1,
    "010010000100001010010000000000111011": 1,
    "010010000100010101100001100101110000": 1,
    "010000000100010011011010100110111110": 1,
    "001010000100101110000000000011110000": 1,
    "010010000100100110100000111101110111": 1,
    "010010000100110000111001100001101100": 1,
    "010010000100010100110010111001000011": 1,
    "010010000100011010000111000010011000": 1,
    "010010100100111111001011010100110011": 1,
    "010010000100110101010100100111100101": 1,
    "010010000100011100010010011010110010": 1,
    "000010000100101000111010011011000010": 1,
    "010010010000011111000110101000101100": 1,
    "010010001100011001111111010011100000": 1,
    "000010000100111100001011101011110010": 1,
    "000010000100110001110101011011011110": 1,
    "010010000100110110100000100000101010": 1,
    "010110000100100011000111111111000010": 1,
    "010010000110100011000100101001011101": 1,
    "010010000100110100110111000111001110": 1,
    "011010000100001010001101001010110011": 1,
    "010010100100101111000010011110110000": 1,
    "000010000100110001000100011001111101": 1,
    "010010000100001011000000111001011110": 1,
    "010010000100101100101011011110101011": 1,
    "011010000100011001011010101101001001": 1,
    "010010000100100000111111111100101100": 1,
    "010010000101100111011110011100010100": 1,
    "010010010100110010001000011101011010": 1,
    "010010000110010010010000110011010100": 1,
    "010010001100001110010001111100001110": 1,
    "010010000101010111111001000111100110": 1,
    "010010000110011011010111011100011010": 1,
    "010010000100010100110101000111110110": 1,
    "010010000100000001100100100100101010": 1,
    "010010000100001001101011101100100010": 1,
    "010010000100111000000010010101110011": 1,
    "010010000100111110101100110101100111": 1,
    "000010000100110001101110010010000110": 1,
    "010000000100001100110111111110111111": 1,
    "010010000100110110010110010010100101": 1,
    "010010000100101100110101001110010000": 1,
    "011010000100000000111001100100100100": 1,
    "010000000100000011111010111100011100": 1,
    "010010000100111101100011100000000101": 1,
    "010010000100111100011111000111000100": 1,
    "010010000100111101011101011000010101": 1,
    "010110100000100101111100001111101111": 1,
    "000010000100011111001100110010111111": 1,
    "010010000100111000100100100011000010": 1,
    "110010000100101010010110101001001001": 1,
    "010010100100111011010000110001001000": 1,
    "010011000100101110011111110010100111": 1,
    "010010000100101011100111011010101011": 1,
    "010010000110011111110001111000011001": 1,
    "010010010100110000100001001011010110": 1,
    "110010000000111011110001100110011100": 1,
    "010010000100010011111011011110001010": 1,
    "010010000100110110110101000101001111": 1,
    "000000000100001001100000101011110101": 1,
    "010000000100111001100011000011011010": 1,
    "010010000100110011001111000110111101": 1,
    "010110000100101010110110010111010100": 1,
    "010000000100011000001100000001111000": 1,
    "000010000100001100000101010010000000": 1,
    "010010010100100001011100000000101111": 1,
    "010010000101110111101100001001011101": 1,
    "010010001100110000100100010101100001": 1,
    "000110000100100101001001100001110011": 1,
    "010010000100011010110111010110010100": 1,
    "010010010100011000100000001000000000": 1,
    "000010000100110011011100111010111011": 1,
    "010010000100010111101011000111111011": 1,
    "010010000010011111100011111011001010": 1,
    "010010000100010100101011111111010000": 1,
    "010010000110000000100000010001000011": 1,
    "010010000100001101101111010100101110": 1,
    "010010000110000010010111100111010010": 1,
    "010010000100110000011110111000011011": 1,
    "010010100100010111010100101010010101": 1,
    "010010000100011010010010001010001101": 1,
    "010010000100111111101001000001110110": 1,
    "011010000100111001110101001011100001": 1,
    "010110100100101000111001100000111010": 1,
    "010010000100100001101001101000110101": 1,
    "010010000100011110101001000011111110": 1,
    "010001000000010010101101100010110111": 1,
    "010000000100010011001001001001100110": 1,
    "010010000101111101101100011110110010": 1,
    "010010000100100111111000001111100110": 1,
    "010010000100010010000001110101110001": 1,
    "010010000101111010010010110011011010": 1,
    "010010000100110111001100001111011010": 1,
    "000010000100011001101100000011010100": 1,
    "010010000100001100000001010100101000": 1,
    "010010000100110000100100011000110101": 1,
    "010010000100001001001010101011001100": 1,
    "010010000100011101101111000100010010": 1,
    "010010010100001000010011100010110100": 1,
    "010010000100011110000110101010000101": 1,
    "010010000100100111010111101001111110": 1,
    "010010000100111010001000100101000001": 1,
    "010010000100001101110101101011000011": 1,
    "010010000110110110000100000001010010": 1,
    "010010000110100101011001010010101110": 1,
    "010010100100010010000111011011111110": 1,
    "010010000100100010001001101100011001": 1,
    "010010000000000011001010010011100100": 1,
    "010010000100011001100011011101011000": 1,
    "010010000100011101100101010110101011": 1,
    "010010000100110000000101110110100111": 1,
    "010010000100001010000111101110010100": 1,
    "001010000100001100000101111001100100": 1,
    "010010000100000011110001111001110100": 1,
    "010010000100110011100011101100000000": 1,
    "010010000100110101101111001101001001": 1,
    "010010000100011100000110000110000101": 1,
    "010010001100011100100110001110100111": 1,
    "010010000100110010100111000011100011": 1,
    "010010001100100010110001100110000000": 1,
    "010010000100100110111010110010111010": 1,
    "010010000110100100001101011001100010": 1,
    "010010000100001100100101110101100000": 1,
    "010010000110001101101110000001011000": 1,
    "010010100100000000111100000100100100": 1,
    "010010000000100000100101001000110100": 1,
    "010010000100001100101010111100010110": 1,
    "010010000100011001011111111000010001": 1,
    "010010000100010100100111000100000001": 1,
    "000010100100101011100000010001011101": 1,
    "010010000100100101110100011111001011": 1,
    "010010000100010001100100011011100011": 1,
    "010010000100110111010011101001010000": 1,
    "010010000100011100011011011111110101": 1,
    "010010000100010100010011001110100111": 1,
    "010100010100001000110110001001111011": 1,
    "010000000101001100010001101011101111": 1,
    "010010000110100100111000010101110011": 1,
    "010010000100000011001110010000010111": 1,
    "010010000100100000111011000010101010": 1,
    "011010000100110100011110100010000101": 1,
    "110010000100111110001100111111100101": 1,
    "010110000100111111111001101101011101": 1,
    "010010000100000000110001001111100110": 1,
    "010110000100010000010000101101000011": 1,
    "010010000100000101010000101001000101": 1,
    "010110000100101110001101101011111011": 1,
    "010010000100010111011110101010101100": 1,
    "010010000100011000100110111011111101": 1,
    "000010011100110101000001010101111001": 1,
    "010010001100010000001111010010110010": 1,
    "000010000100111100001110111000010101": 1,
    "010010000100111111101111010111000010": 1,
    "010010010000010000110100110101111111": 1,
    "000010000100101001000010100001111100": 1,
    "010010000100110101110000101000111010": 1,
    "010010000100101111000000101011100000": 1,
    "110011000100000110100010001011100100": 1,
    "010010000100011000010110001000001000": 1,
    "010010000100101010010011001110000000": 1,
    "010010000000101101100110011101111011": 1,
    "010010000100101000110010010001011110": 1,
    "010010000100000111111101100011111010": 1,
    "010010000100111101101100000101010001": 1,
    "010010000100001010000000001001001011": 1,
    "010010000100100000001010111010101000": 1,
    "010010000100011001010110101101001101": 1,
    "000010000100111110100101000011011010": 1,
    "010010000100111011001101001011011000": 1,
    "011000000100111110001100011000000101": 1,
    "010000000100111110110011011110000100": 1,
    "000010000100011101100101111110010110": 1,
    "010010000100100111011000001110111001": 1,
    "010010000100110110100010101110111101": 1,
    "010010000100001000100011011100110111": 1,
    "011010000100011110111110101100001011": 1,
    "010010000110011101111010010100011101": 1,
    "010010000100011100101100010111111111": 1,
    "010010000100101010101101101000011011": 1,
    "010010000100110110111010000101100110": 1,
    "010000000100101001101001110000100010": 1,
    "010110000100011000110011100001111011": 1,
    "010010000100010010011100011110100010": 1,
    "010010000100001010000010101100110101": 1,
    "010010000100001110011100010101111000": 1,
    "000010000101010000111001110101011011": 1,
    "010010000100011000111111010010111110": 1,
    "010010000110000001001111100101001001": 1,
    "000010000100101101011110101011000110": 1,
    "010000000100000010101001010100111010": 1,
    "010010000100100011010110010010011101": 1,
    "010010000100000001011000000010111000": 1,
    "010010000100111111001111001110111001": 1,
    "010010000100110000111010101001111000": 1,
    "010010000100000101101101110101011111": 1,
    "010000000100000010001100010101010010": 1,
    "010010000100010001110100010110010100": 1,
    "010010000100000000010010101100110010": 1,
    "011010000100110000111001010001101010": 1,
    "011010000100010111101010110001010111": 1,
    "010010000100110010011111111010101100": 1,
    "010010001101100010110001001100001110": 1,
    "010010000100001111010100011011100100": 1,
    "010010000100110100000000110001100000": 1,
    "010000000100111111111000111000110111": 1,
    "010010000100111101001101101000111111": 1,
    "010010000100011011100110101001010011": 1,
    "010010000100110001110110010000110000": 1,
    "010010000100000111111100110100000100": 1,
    "010010100000100101111011110110011010": 1,
    "000010000100011010101000101011111111": 1,
    "010010000100011001011111100111100100": 1,
    "010010000100000110111001100010110000": 1,
    "010010000100100111010001011000110010": 1,
    "010010000100011100110011000010110100": 1,
    "010010000100000111101111000101001100": 1,
    "010110100100111011101110100100000001": 1,
    "000010000100000101110110011101000111": 1,
    "010010000100100011101110111000010001": 1,
    "000010000100001010110010100100000001": 1,
    "010010000100110100011111010010011110": 1,
    "010000000100101100001100100110010110": 1,
    "010010000100110111101100110000100010": 1,
    "010010000100101101000001001101110111": 1,
    "010010000100111100000010001000111101": 1,
    "110000000100111111001011011011111001": 1,
    "010010010100001101100011001001001101": 1,
    "010010000100011100010100001101110001": 1,
    "010010001100111111011001110011001110": 1,
    "010010010100101100101101001010001111": 1,
    "010010000100010101010110100100110111": 1,
    "010010000100011001111110100001111000": 1,
    "110010000110010100000100101001100111": 1,
    "010010000110000101111000101100101101": 1,
    "010010010100100000001110111001001101": 1
  }
]
metrics
{
  "caller": "qiskit",
  "qiskit_version": "qiskit_ibm_runtime-0.52.1,qiskit-2.6.2*,qiskit_aer-0.17.2*",
  "timestamps": {
    "created": "2026-11-21T02:23:11.269232Z",
    "finished": "2026-11-21T02:23:16.912827Z",
    "running": "2026-11-21T02:23:12.637635Z"
  },
  "usage": {
    "qpu_charge_time_seconds": 2,
    "value": 0.029489,
    "unit": "resource_units",
    "status": "complete",
    "details": [
      {
        "value": 0.029489,
        "unit": "resource_units",
        "metric": {
          "id": "caffe3ca-729c-5750-8777-df63bbf8bfd9",
          "value": 2
        }
      }
    ]
  },
  "circuits_execution_time_ns": 67258624
}
analysis
{
  "raw_byte_exact": 178,
  "decoded_byte_exact": 230,
  "rescued": 55,
  "lost": 3,
  "uncorrectable_flags": 5,
  "wrong_returned": 21,
  "received_words": {
    "010000001100": 1,
    "010010000100": 134,
    "010010100100": 7,
    "010011000100": 2,
    "000000000100": 3,
    "010010001100": 8,
    "010010010100": 9,
    "010110000100": 7,
    "010000000100": 13,
    "010010000101": 6,
    "001010000100": 2,
    "000010000100": 17,
    "010010010000": 2,
    "010010000110": 14,
    "011010000100": 8,
    "010110100000": 1,
    "110010000100": 2,
    "110010000000": 1,
    "000110000100": 1,
    "010010000010": 1,
    "010110100100": 2,
    "010001000000": 1,
    "010010000000": 3,
    "000010100100": 1,
    "010100010100": 1,
    "010000000101": 1,
    "000010011100": 1,
    "110011000100": 1,
    "011000000100": 1,
    "000010000101": 1,
    "010010001101": 1,
    "010010100000": 1,
    "110000000100": 1,
    "110010000110": 1
  },
  "codeword_bit_errors": {
    "0": 134,
    "1": 96,
    "2": 22,
    "3": 4
  }
}

Simulation & checks

These are the supplied simulator records and their preserved variants. Their model, seed, settings and results appear exactly as saved. Shared simulator references on fresh-map pages describe the ideal graph protocol, rather than a new hardware-matched calibration.

field-report/outputs/Hamming-A-simulator.json · full record
{
  "ideal_shots": 256,
  "analysis": {
    "raw_byte_exact": 256,
    "decoded_byte_exact": 256,
    "rescued": 0,
    "lost": 0,
    "uncorrectable_flags": 0,
    "wrong_returned": 0,
    "received_words": {
      "010010000100": 256
    },
    "codeword_bit_errors": {
      "0": 256
    }
  },
  "all_single_bit_decoder_tests_passed": 3072
}
noise-wall/results/Hamming-A-simulator.json · full record
{
  "ideal_shots": 256,
  "analysis": {
    "raw_byte_exact": 256,
    "decoded_byte_exact": 256,
    "rescued": 0,
    "lost": 0,
    "uncorrectable_flags": 0,
    "wrong_returned": 0,
    "received_words": {
      "010010000100": 256
    },
    "codeword_bit_errors": {
      "0": 256
    }
  },
  "all_single_bit_decoder_tests_passed": 3072
}

Source code

Original experiment and verification programs are preserved byte for byte. These are historical listings; dependencies, authentication prompts and machine-specific input paths may need adjustment before a rerun.

  • hamming_ascii.pyQuantum Field Report.pdf / Experiment-source.zip · 4,977 bytes
  • check_hamming_a.pyQuantum Field Report.pdf / Experiment-source.zip · 1,314 bytes
  • hamming_ascii.pyThrough the Noise Wall.pdf / Kingston measurements and source.zip · 4,977 bytes
field-report/outputs/hamming_ascii.py · complete source
"""Classically encode one byte, teleport its 12-bit codeword, decode Bob's readouts."""
import getpass
import logging
import sys
import traceback
from collections import Counter
from pathlib import Path

from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.accounts.exceptions import InvalidAccountError

from graph156 import save
from run_switch_puzzles import ROOT, SHOTS, execute, load
from teleport_ascii_a import VALUE, circuit, prepare, triples

WIDTH=12
PARITY=(1,2,4,8)
DATA=tuple(i for i in range(1,WIDTH+1) if i not in PARITY)
SIM=ROOT/"Hamming-A-simulator.json"
HW=ROOT/"Hamming-A-Kingston.json"
TAG="hamming12-8-ascii-A-kingston-20261120"


def syndrome(word):
    check=0
    for i in range(1,WIDTH+1):
        if word & (1<<(i-1)):
            check^=i
    return check


def encode(byte):
    word=sum(((byte>>j)&1)<<(i-1) for j,i in enumerate(DATA))
    check=syndrome(word)
    return word+sum(1<<(i-1) for i in PARITY if i&check)


def payload(word):
    return sum(((word>>(i-1))&1)<<j for j,i in enumerate(DATA))


def decode(word):
    check=syndrome(word)
    if check>WIDTH:
        return None
    if check:
        word^=1<<(check-1)
    return payload(word)


def analyze(counts):
    raw=correct=rescued=lost=flags=0
    distances=Counter()
    words=Counter()
    for bits,n in counts.items():
        assert len(bits)==3*WIDTH and set(bits)<={"0","1"}
        word=int(bits,2)>>(2*WIDTH)
        before=payload(word)==VALUE
        after=decode(word)
        good=after==VALUE
        words[format(word,"012b")]+=n
        distances[(word^encode(VALUE)).bit_count()]+=n
        raw+=n*before
        correct+=n*good
        rescued+=n*(good and not before)
        lost+=n*(before and not good)
        flags+=n*(after is None)
    assert sum(counts.values())==SHOTS and raw+rescued-lost==correct
    return dict(raw_byte_exact=raw,decoded_byte_exact=correct,rescued=rescued,lost=lost,
                uncorrectable_flags=flags,wrong_returned=SHOTS-correct-flags,
                received_words=dict(words),codeword_bit_errors=dict(sorted(distances.items())))


def simulate():
    for b in range(256):
        w=encode(b)
        assert syndrome(w)==0 and decode(w)==b
        assert all(decode(w^(1<<j))==b for j in range(WIDTH))
    q=circuit("teleport",value=encode(VALUE),width=WIDTH)
    counts=AerSimulator(method="stabilizer").run(q,shots=SHOTS,seed_simulator=20261120).result().get_counts()
    result=analyze(counts)
    assert result["raw_byte_exact"]==result["decoded_byte_exact"]==SHOTS
    save(SIM,dict(ideal_shots=SHOTS,analysis=result,all_single_bit_decoder_tests_passed=256*WIDTH))
    print(result)


def hardware():
    rec=load(HW)
    if rec.get("analysis"):
        return
    if not sys.stdin.isatty() or not SIM.exists():
        raise RuntimeError("Complete simulation and use a private console")
    while True:
        key=getpass.getpass("IBM Cloud API key (hidden): ").strip()
        if not key:
            return
        try:
            service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,
                                         plans_preference=["open"],region="us-east")
            break
        except InvalidAccountError:
            print("Instance lookup failed. Paste the key again or press Enter to exit.")
    backend=service.backend("ibm_kingston")
    isa=[]
    if not rec:
        previous=load(ROOT/"ASCII-A-Kingston.json")
        data_paths=previous["triples_from_least_significant_bit"]
        reserved={q for p in data_paths for q in p}
        parity_paths=triples(backend,len(PARITY),reserved)
        by_position=dict(zip(DATA,data_paths))
        by_position.update(zip(PARITY,parity_paths))
        paths=[by_position[i] for i in range(1,13)]
        assert len({q for p in paths for q in p})==36
        _,fast,isa=prepare(backend,paths,("teleport",),encode(VALUE))
        rec=dict(backend=backend.name,input="A",codeword_positions_12_to_1=format(encode(VALUE),"012b"),
                 data_positions_lsb_first=DATA,triples_by_position=paths,previous_byte_job=previous["job_id"],
                 fast_mid_measure=fast,native_counts=dict(isa[0].count_ops()),
                 policy="Flip position 1..12 on a matching syndrome. Flag 13..15 and count as unsuccessful.")
    rec=execute(service,backend,HW,TAG,rec,lambda:isa)
    rec["analysis"]=analyze(rec["counts"][0])
    save(HW,rec)


if __name__=="__main__":
    if sys.argv[1:]==["simulate"]:
        simulate()
    elif sys.argv[1:]==["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
            save(ROOT.parent/"work"/"hamming-a-error.json",{"type":type(exc).__name__,"frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")
field-report/work/check_hamming_a.py · complete source
import json
from pathlib import Path
from collections import Counter
from scipy.stats import binomtest

root=Path(__file__).resolve().parents[1]/"outputs"
r=json.loads((root/"Hamming-A-Kingston.json").read_text())
positions=[3,5,6,7,9,10,11,12]
book={}
for data in range(256):
    bits={p:(data>>i)&1 for i,p in enumerate(positions)}
    for p in (1,2,4,8):
        bits[p]=sum(bits[q] for q in positions if q&p)%2
    book[data]=sum(v<<(q-1) for q,v in bits.items())
totals=Counter()
dist_hist=Counter()
for raw,n in r["counts"][0].items():
    w=int(raw[:12],2)
    candidates=[k for k,c in book.items() if (c^w).bit_count()<=1]
    assert len(candidates)<=1
    before=sum(((w>>(p-1))&1)<<i for i,p in enumerate(positions))==65
    after=candidates==[65]
    for k,f in (("raw_byte_exact",before),("decoded_byte_exact",after),("rescued",after and not before),
                ("lost",before and not after),("uncorrectable_flags",not candidates),
                ("wrong_returned",bool(candidates) and not after)):
        totals[k]+=n*f
    dist_hist[(w^book[65]).bit_count()]+=n
assert sum(dist_hist.values())==256 and all(r["analysis"][k]==v for k,v in totals.items())
print(totals,dist_hist,binomtest(totals["decoded_byte_exact"],256).proportion_ci(method="wilson"))
print(r["job_id"],r["metrics"]["usage"])
noise-wall/source/hamming_ascii.py · complete source
"""Classically encode one byte, teleport its 12-bit codeword, decode Bob's readouts."""
import getpass
import logging
import sys
import traceback
from collections import Counter
from pathlib import Path

from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.accounts.exceptions import InvalidAccountError

from graph156 import save
from run_switch_puzzles import ROOT, SHOTS, execute, load
from teleport_ascii_a import VALUE, circuit, prepare, triples

WIDTH=12
PARITY=(1,2,4,8)
DATA=tuple(i for i in range(1,WIDTH+1) if i not in PARITY)
SIM=ROOT/"Hamming-A-simulator.json"
HW=ROOT/"Hamming-A-Kingston.json"
TAG="hamming12-8-ascii-A-kingston-20261120"


def syndrome(word):
    check=0
    for i in range(1,WIDTH+1):
        if word & (1<<(i-1)):
            check^=i
    return check


def encode(byte):
    word=sum(((byte>>j)&1)<<(i-1) for j,i in enumerate(DATA))
    check=syndrome(word)
    return word+sum(1<<(i-1) for i in PARITY if i&check)


def payload(word):
    return sum(((word>>(i-1))&1)<<j for j,i in enumerate(DATA))


def decode(word):
    check=syndrome(word)
    if check>WIDTH:
        return None
    if check:
        word^=1<<(check-1)
    return payload(word)


def analyze(counts):
    raw=correct=rescued=lost=flags=0
    distances=Counter()
    words=Counter()
    for bits,n in counts.items():
        assert len(bits)==3*WIDTH and set(bits)<={"0","1"}
        word=int(bits,2)>>(2*WIDTH)
        before=payload(word)==VALUE
        after=decode(word)
        good=after==VALUE
        words[format(word,"012b")]+=n
        distances[(word^encode(VALUE)).bit_count()]+=n
        raw+=n*before
        correct+=n*good
        rescued+=n*(good and not before)
        lost+=n*(before and not good)
        flags+=n*(after is None)
    assert sum(counts.values())==SHOTS and raw+rescued-lost==correct
    return dict(raw_byte_exact=raw,decoded_byte_exact=correct,rescued=rescued,lost=lost,
                uncorrectable_flags=flags,wrong_returned=SHOTS-correct-flags,
                received_words=dict(words),codeword_bit_errors=dict(sorted(distances.items())))


def simulate():
    for b in range(256):
        w=encode(b)
        assert syndrome(w)==0 and decode(w)==b
        assert all(decode(w^(1<<j))==b for j in range(WIDTH))
    q=circuit("teleport",value=encode(VALUE),width=WIDTH)
    counts=AerSimulator(method="stabilizer").run(q,shots=SHOTS,seed_simulator=20261120).result().get_counts()
    result=analyze(counts)
    assert result["raw_byte_exact"]==result["decoded_byte_exact"]==SHOTS
    save(SIM,dict(ideal_shots=SHOTS,analysis=result,all_single_bit_decoder_tests_passed=256*WIDTH))
    print(result)


def hardware():
    rec=load(HW)
    if rec.get("analysis"):
        return
    if not sys.stdin.isatty() or not SIM.exists():
        raise RuntimeError("Complete simulation and use a private console")
    while True:
        key=getpass.getpass("IBM Cloud API key (hidden): ").strip()
        if not key:
            return
        try:
            service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,
                                         plans_preference=["open"],region="us-east")
            break
        except InvalidAccountError:
            print("Instance lookup failed. Paste the key again or press Enter to exit.")
    backend=service.backend("ibm_kingston")
    isa=[]
    if not rec:
        previous=load(ROOT/"ASCII-A-Kingston.json")
        data_paths=previous["triples_from_least_significant_bit"]
        reserved={q for p in data_paths for q in p}
        parity_paths=triples(backend,len(PARITY),reserved)
        by_position=dict(zip(DATA,data_paths))
        by_position.update(zip(PARITY,parity_paths))
        paths=[by_position[i] for i in range(1,13)]
        assert len({q for p in paths for q in p})==36
        _,fast,isa=prepare(backend,paths,("teleport",),encode(VALUE))
        rec=dict(backend=backend.name,input="A",codeword_positions_12_to_1=format(encode(VALUE),"012b"),
                 data_positions_lsb_first=DATA,triples_by_position=paths,previous_byte_job=previous["job_id"],
                 fast_mid_measure=fast,native_counts=dict(isa[0].count_ops()),
                 policy="Flip position 1..12 on a matching syndrome. Flag 13..15 and count as unsuccessful.")
    rec=execute(service,backend,HW,TAG,rec,lambda:isa)
    rec["analysis"]=analyze(rec["counts"][0])
    save(HW,rec)


if __name__=="__main__":
    if sys.argv[1:]==["simulate"]:
        simulate()
    elif sys.argv[1:]==["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
            save(ROOT.parent/"work"/"hamming-a-error.json",{"type":type(exc).__name__,"frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")

Personal comments

Personal comments will be added here.