contract = {"order": ("q0", "q1"), "support": {"00", "11"}, "p": {"00": .5, "11": .5}}
def canonical_counts(record):
    columns = record.get("columns")
    counts = record.get("counts", {})
    if (type(columns) is not tuple or len(columns) != len(set(columns)) or
            set(columns) != set(contract["order"]) or not counts):
        raise ValueError("adapter columns must be a permutation of the contract order")
    output = {}
    for bitstring, count in counts.items():
        if len(bitstring) != len(columns) or type(count) is not int or count < 0:
            raise ValueError("counts must use fixed-width bit strings and integer counts")
        by_qubit = dict(zip(columns, bitstring))
        canonical = "".join(by_qubit[qubit] for qubit in contract["order"])
        output[canonical] = output.get(canonical, 0) + count
    return output

cirq_bell = canonical_counts({"columns": ("q0", "q1"), "counts": {"00": 501, "11": 499}})
second_bell = canonical_counts({"columns": ("q1", "q0"), "counts": {"00": 501, "11": 499}})
cirq_asymmetric = canonical_counts({"columns": ("q0", "q1"), "counts": {"01": 700, "10": 300}})
second_asymmetric = canonical_counts({"columns": ("q1", "q0"), "counts": {"10": 700, "01": 300}})
wrong_declaration = canonical_counts({"columns": ("q0", "q1"), "counts": {"10": 700, "01": 300}})
invalid_rejected = False
try:
    canonical_counts({"columns": ("q0", "q0"), "counts": {"00": 1}})
except ValueError:
    invalid_rejected = True
assert set(cirq_bell) == contract["support"] and cirq_bell == second_bell
assert cirq_asymmetric == second_asymmetric == {"01": 700, "10": 300}
assert wrong_declaration != cirq_asymmetric and invalid_rejected
print(f"PASS: 39 adapter Bell={cirq_bell} asymmetric={cirq_asymmetric} wrong_order={wrong_declaration}")
