示例#1
0
def test_planar_mps_decoder_cosets_probability_pair_optimisation(mode):
    code = PlanarCode(5, 5)
    decoder = PlanarMPSDecoder(mode=mode)
    # probabilities
    prob_dist = BiasedDepolarizingErrorModel(bias=10).probability_distribution(
        probability=0.1)
    # coset probabilities for null Pauli
    coset_i_ps, _ = decoder._coset_probabilities(prob_dist, code.new_pauli())
    coset_x_ps, _ = decoder._coset_probabilities(prob_dist,
                                                 code.new_pauli().logical_x())
    # expect Pr(iIG) ~= Pr(xXG)
    assert _is_close(
        coset_i_ps[0], coset_x_ps[1], rtol=0,
        atol=0), ('Coset probabilites do not satisfy Pr(iIG) ~= Pr(xXG)')
    # expect Pr(iXG) ~= Pr(xIG)
    assert _is_close(
        coset_i_ps[1], coset_x_ps[0], rtol=0,
        atol=0), ('Coset probabilites do not satisfy Pr(iXG) ~= Pr(xIG)')
    # expect Pr(iZG) ~= Pr(xYG)
    assert _is_close(
        coset_i_ps[3], coset_x_ps[2], rtol=0,
        atol=0), ('Coset probabilites do not satisfy Pr(iZG) ~= Pr(xYG)')
    # expect Pr(iYG) ~= Pr(xZG)
    assert _is_close(
        coset_i_ps[2], coset_x_ps[3], rtol=0,
        atol=0), ('Coset probabilites do not satisfy Pr(iYG) ~= Pr(xZG)')
示例#2
0
def test_planar_mps_decoder_small_code_negative_coset_probability(chi, mode):
    # parameters
    code = PlanarCode(3, 3)
    decoder = PlanarMPSDecoder(chi=chi, mode=mode)
    error_model = DepolarizingErrorModel()
    error_probability = 0.1
    # logged run values
    error = pt.unpack(["e0048000", 26])
    syndrome = pt.bsp(error, code.stabilizers.T)
    # debug
    print()
    print(code.ascii_art(syndrome, code.new_pauli(error)))
    # decode
    prob_dist = error_model.probability_distribution(error_probability)
    any_recovery = decoder.sample_recovery(code, syndrome)
    # coset probabilities
    coset_ps, recoveries = decoder._coset_probabilities(
        prob_dist, any_recovery)
    print('chi={}, mode={}, coset_ps={}'.format(chi, mode, coset_ps))
    max_coset_p, max_recovery = max(
        zip(coset_ps, recoveries),
        key=lambda coset_p_recovery: coset_p_recovery[0])
    success = np.all(
        pt.bsp(max_recovery.to_bsf() ^ error, code.logicals.T) == 0)
    print('### success=', success)
    assert mp.isfinite(
        max_coset_p
    ) and max_coset_p > 0, 'Max coset probability not as expected'
    assert np.all(
        np.array(coset_ps) >= 0), 'At least one coset probability is negative'
示例#3
0
def test_planar_mps_decoder_correlated_errors():
    # check MPS decoder successfully decodes for error
    # I--+--I--+--I
    #    I     I
    # Y--+--I--+--Y
    #    I     I
    # I--+--I--+--I
    # and MWPM decoder fails as expected
    code = PlanarCode(3, 3)
    error = code.new_pauli().site('Y', (2, 0), (2, 4)).to_bsf()
    syndrome = pt.bsp(error, code.stabilizers.T)
    # MPS decoder
    decoder = PlanarMPSDecoder()
    recovery = decoder.decode(code, syndrome)
    # check recovery ^ error commutes with stabilizers (by construction)
    assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
        'recovery ^ error ({} ^ {}) does not commute with stabilizers for MPS decoder.'
        .format(recovery, error))
    # check recovery ^ error commutes with logicals (we expect this to succeed for MPS)
    assert np.all(pt.bsp(recovery ^ error, code.logicals.T) == 0), (
        'recovery ^ error ({} ^ {}) does not commute with logicals for MPS decoder.'
        .format(recovery, error))
    # MWPM decoder
    decoder = PlanarMWPMDecoder()
    recovery = decoder.decode(code, syndrome)
    # check recovery ^ error commutes with stabilizers (by construction)
    assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
        'recovery ^ error ({} ^ {}) does not commute with stabilizers for MWPM decoder.'
        .format(recovery, error))
    # check recovery ^ error commutes with logicals (we expect this to fail for MWPM)
    assert not np.all(pt.bsp(recovery ^ error, code.logicals.T) == 0), (
        'recovery ^ error ({} ^ {}) does commute with logicals for MWPM decoder.'
        .format(recovery, error))
