def test_rotated_planar_rmps_decoder_cosets_probability_pair_optimisation(
        mode):
    code = RotatedPlanarCode(5, 5)
    decoder = RotatedPlanarRMPSDecoder(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)')
def test_rotated_planar_mps_decoder_small_codes_exact_approx():
    code = RotatedPlanarCode(5, 5)
    exact_decoder = RotatedPlanarMPSDecoder()
    approx_decoder = RotatedPlanarMPSDecoder(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)')
def test_rotated_planar_mps_decoder_cosets_probability_inequality(mode, rtol):
    code = RotatedPlanarCode(25, 25)
    decoder = RotatedPlanarMPSDecoder(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)'
def test_rotated_planar_rmps_mps_performance():
    from qecsim.models.rotatedplanar import RotatedPlanarMPSDecoder
    n_run = 5
    code = RotatedPlanarCode(17, 17)
    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(RotatedPlanarRMPSDecoder(chi=8))
    mps_time = _timed_runs(RotatedPlanarMPSDecoder(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'
Exemple #5
0
    @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)),
    (PlanarCode(5, 5), DepolarizingErrorModel(), PlanarMPSDecoder(chi=6)),
    (PlanarCode(5, 5), PhaseFlipErrorModel(), PlanarMPSDecoder(chi=6)),
])
def test_run_once(code, error_model, decoder):
def test_rotated_planar_pauli_properties(size):
    code = RotatedPlanarCode(*size)
    pauli = code.new_pauli()
    assert pauli.code == code
    assert isinstance(repr(pauli), str)
    assert isinstance(str(pauli), str)
def test_rotated_planar_pauli_operator_invalid_index(size, index):
    pauli = RotatedPlanarCode(*size).new_pauli()
    with pytest.raises(IndexError):
        pauli.operator(index)
def test_rotated_planar_lattice_is_in_site_bounds(index, expected):
    lattice = RotatedPlanarCode(3, 5)
    assert lattice.is_in_site_bounds(index) == expected
    (5, 3),
    (4, 6),
    (6, 4),
    (3, 4),
    (4, 3),
])
def test_rotated_planar_pauli_properties(size):
    code = RotatedPlanarCode(*size)
    pauli = code.new_pauli()
    assert pauli.code == code
    assert isinstance(repr(pauli), str)
    assert isinstance(str(pauli), str)


@pytest.mark.parametrize('planar_pauli', [
    RotatedPlanarCode(5, 5).new_pauli(),
    RotatedPlanarCode(5, 6).new_pauli().plaquette((1, 1)).plaquette((3, 2)),
    RotatedPlanarCode(5, 5).new_pauli().logical_x().plaquette(
        (-1, 0)).plaquette((4, 1)),
    RotatedPlanarCode(6, 5).new_pauli().logical_z().plaquette(
        (1, 5)).plaquette((3, -1)),
    RotatedPlanarCode(7, 5).new_pauli().logical_x().plaquette(
        (0, 2)).plaquette((1, 1)),
    RotatedPlanarCode(5, 7).new_pauli().logical_z().plaquette(
        (1, -1)).plaquette((2, 4)),
])
def test_rotated_planar_pauli_new_to_bsf(planar_pauli):
    assert planar_pauli.code.new_pauli(
        planar_pauli.to_bsf()) == planar_pauli, (
            'Conversion to_bsf+from_bsf does not result in equality.')
def test_rotated_planar_code_new_invalid_parameters(rows, columns):
    with pytest.raises((ValueError, TypeError), match=r"^RotatedPlanarCode") as exc_info:
        RotatedPlanarCode(rows, columns)
    print(exc_info)
def test_rotated_planar_code_properties(size):
    code = RotatedPlanarCode(*size)
    assert isinstance(code.label, str)
    assert isinstance(repr(code), str)
Exemple #12
0
from qecsim.models.rotatedplanar import RotatedPlanarCode, RotatedPlanarMPSDecoder


if __name__=='__main__':

    def square(a):
        return a**2
    vsquare=np.vectorize(square)
    layout='rotated'
    bdry_name='surface'

    sizes= range(6,7,2)
    # codes_and_size = [PlanarCode(*(size,size)) for size in sizes]

    rotsizes= range(17,18,2)
    codes_and_size = [RotatedPlanarCode(*(size,size)) for size in rotsizes]
    p_min,p_max=0.01,0.50
    error_probabilities=np.linspace(p_min,p_max,8)

    #export data
    # code_names=['spiral_XZ','random_XZ','random_XZ_YZ','random_XY']
    # code_names=['random_all','random_XZ_YZ']
    # # code_names=['spiral_XZ','random_XZ','random_all','random_XY']
    # code_names=['XY','CSS']

    bias_list=[50]

    code_names=['XY','random_XZ_YZ4','random_XZ_YZ3','random_XZ_YZ2','random_XZ_YZ1','random_XZ_YZ0','rotXY']
    
    code_names=['random_rot_XZ_YZ','rotXY']