示例#4
0
def test_planar_mps_decoder_positive_max_coset_probability(mode):
    # parameters
    code = PlanarCode(9, 9)
    decoder = PlanarMPSDecoder(chi=48, mode=mode)
    error_model = BiasedDepolarizingErrorModel(bias=100)
    error_probability = 0.41
    # logged run values
    error = pt.unpack([
        "c96aa012210dc2254031f15d9ce80c871fb864b510c91086e112a018f8aece7406638fdc00",
        290
    ])
    syndrome = pt.unpack(["8f59cd273bd1c027b3b925085af85f2aaf22", 144])
    assert np.array_equal(syndrome, pt.bsp(error, code.stabilizers.T))
    # debug
    # print(code.ascii_art(syndrome, code.new_pauli(error)))
    # decode
    prob_dist = error_model.probability_distribution(error_probability)
    any_recovery = decoder.sample_recovery(code, syndrome)
    # coset probabilities
    coset_ps, recoveries = decoder._coset_probabilities(
        prob_dist, any_recovery)
    print('mode={}, coset_ps={}'.format(mode, coset_ps))
    max_coset_p, max_recovery = max(
        zip(coset_ps, recoveries),
        key=lambda coset_p_recovery: coset_p_recovery[0])
    success = np.all(
        pt.bsp(max_recovery.to_bsf() ^ error, code.logicals.T) == 0)
    print('### success=', success)
    assert mp.isfinite(
        max_coset_p
    ) and max_coset_p > 0, 'Max coset probability not as expected'
示例#5
0
def test_planar_mps_decoder_svd_does_not_converge():
    code = PlanarCode(21, 21)
    decoder = PlanarMPSDecoder(chi=4)
    error = pt.unpack((
        '001281500200080080000000000080001000000c0000002012000000801040004000000100000000004000002100000800800000000000'
        '02000100028022001000002044841000080080008110020000400801200000801040112008010004400000000000000002000000402201'
        '10040000000000000481000200000601000080080000000820200020000000008820000100000010045000004000010000000000000000'
        '40010000840010200008000400024000880000000004000000004000200890040001082000000000000002000000',
        1682))
    syndrome = pt.bsp(error, code.stabilizers.T)
    recovery = decoder.decode(code, syndrome)  # no error raised
    assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
        'recovery ^ error ({} ^ {}) does not commute with stabilizers.'.format(
            recovery, error))
示例#6
0
def test_planar_mps_decoder_cosets_probability_equivalence(
        sample_pauli_f, sample_pauli_g):
    decoder = PlanarMPSDecoder(chi=8)
    # probabilities
    prob_dist = BiasedDepolarizingErrorModel(bias=10).probability_distribution(
        probability=0.1)
    # coset probabilities
    coset_f_ps, _ = decoder._coset_probabilities(prob_dist, sample_pauli_f)
    coset_g_ps, _ = decoder._coset_probabilities(prob_dist, sample_pauli_g)
    print('#Pr(fG)=', coset_f_ps)
    print('#Pr(gG)=', coset_g_ps)
    assert all(_is_close(
        coset_f_ps, coset_g_ps, rtol=1e-12,
        atol=0)), ('Coset probabilites do not satisfy Pr(fG) ~= Pr(gG)')
示例#7
0
def test_planar_mps_decoder_zero_norm_in_left_canonical_form():
    # parameters
    random_seed = 13
    code = PlanarCode(7, 7)
    error_model = BitFlipErrorModel()
    decoder = PlanarMPSDecoder(chi=6, mode='c')
    error_probability = 0.1
    # single run
    error = error_model.generate(code, error_probability,
                                 np.random.default_rng(random_seed))
    syndrome = pt.bsp(error, code.stabilizers.T)
    decoder.decode(code,
                   syndrome,
                   error_model=error_model,
                   error_probability=error_probability)
示例#8
0
def test_planar_mps_decoder_cosets_probability_stp():
    # parameters
    sample = PlanarCode(3, 4).new_pauli().site('Y', (2, 0), (2, 4))
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)

    # coset probabilities exact
    exact_coset_ps, _ = PlanarMPSDecoder(mode='a')._coset_probabilities(
        prob_dist, sample)
    print('#exact_coset_ps=', exact_coset_ps)

    # coset probabilities approx (chi=6)
    approx_coset_ps, _ = PlanarMPSDecoder(chi=6,
                                          mode='a')._coset_probabilities(
                                              prob_dist, sample)
    print('#approx_coset_ps=', approx_coset_ps)
    assert all(
        _is_close(exact_coset_ps, approx_coset_ps, rtol=1e-14,
                  atol=0)), ('approx_coset_ps not close to exact_coset_ps')

    # coset probabilities approx (chi=6, stp=0)
    coset_ps, _ = PlanarMPSDecoder(chi=6, mode='a',
                                   stp=0)._coset_probabilities(
                                       prob_dist, sample)
    print('#coset_ps (chi=6, stp=0)=', coset_ps)
    assert all(_is_close(
        approx_coset_ps, coset_ps, rtol=0,
        atol=0)), ('coset_ps (chi=6, stp=0) not equal to approx_coset_ps')

    # coset probabilities approx (chi=6, stp=1)
    coset_ps, _ = PlanarMPSDecoder(chi=6, mode='a',
                                   stp=1)._coset_probabilities(
                                       prob_dist, sample)
    print('#coset_ps (chi=6, stp=1)=', coset_ps)
    assert all(_is_close(
        exact_coset_ps, coset_ps, rtol=0,
        atol=0)), ('coset_ps (chi=6, stp=1) not equal to exact_coset_ps')

    # coset probabilities approx (chi=6, stp=0.5)
    coset_ps, _ = PlanarMPSDecoder(chi=6, mode='a',
                                   stp=0.5)._coset_probabilities(
                                       prob_dist, sample)
    print('#coset_ps (chi=6, stp=0.5)=', coset_ps)
    assert all(_is_close(
        exact_coset_ps, coset_ps, rtol=1e-10,
        atol=0)), ('coset_ps (chi=6, stp=0.5) not close to exact_coset_ps')
    assert all(_is_close(
        approx_coset_ps, coset_ps, rtol=1e-10,
        atol=0)), ('coset_ps (chi=6, stp=0.5) not close to approx_coset_ps')
示例#9
0
def test_planar_mps_decoder_decode(error_pauli, chi, caplog):
    with caplog.at_level(logging.WARN):
        error = error_pauli.to_bsf()
        code = error_pauli.code
        syndrome = pt.bsp(error, code.stabilizers.T)
        decoder = PlanarMPSDecoder(chi=chi)
        recovery = decoder.decode(code, syndrome)
        assert np.array_equal(pt.bsp(
            recovery, code.stabilizers.T), syndrome), (
                'recovery {} does not give the same syndrome as the error {}'.
                format(recovery, error))
        assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
            'recovery ^ error ({} ^ {}) does not commute with stabilizers.'.
            format(recovery, error))
        assert len(caplog.records) == 0, 'Unexpected log messages: {}'.format(
            caplog.text)
示例#10
0
def test_planar_mps_decoder_decode_logging_nonpositivefinite_max_coset_probability(
        caplog):
    # taken from corner case mode='a' of test_planar_mps_decoder_positive_max_coset_probability
    code = PlanarCode(9, 9)
    decoder = PlanarMPSDecoder(chi=48, mode='a')
    error_model = BiasedDepolarizingErrorModel(bias=100)
    error_probability = 0.41
    error = pt.unpack([
        "c96aa012210dc2254031f15d9ce80c871fb864b510c91086e112a018f8aece7406638fdc00",
        290
    ])
    syndrome = pt.unpack(["8f59cd273bd1c027b3b925085af85f2aaf22", 144])
    assert np.array_equal(syndrome, pt.bsp(error, code.stabilizers.T))
    decoder.decode(code,
                   syndrome,
                   error_model=error_model,
                   error_probability=error_probability)
    assert 'NON-POSITIVE-FINITE MAX COSET PROBABILITY' in caplog.text, (
        'Non-positive-finite max coset probability not logged')