def test_rotated_planar_lattice_size(size):
    lattice = RotatedPlanarCode(*size)
    assert lattice.size == size
def test_rotated_planar_code_validate(size):
    code = RotatedPlanarCode(*size)
    code.validate()  # no error raised
Exemple #15
0
@pytest.mark.parametrize('filename', [
    os.path.join(FILES_DIR, 'incorrect_length_in_packed_error.jsonl'),
    os.path.join(FILES_DIR, 'incorrect_length_in_packed_error2.jsonl')
])
def test_file_error_model_generate_incorrect_length_in_packed_error(filename):
    fem = FileErrorModel(filename)
    fqc = FiveQubitCode()
    with pytest.raises(ValueError):
        fem.generate(fqc, 0.4)


# TESTS FOR GENERATED SAMPLES BELOW

@pytest.mark.parametrize('code, filename, decoder', [
    (RotatedPlanarCode(5, 5),
     os.path.join(FILES_DIR, 'rotated_planar_code_size_5_J_0.1_p_2.jsonl'),
     RotatedPlanarMPSDecoder(chi=8)),
    (RotatedPlanarCode(5, 5),
     os.path.join(FILES_DIR, 'rotated_planar_code_size_5_J_0.1_p_4.jsonl'),
     RotatedPlanarMPSDecoder(chi=8)),
    (RotatedPlanarCode(5, 5),
     os.path.join(FILES_DIR, 'rotated_planar_code_size_5_J_0.1_p_6.jsonl'),
     RotatedPlanarMPSDecoder(chi=8)),
])
def test_file_error_model_generated_sample_error_probability(code, filename, decoder):
    with CliRunner().isolated_filesystem():  # isolate from logging_qecsim.ini
        # error model and probability from sample
        error_model = FileErrorModel(filename, start=1000)
        e_prob = error_model._probability
        # runs (repeat many times to ensure physical_error_rate is close to error_probability)
def test_rotated_planar_code_logicals():
    assert len(RotatedPlanarCode(5, 5).logicals) == 2
def test_rotated_planar_code_stabilizers(size, expected):
    assert len(RotatedPlanarCode(*size).stabilizers) == expected
def test_rotated_planar_code_n_k_d(size, expected):
    code = RotatedPlanarCode(*size)
    assert code.n_k_d == expected
Exemple #19
0
    print('Forward contraction result: ', repr(result_forwards))
    assert isinstance(result_forwards,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= result_forwards <= 1, 'Contracted tensor network not within bounds'
    result_backwards = tt.mps2d.contract(tn, start=-1, step=-1)
    print('Backward contraction result:', repr(result_backwards))
    assert isinstance(result_backwards,
                      mp.mpf), 'Contracted tensor network is not an mp.mpf'
    assert 0 <= result_backwards <= 1, 'Contracted tensor network not within bounds'
    assert _is_close(result_forwards, result_backwards, rtol=1e-14, atol=0), (
        'Contracting forwards does not give the same result as contracting backwards'
    )


@pytest.mark.parametrize('pauli', [
    (RotatedPlanarCode(3, 3).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(4, 4).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(3, 4).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(4, 3).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(5, 5).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(4, 5).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(5, 4).new_pauli().site('Y', (2, 0), (2, 4))),
    (RotatedPlanarCode(6, 6).new_pauli().site('Y', (2, 0), (2, 4))),
])
def test_rotatedplanar_mps2d_contract(pauli):
    prob_dist = DepolarizingErrorModel().probability_distribution(0.1)
    tnc = RotatedPlanarRMPSDecoder.TNC()
    tn = tnc.create_tn(prob_dist, pauli)
    print('tn.shape=', tn.shape)
    result = tt.mps2d.contract(tn)
    assert isinstance(result,
        ('asdf', 'c', None),  # invalid chi
        (None, None, None),  # invalid mode
        (None, 't', None),  # invalid mode
        (None, 2, None),  # invalid mode
        (None, 'c', -1),  # invalid tol
        (None, 'c', 'asdf'),  # invalid tol
    ])
def test_rotated_planar_mps_decoder_new_invalid_parameters(chi, mode, tol):
    with pytest.raises((ValueError, TypeError),
                       match=r"^RotatedPlanarMPSDecoder") as exc_info:
        RotatedPlanarMPSDecoder(chi=chi, mode=mode, tol=tol)
    print(exc_info)