示例#11
0
def test_planar_mps2d_contract():
    code = PlanarCode(3, 3)
    sample = code.new_pauli().site('Y', (2, 0), (2, 4))
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)
    tnc = PlanarMPSDecoder.TNC()
    tn = tnc.create_tn(prob_dist, sample)
    result = tt.mps2d.contract(tn)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= result <= 1, 'Contracted tensor network not within bounds'
示例#12
0
def test_planar_mps_decoder_cosets_probability_inequality_bsv(mode, rtol):
    code = PlanarCode(25, 25)
    decoder = PlanarMPSDecoder(chi=5, mode=mode)
    # probabilities
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)
    # coset probabilities for null Pauli
    coset_ps, _ = decoder._coset_probabilities(prob_dist, code.new_pauli())
    coset_i_p, coset_x_p, coset_y_p, coset_z_p = coset_ps
    # expect Pr(IG) > Pr(XG) ~= Pr(ZG) > Pr(YG)
    print('{} > {} ~= {} > {}. rtol={}'.format(
        coset_i_p, coset_x_p, coset_z_p, coset_y_p,
        abs(coset_x_p - coset_z_p) / abs(coset_z_p)))
    print('types: Pr(IG):{}, Pr(XG):{}, Pr(ZG):{}, Pr(YG):{}'.format(
        type(coset_i_p), type(coset_x_p), type(coset_z_p), type(coset_y_p)))
    assert coset_i_p > coset_x_p, 'Coset probabilites do not satisfy Pr(IG) > Pr(XG)'
    assert coset_i_p > coset_z_p, 'Coset probabilites do not satisfy Pr(IG) > Pr(ZG)'
    assert _is_close(
        coset_x_p, coset_z_p, rtol=rtol,
        atol=0), 'Coset probabilites do not satisfy Pr(XG) ~= Pr(ZG)'
    assert coset_x_p > coset_y_p, 'Coset probabilites do not satisfy Pr(XG) > Pr(YG)'
    assert coset_z_p > coset_y_p, 'Coset probabilites do not satisfy Pr(ZG) > Pr(YG)'
示例#13
0
def test_planar_mps_decoder_sample_recovery(error_pauli):
    error = error_pauli.to_bsf()
    code = error_pauli.code
    syndrome = pt.bsp(error, code.stabilizers.T)
    recovery_pauli = PlanarMPSDecoder.sample_recovery(code, syndrome)
    recovery = recovery_pauli.to_bsf()
    assert np.array_equal(pt.bsp(recovery, code.stabilizers.T), syndrome), (
        'recovery {} does not give the same syndrome as the error {}'.format(
            recovery, error))
    assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
        'recovery ^ error ({} ^ {}) does not commute with stabilizers.'.format(
            recovery, error))
示例#14
0
文件: test_app.py 项目: silky/qecsim
def test_run_seeded():
    code = PlanarCode(5, 5)
    error_model = DepolarizingErrorModel()
    decoder = PlanarMPSDecoder()
    error_probability = 0.101
    max_runs = 5
    random_seed = 5
    data1 = app.run(code, error_model, decoder, error_probability, max_runs=max_runs, random_seed=random_seed)
    data2 = app.run(code, error_model, decoder, error_probability, max_runs=max_runs, random_seed=random_seed)
    # remove wall_time from data
    for data in (data1, data2):
        del data['wall_time']
    assert data1 == data2, 'Identically seeded runs are not the same. '
示例#15
0
def test_planar_mps_decoder_zero_max_coset_probability(code, chi):
    decoder = PlanarMPSDecoder(chi=chi, mode='c')
    error_model = BiasedDepolarizingErrorModel(bias=1000)
    random_seed = 69
    # probabilities
    probability = 0.4
    prob_dist = error_model.probability_distribution(probability)
    # error
    error = error_model.generate(code, probability,
                                 np.random.default_rng(random_seed))
    # syndrome
    syndrome = pt.bsp(error, code.stabilizers.T)
    # any_recovery
    any_recovery = decoder.sample_recovery(code, syndrome)
    # coset probabilities
    coset_ps, _ = decoder._coset_probabilities(prob_dist, any_recovery)
    print(coset_ps)
    max_coset_p = max(coset_ps)
    assert mp.isfinite(
        max_coset_p
    ) and max_coset_p > 0, 'Max coset probability out of bounds {}'.format(
        coset_ps)