@pytest.mark.parametrize('error_pauli', [
    RotatedPlanarCode(3, 3).new_pauli().site('X', (1, 0)).site('Y', (2, 2)),
    RotatedPlanarCode(5, 5).new_pauli().site('X',
                                             (1, 1)).site('Y', (2, 2)).site(
                                                 'Z', (3, 2)),
    RotatedPlanarCode(7, 7).new_pauli().site('X',
                                             (4, 2)).site('Y', (3, 3)).site(
                                                 'Z', (6, 4), (6, 3)),
])
def test_rotated_planar_mps_decoder_sample_recovery(error_pauli):
    print('ERROR:')
    print(error_pauli)
    error = error_pauli.to_bsf()
    code = error_pauli.code
    syndrome = pt.bsp(error, code.stabilizers.T)
    print('SYNDROME:')
    print(code.ascii_art(syndrome=syndrome))
     ]
     layout = 'planar'
     num_realiz = 1
     bias_str = 'Z'
     max_runs = 20000
 elif code_name == 'XY':
     codes_and_size = [
         PlanarCode(*(size, size)) for size in sizes
     ]
     layout = 'planar'
     bias_str = 'Y'
     num_realiz = 1
     max_runs = 20000
 elif code_name == 'rotXY':
     codes_and_size = [
         RotatedPlanarCode(*(size, size)) for size in rotsizes
     ]
     decoder = _rotatedplanarmpsdecoder_def.RotatedPlanarMPSDecoder_def(
         chi=chi_val)
     layout = 'rotated'
     bias_str = 'Y'
     num_realiz = 1
     max_runs = 10000
 elif code_name == 'rot_spiral':
     codes_and_size = [
         RotatedPlanarCode(*(size, size)) for size in rotsizes
     ]
     decoder = _rotatedplanarmpsdecoder_def.RotatedPlanarMPSDecoder_def(
         chi=chi_val)
     layout = 'rotated'
     bias_str = 'Y'
def test_rotated_planar_lattice_is_virtual_plaquette(index, expected):
    lattice = RotatedPlanarCode(3, 5)
    assert lattice.is_virtual_plaquette(index) == expected
Exemple #23
0
    np.random.seed(1234 * (run_id + 1))

    def square(a):
        return a**2
    
    vsquare=np.vectorize(square)
    bdry_name='rotated'
    code_name = 'rotspiral'
    
    error_probability= err_prob

    perm_rates=[0,0,0,0,0,0]

    from itertools import cycle
    
    code = RotatedPlanarCode(*(code_size,code_size))
    decoder = _rotatedplanarmpsdecoder_defp.RotatedPlanarMPSDecoder_defp(chi=chi_val)
    layout='rotated'
    bias_str='Z'
            
    error_model = BiasedDepolarizingErrorModel(bias,bias_str)
    # print run parameters
    print('code:',code.label )
    print('Error model:',error_model.label)
    print('number of realizations:',num_realiz)
    print('Decoder:',decoder.label)
    print('Error probabilities:',error_probability)
    print('Maximum runs:',max_runs)
    
    results = TNDresult_random(code,decoder,error_model,max_runs,perm_rates,error_probability,code_name,layout,num_realiz)
    
@pytest.mark.parametrize('index, expected', [
    ((2, 1), True),  # in-bounds x plaquette
    ((4, 1), True),  # boundary x plaquette
    ((2, -1), True),  # out-bounds x plaquette
    ((3, 1), False),  # in-bounds z plaquette
    ((2, 2), False),  # boundary z plaquette
    ((-1, 1), False),  # out-bounds z plaquette
])
def test_rotated_planar_lattice_is_x_plaquette(index, expected):
    lattice = RotatedPlanarCode(3, 5)
    assert lattice.is_x_plaquette(index) == expected


@pytest.mark.parametrize('lattice, expected', [
    # RotatedPlanarCode(row, cols), (max_site_x, max_site_y)
    (RotatedPlanarCode(3, 3), (2, 2)),
    (RotatedPlanarCode(4, 4), (3, 3)),
    (RotatedPlanarCode(3, 5), (4, 2)),
    (RotatedPlanarCode(5, 3), (2, 4)),
    (RotatedPlanarCode(4, 6), (5, 3)),
    (RotatedPlanarCode(6, 4), (3, 5)),
    (RotatedPlanarCode(3, 4), (3, 2)),
    (RotatedPlanarCode(4, 3), (2, 3)),
])
def test_rotated_planar_lattice_site_bounds(lattice, expected):
    assert lattice.site_bounds == expected


@pytest.mark.parametrize('index, expected', [
    ((0, 1), True),  # in-bounds left
    ((4, 1), True),  # in-bounds right