示例#16
0
def test_planar_rmps_mps_accuracy(error_pauli):
    error = error_pauli.to_bsf()
    code = error_pauli.code
    syndrome = pt.bsp(error, code.stabilizers.T)
    recovery_pauli = PlanarRMPSDecoder.sample_recovery(code, syndrome)
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)
    rmps_coset_ps, _ = PlanarRMPSDecoder(chi=8)._coset_probabilities(
        prob_dist, recovery_pauli)
    print('#rmps_coset_ps (chi=8)=', rmps_coset_ps)
    mps_coset_ps, _ = PlanarMPSDecoder(chi=8)._coset_probabilities(
        prob_dist, recovery_pauli)
    print('#mps_coset_ps (chi=8)=', mps_coset_ps)
    assert all(_is_close(
        rmps_coset_ps, mps_coset_ps, rtol=1e-1,
        atol=0)), ('rmps_coset_ps (chi=8) not close to mps_coset_ps (chi=8)')
示例#17
0
def test_planar_rmps_mps_performance():
    n_run = 5
    code = PlanarCode(21, 21)
    error_model = DepolarizingErrorModel()
    error_probability = 0.2

    def _timed_runs(decoder):
        start_time = time.time()
        for _ in range(n_run):
            error = error_model.generate(code, error_probability)
            syndrome = pt.bsp(error, code.stabilizers.T)
            recovery = decoder.decode(code, syndrome)
            assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
                'recovery ^ error ({} ^ {}) does not commute with stabilizers.'
                .format(recovery, error))
        return time.time() - start_time

    rmps_time = _timed_runs(PlanarRMPSDecoder(chi=8))
    mps_time = _timed_runs(PlanarMPSDecoder(chi=8))
    # expect rmps_time < mps_time
    print('rmps_time = {} < {} = mps_time'.format(rmps_time, mps_time))
    assert rmps_time < mps_time, 'RMPS decoder slower than MPS decoder'
示例#18
0
def test_planar_mps_decoder_small_codes_exact_approx():
    code = PlanarCode(4, 4)
    exact_decoder = PlanarMPSDecoder()
    approx_decoder = PlanarMPSDecoder(chi=8)
    identity = code.new_pauli()
    # probabilities
    prob_dist = BiasedDepolarizingErrorModel(bias=10).probability_distribution(
        probability=0.1)
    # coset probabilities
    exact_coset_ps, _ = exact_decoder._coset_probabilities(prob_dist, identity)
    approx_coset_ps, _ = approx_decoder._coset_probabilities(
        prob_dist, identity)
    print('#exact Pr(G)=', exact_coset_ps)
    print('#approx Pr(G)=', approx_coset_ps)
    assert all(_is_close(
        exact_coset_ps, approx_coset_ps, rtol=1e-11, atol=0)), (
            'Coset probabilites do not satisfy exact Pr(G) ~= approx Pr(G)')
示例#19
0
def test_planar_mps_mwpm_performance():
    n_run = 5
    code = PlanarCode(25, 25)
    error_model = DepolarizingErrorModel()
    error_probability = 0.4
    rng = np.random.default_rng(13)

    def _timed_runs(decoder):
        start_time = time.time()
        for _ in range(n_run):
            error = error_model.generate(code, error_probability, rng)
            syndrome = pt.bsp(error, code.stabilizers.T)
            recovery = decoder.decode(code, syndrome)
            assert np.all(pt.bsp(recovery ^ error, code.stabilizers.T) == 0), (
                'recovery ^ error ({} ^ {}) does not commute with stabilizers.'
                .format(recovery, error))
        return time.time() - start_time

    mps_time = _timed_runs(PlanarMPSDecoder(chi=6))
    mwpm_time = _timed_runs(PlanarMWPMDecoder())
    # expect mps_time < mwpm_time
    print('mps_time = {} < {} = mwpm_time'.format(mps_time, mwpm_time))
    assert mps_time < mwpm_time, 'MPS decoder slower than MWPM decoder'
示例#20
0
import multiprocessing as mp
import collections
import itertools
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
import qecsim
from qecsim import app
from qecsim.models.generic import PhaseFlipErrorModel
from qecsim.models.planar import PlanarCode, PlanarMPSDecoder

# set models
codes = [PlanarCode(*size) for size in [(3, 3), (5, 5)]]
error_model = PhaseFlipErrorModel()
decoder = PlanarMPSDecoder()
# set physical error probabilities
error_probability_min, error_probability_max = 0, 0.4
error_probabilities = np.linspace(error_probability_min, error_probability_max,
                                  5)
# set max_runs for each probability
max_runs = 10

# print run parameters
print('Codes:', [code.label for code in codes])
print('Error model:', error_model.label)
print('Decoder:', decoder.label)
print('Error probabilities:', error_probabilities)
print('Maximum runs:', max_runs)


def parallel_step_p(code, error_model, decoder, max_runs, error_probability):
示例#21
0
def test_planar_mps2d_contract_mask():
    code = PlanarCode(3, 4)
    sample = code.new_pauli().site('Y', (2, 0), (2, 4))
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)
    tnc = PlanarMPSDecoder.TNC()
    tn = tnc.create_tn(prob_dist, sample)
    rng = np.random.default_rng()

    # tn_contract exact
    exact_result = tt.mps2d.contract(tn)
    assert isinstance(exact_result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= exact_result <= 1, 'Contracted tensor network not within bounds'
    print('#exact_result=', exact_result)

    # tn_contract approx
    approx_result = tt.mps2d.contract(tn, chi=2)
    assert isinstance(approx_result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= approx_result <= 1, 'Contracted tensor network not within bounds'
    print('#approx_result=', approx_result, '#rtol=',
          abs(approx_result - exact_result) / abs(exact_result))
    assert _is_close(exact_result, approx_result, rtol=1e-4,
                     atol=0), 'tn_contract(chi=2) not as expected'

    # tn_contract with truncate (chi, mask=0)
    stp = 0  # skip truncate probability
    mask = rng.choice((True, False), size=tn.shape, p=(1 - stp, stp))
    result = tt.mps2d.contract(tn, chi=2, mask=mask)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= result <= 1, 'Contracted tensor network not within bounds'
    print('#result (chi=2, mask=0)=', result, '#rtol=',
          abs(result - approx_result) / abs(approx_result))
    assert approx_result == result, 'tn_contract(chi=2, mask=0) not same as approx_result'

    # tn_contract with truncate (chi, mask=1)
    stp = 1  # skip truncate probability
    mask = rng.choice((True, False), size=tn.shape, p=(1 - stp, stp))
    result = tt.mps2d.contract(tn, chi=2, mask=mask)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= result <= 1, 'Contracted tensor network not within bounds'
    print('#result (chi=2, mask=1)=', result, '#rtol=',
          abs(result - exact_result) / abs(exact_result))
    assert exact_result == result, 'tn_contract(chi=2, mask=1) not same as exact_result'

    # tn_contract with truncate (chi, mask=0.5)
    stp = 0.5  # skip truncate probability
    mask = rng.choice((True, False), size=tn.shape, p=(1 - stp, stp))
    result = tt.mps2d.contract(tn, chi=2, mask=mask)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= result <= 1, 'Contracted tensor network not within bounds'
    print('#result (chi=2, mask=0.5)=', result, '#rtol=',
          abs(result - exact_result) / abs(exact_result))
    assert exact_result != result, 'tn_contract(chi=2, mask=0.5) should not equal exact_result'
    assert approx_result != result, 'tn_contract(chi=2, mask=0.5) should not equal approx_result'
    assert _is_close(
        exact_result, result, rtol=1e-4,
        atol=0), 'tn_contract(chi=2, mask=0.5) not close to exact_result'
    print('#result (chi=2, mask=0.5)=', result, '#rtol=',
          abs(result - approx_result) / abs(approx_result))
    assert _is_close(
        approx_result, result, rtol=1e-4,
        atol=0), ('tn_contract(chi=2, mask=0.5) not close to approx_result')
示例#22
0
def test_planar_mps_functions():
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)
    rng = np.random.default_rng()
    tnc = PlanarMPSDecoder.TNC()
    # column bra, mpo and ket
    bra = [
        tnc.create_h_node(prob_dist, 'X', 'nw'),
        tnc.create_s_node('w'),
        tnc.create_h_node(prob_dist, 'Z', 'sw'),
    ]
    mpo = [
        tnc.create_s_node('n'),
        tnc.create_v_node(prob_dist, 'Y'),
        tnc.create_s_node('s'),
    ]
    ket = [
        tnc.create_h_node(prob_dist, 'Z', 'ne'),
        tnc.create_s_node('e'),
        tnc.create_h_node(prob_dist, 'I', 'se'),
    ]
    # tensor network corresponding to column bra, mpo and ket
    tn = np.array([bra, mpo, ket], dtype=object).transpose()
    expected = 0.00096790123456790152

    # exact contraction for expected
    result = tt.mps.contract_pairwise(bra, mpo)
    result = tt.mps.inner_product(result, ket)
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14,
                     atol=0), 'Exact contraction not as expected'

    # exact contraction with contract_ladder
    result = tt.mps.contract_pairwise(bra, mpo)
    result = tt.mps.contract_pairwise(result, ket)
    result = tt.mps.contract_ladder(result)[0, 0, 0, 0]
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14,
                     atol=0), 'Exact contraction not as expected'

    # exact contraction with lcf
    result = tt.mps.left_canonical_form(bra)
    result = tt.mps.contract_pairwise(result, mpo)
    result = tt.mps.left_canonical_form(result)
    result = tt.mps.inner_product(result, ket)
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14,
                     atol=0), 'Exact contraction with lcf not as expected'

    # exact contraction with rcf
    result = tt.mps.right_canonical_form(bra)
    result = tt.mps.contract_pairwise(result, mpo)
    result = tt.mps.right_canonical_form(result)
    result = tt.mps.inner_product(result, ket)
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14,
                     atol=0), 'Exact contraction with rcf not as expected'

    # exact contraction with truncate
    result = tt.mps.contract_pairwise(bra, mpo)
    result, norm = tt.mps.truncate(result)
    result = tt.mps.inner_product(result, ket)
    result *= norm
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14,
                     atol=0), 'Exact contraction with truncate not as expected'

    # exact contraction with normalise lcf
    result, norm1 = tt.mps.left_canonical_form(bra, normalise=True)
    result = tt.mps.contract_pairwise(result, mpo)
    result, norm2 = tt.mps.left_canonical_form(result, normalise=True)
    result = tt.mps.inner_product(result, ket)
    result *= norm1 * norm2
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(
        expected, result, rtol=1e-14,
        atol=0), 'Exact contraction with normalise lcf not as expected'

    # exact contraction with normalise rcf
    result, norm1 = tt.mps.right_canonical_form(bra, normalise=True)
    result = tt.mps.contract_pairwise(result, mpo)
    result, norm2 = tt.mps.right_canonical_form(result, normalise=True)
    result = tt.mps.inner_product(result, ket)
    result *= norm1 * norm2
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(
        expected, result, rtol=1e-14,
        atol=0), 'Exact contraction with normalise rcf not as expected'

    # approximate contraction with truncate (chi)
    result = tt.mps.contract_pairwise(bra, mpo)
    result, norm = tt.mps.truncate(result, chi=2)
    result = tt.mps.inner_product(result, ket)
    result *= norm
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(
        expected, result, rtol=1e-14,
        atol=0), 'Approx. contraction with truncate (chi) not as expected'

    # approximate contraction with truncate (tol)
    result = tt.mps.contract_pairwise(bra, mpo)
    result, norm = tt.mps.truncate(result, tol=1e-8)
    result = tt.mps.inner_product(result, ket)
    result *= norm
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(
        expected, result, rtol=1e-14,
        atol=0), 'Approx. contraction with truncate (tol) not as expected'

    # tn_contract
    result = tt.mps2d.contract(tn)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14,
                     atol=0), 'Exact tn contraction not as expected'

    # tn_contract with truncate (chi)
    result = tt.mps2d.contract(tn, chi=2)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(
        expected, result, rtol=1e-14,
        atol=0), 'Approx. tn contraction with truncate (chi) not as expected'

    # tn_contract with truncate (tol)
    result = tt.mps2d.contract(tn, tol=1e-8)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(
        expected, result, rtol=1e-14,
        atol=0), 'Approx. tn contraction with truncate (tol) not as expected'

    # tn_contract with truncate (chi, mask)
    stp = 0.2  # skip truncate probability
    mask = rng.choice((True, False), size=tn.shape, p=(1 - stp, stp))
    result = tt.mps2d.contract(tn, chi=2, mask=mask)
    assert isinstance(result,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    print('#result=', result, '#rtol=', abs(result - expected) / abs(expected))
    assert _is_close(expected, result, rtol=1e-14, atol=0), (
        'Approx. tn contraction with truncate (chi, mask) not as expected')
示例#23
0
文件: test_app.py 项目: silky/qecsim
        self.decoding = decoding

    def decode(self, code, syndrome, **kwargs):
        return self.decoding

    @property
    def label(self):
        return 'fixed'


@pytest.mark.parametrize('code, error_model, decoder', [
    # each code with each valid decoder
    (Color666Code(5), DepolarizingErrorModel(), Color666MPSDecoder(chi=8)),
    (FiveQubitCode(), DepolarizingErrorModel(), NaiveDecoder()),
    (PlanarCode(5, 5), DepolarizingErrorModel(), PlanarCMWPMDecoder()),
    (PlanarCode(5, 5), DepolarizingErrorModel(), PlanarMPSDecoder(chi=6)),
    (PlanarCode(5, 5), DepolarizingErrorModel(), PlanarMWPMDecoder()),
    (PlanarCode(5, 5), DepolarizingErrorModel(), PlanarRMPSDecoder(chi=6)),
    (PlanarCode(4, 5), BitPhaseFlipErrorModel(), PlanarYDecoder()),
    (RotatedPlanarCode(7, 7), DepolarizingErrorModel(), RotatedPlanarMPSDecoder(chi=8)),
    (RotatedPlanarCode(7, 7), DepolarizingErrorModel(), RotatedPlanarRMPSDecoder(chi=8)),
    (RotatedPlanarCode(7, 7), BiasedDepolarizingErrorModel(100), RotatedPlanarSMWPMDecoder()),
    (RotatedToricCode(6, 6), BiasedDepolarizingErrorModel(100), RotatedToricSMWPMDecoder()),
    (SteaneCode(), DepolarizingErrorModel(), NaiveDecoder()),
    (ToricCode(5, 5), DepolarizingErrorModel(), ToricMWPMDecoder()),
    # each generic noise model
    (PlanarCode(5, 5), BiasedDepolarizingErrorModel(10), PlanarMPSDecoder(chi=6)),
    (PlanarCode(5, 5), BiasedYXErrorModel(10), PlanarMPSDecoder(chi=6)),
    (PlanarCode(5, 5), BitFlipErrorModel(), PlanarMPSDecoder(chi=6)),
    (PlanarCode(5, 5), BitPhaseFlipErrorModel(), PlanarMPSDecoder(chi=6)),
    (PlanarCode(5, 5), CenterSliceErrorModel((0.2, 0.8, 0), 0.5), PlanarMPSDecoder(chi=6)),
示例#24
0
def test_planar_mps_decoder_new_invalid_parameters(chi, mode, stp, tol):
    with pytest.raises((ValueError, TypeError),
                       match=r"^PlanarMPSDecoder") as exc_info:
        PlanarMPSDecoder(chi=chi, mode=mode, stp=stp, tol=tol)
    print(exc_info)
示例#25
0
def test_planar_mps_decoder_new_valid_parameters(chi, mode, stp, tol):
    PlanarMPSDecoder(chi=chi, mode=mode, stp=stp, tol=tol)  # no error raised
示例#26
0
def test_planar_mps_decoder_properties():
    decoder = PlanarMPSDecoder(chi=8, mode='r', tol=1e-14)
    assert isinstance(decoder.label, str)
    assert isinstance(repr(decoder), str)
    assert isinstance(str(decoder), str)