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'
def test_biased_depolarising_error_model_probability_distribution_bias_half(): for axis in 'XYZ': bias = 0.5 error_model = BiasedDepolarizingErrorModel(bias, axis) depolarizing_error_model = DepolarizingErrorModel() p = 0.1 assert error_model.probability_distribution(p) == depolarizing_error_model.probability_distribution(p), ( 'Biased-depolarizing probability (bias=0.5) does not match standard depolarizing probability distribution.')
def decode( self, code, perm_mat, syndrome, error_model=DepolarizingErrorModel(), # noqa: B008 error_probability=0.1, **kwargs): """ See :meth:`qecsim.model.Decoder.decode` Note: The optional keyword parameters ``error_model`` and ``error_probability`` are used to determine the prior probability distribution for use in the decoding algorithm. Any provided error model must implement :meth:`~qecsim.model.ErrorModel.probability_distribution`. :param code: Rotated planar code. :type code: RotatedPlanarCode :param syndrome: Syndrome as binary vector. :type syndrome: numpy.array (1d) :param error_model: Error model. (default=DepolarizingErrorModel()) :type error_model: ErrorModel :param error_probability: Overall probability of an error on a single qubit. (default=0.1) :type error_probability: float :return: Recovery operation as binary symplectic vector. :rtype: numpy.array (1d) """ # any recovery any_recovery = self.sample_recovery(code, syndrome) # probability distribution prob_dist = error_model.probability_distribution(error_probability) # coset probabilities,recovery operations coset_ps, recoveries = self._coset_probabilities( prob_dist, perm_mat, any_recovery) # most likely recovery operation max_coset_p, max_recovery = max( zip(coset_ps, recoveries), key=lambda coset_p_recovery: coset_p_recovery[0]) # logging if not (mp.isfinite(max_coset_p) and max_coset_p > 0): log_data = { # instance 'decoder': repr(self), # method parameters 'code': repr(code), 'syndrome': pt.pack(syndrome), 'error_model': repr(error_model), 'error_probability': error_probability, # variables 'prob_dist': prob_dist, 'coset_ps': [repr(p) for p in coset_ps ], # convert to string because mp.mpf # context 'error': pt.pack(kwargs['error']) if 'error' in kwargs else None, } logger.warning( 'NON-POSITIVE-FINITE MAX COSET PROBABILITY: {}'.format( json.dumps(log_data, sort_keys=True))) # return most likely recovery operation as bsf return max_recovery.to_bsf(), coset_ps, max_coset_p
def test_color666_mps_decoder_decode_value(): # expected coset_ps expected_coset_ps = ( mp.mpf('1.4290529991554288e-9'), # I mp.mpf('2.1657729564075353e-13'), # X mp.mpf('2.2541268663248664e-13'), # Y mp.mpf('9.3780172173812118e-12'), # Z ) code = Color666Code(7) decoder = Color666MPSDecoder(chi=16) # error error = code.new_pauli() error.site('X', (2, 1)) # error.site('Y', (3, 1), (4, 2), (7, 3), (9, 6)) error.site('Y', (7, 3)) error.site('Z', (6, 0), (3, 3), (7, 6)) # syndrome syndrome = pt.bsp(error.to_bsf(), code.stabilizers.T) # sample sample = decoder.sample_recovery(code, syndrome) print(sample) # probabilities prob_dist = DepolarizingErrorModel().probability_distribution(0.1) # coset probabilities coset_ps, _ = decoder._coset_probabilities(prob_dist, sample) print('# expected Pr(G)=', expected_coset_ps) print('# actual Pr(G)=', coset_ps) assert all(_is_close(expected_coset_ps, coset_ps, rtol=1e-11, atol=0)), ( 'Coset probabilites do not satisfy expected Pr(G) ~= Pr(G)')
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'
def test_run_once_seeded(): code = PlanarCode(5, 5) error_model = DepolarizingErrorModel() decoder = PlanarMWPMDecoder() error_probability = 0.15 data1 = app.run_once(code, error_model, decoder, error_probability, rng=np.random.default_rng(5)) data2 = app.run_once(code, error_model, decoder, error_probability, rng=np.random.default_rng(5)) assert data1['error_weight'] == data2['error_weight'] assert data1['success'] == data2['success'] assert np.array_equal(data1['logical_commutations'], data2['logical_commutations']) assert np.array_equal(data1['custom_values'], data2['custom_values'])
def test_planar_rmps_decoder_cosets_probability_equivalence( sample_pauli_f, sample_pauli_g): decoder = PlanarRMPSDecoder(chi=8) # probabilities prob_dist = DepolarizingErrorModel().probability_distribution(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-9, atol=0)), ('Coset probabilites do not satisfy Pr(fG) ~= Pr(gG)')
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. '
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)')
def test_planar_rmps_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, _ = PlanarRMPSDecoder(mode='a')._coset_probabilities( prob_dist, sample) print('#exact_coset_ps=', exact_coset_ps) # coset probabilities approx (chi=6) approx_coset_ps, _ = PlanarRMPSDecoder(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, _ = PlanarRMPSDecoder(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, _ = PlanarRMPSDecoder(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, _ = PlanarRMPSDecoder(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')
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, mp.mpf), 'Contracted tensor network is not an mp.mpf' assert 0 <= result <= 1, 'Contracted tensor network not within bounds' # partial contraction # note: for optimization we contract tn from left to left_stop as bra common to all cosets left_stop = ((tn.shape[1] - 1) // 2) - 1 bra, bra_mult = tt.mps2d.contract(tn, stop=left_stop) # empty bra if None bra = np.full(tn.shape[0], None, dtype=object) if bra is None else bra print('len(bra)=', len(bra)) assert isinstance( bra, np.ndarray), 'Partially contracted tensor network is not an np.array' assert isinstance( bra_mult, mp.mpf ), 'Partially contracted tensor network multiplier is not an mp.mpf' # note: for optimization we contract tn from right to right_stop as ket common to all cosets right_stop = left_stop + 2 ket, ket_mult = tt.mps2d.contract(tn, start=-1, stop=right_stop, step=-1) # empty ket if None ket = np.full(tn.shape[0], None, dtype=object) if ket is None else ket print('len(ket)=', len(ket)) assert isinstance( ket, np.ndarray), 'Partially contracted tensor network is not an np.array' assert isinstance( ket_mult, mp.mpf ), 'Partially contracted tensor network multiplier is not an mp.mpf' # stack bra, remaining tn and ket middle = tn[:, left_stop:right_stop + 1] print('middle.shape=', middle.shape) partial_tn = np.column_stack((bra, middle, ket)) result_from_partial = tt.mps2d.contract(partial_tn) assert isinstance( result_from_partial, mp.mpf), 'Contracted tensor network (from partial) is not an mp.mpf' assert 0 <= result_from_partial <= 1, 'Contracted tensor network (from partial) not within bounds' assert result == result_from_partial, 'Results contracted (one go) and (from partial) differ' print(result, result_from_partial)
def test_color666_mps_decoder_cosets_probability_inequality(chi, tol, rtol): code = Color666Code(5) decoder = Color666MPSDecoder(chi=chi, tol=tol) # 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(YG) ~= Pr(ZG) print() print('Pr(IG):{!r} > Pr(XG):{!r} ~= Pr(YG):{!r} ~= Pr(ZG):{!r}. rtol={}. rtol={}'.format( coset_i_p, coset_x_p, coset_y_p, coset_z_p, abs(coset_x_p - coset_y_p) / abs(coset_y_p), abs(coset_y_p - coset_z_p) / abs(coset_z_p))) print('types: Pr(IG):{}, Pr(XG):{}, Pr(YG):{}, Pr(ZG):{}'.format( type(coset_i_p), type(coset_x_p), type(coset_y_p), type(coset_z_p))) assert coset_i_p > coset_x_p, 'Coset probabilites do not satisfy Pr(IG) > Pr(XG)' assert coset_i_p > coset_y_p, 'Coset probabilites do not satisfy Pr(IG) > Pr(YG)' assert coset_i_p > coset_z_p, 'Coset probabilites do not satisfy Pr(IG) > Pr(ZG)' assert _is_close(coset_x_p, coset_y_p, rtol=rtol, atol=0), 'Coset probabilites do not satisfy Pr(XG) ~= Pr(YG)' assert _is_close(coset_y_p, coset_z_p, rtol=rtol, atol=0), 'Coset probabilites do not satisfy Pr(YG) ~= Pr(ZG)'
def test_planar_rmps_decoder_cosets_probability_inequality(mode, rtol): code = PlanarCode(25, 25) decoder = PlanarRMPSDecoder(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_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'
def test_color666_mps2d_contract(): code = Color666Code(5) sample = code.new_pauli().site('X', (3, 1)).site('Y', (2, 2)).site('Z', (6, 4)) print() print(code.ascii_art(pauli=sample)) prob_dist = DepolarizingErrorModel().probability_distribution(0.1) tnc = Color666MPSDecoder.TNC() tn = tnc.create_tn(prob_dist, sample) result_forwards = tt.mps2d.contract(tn) 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' )
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'
def decode(self, code, hadamard_vec,hadamard_mat, syndrome, error_model=DepolarizingErrorModel(), # noqa: B008 error_probability=0.1, **kwargs): """
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')
np.isclose(csem_lim_minus1.ratio, csem_neg_lim_plus1.ratio, rtol, atol)) # check probability distribution assert np.all( np.isclose(csem_lim_zero.probability_distribution(p), csem_neg_lim_zero.probability_distribution(p))) assert np.all( np.isclose(csem_lim_plus1.probability_distribution(p), csem_neg_lim_minus1.probability_distribution(p))) assert np.all( np.isclose(csem_lim_minus1.probability_distribution(p), csem_neg_lim_plus1.probability_distribution(p))) @pytest.mark.parametrize('csem, sem', [ (CenterSliceErrorModel((1, 0, 0), 0), DepolarizingErrorModel()), (CenterSliceErrorModel((0, 1, 0), 0), DepolarizingErrorModel()), (CenterSliceErrorModel((0, 0, 1), 0), DepolarizingErrorModel()), (CenterSliceErrorModel((1, 0, 0), 1), BitFlipErrorModel()), (CenterSliceErrorModel((0, 1, 0), 1), BitPhaseFlipErrorModel()), (CenterSliceErrorModel((0, 0, 1), 1), PhaseFlipErrorModel()), ]) def test_center_slice_standard_error_models(csem, sem): p = 0.1 assert csem.probability_distribution(p) == sem.probability_distribution(p) def test_center_slice_error_model_generate(): code = FiveQubitCode() lim = (0, 0, 1) pos = 0.5
class _FixedDecoder(Decoder): def __init__(self, decoding): 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)),
def test_run_invalid_parameters(error_probability): with pytest.raises(ValueError) as exc_info: app.run(FiveQubitCode(), DepolarizingErrorModel(), NaiveDecoder(), error_probability, max_runs=2) print(exc_info)
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')
def test_color666_mps_functions(): prob_dist = DepolarizingErrorModel().probability_distribution(0.1) tnc = Color666MPSDecoder.TNC() bra = [ tnc.create_q_node(prob_dist, ('I', 'I'), 'nw'), tnc.create_s_node('w'), tnc.create_q_node(prob_dist, ('I', None), 'sw'), ] mpo1 = [ tnc.create_s_node('n'), tnc.create_q_node(prob_dist, ('I', 'I'), 's'), None, ] mpo2 = [ tnc.create_q_node(prob_dist, (None, 'I'), 'ne'), tnc.create_s_node('s'), None, ] ket = [ None, tnc.create_q_node(prob_dist, ('I', None), 'e'), None, ] expected = 0.47831585185185249 # exact contraction for expected result = tt.mps.contract_pairwise(bra, mpo1) result = tt.mps.contract_pairwise(result, mpo2) 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, mpo1) result = tt.mps.contract_pairwise(result, mpo2) 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, mpo1) result = tt.mps.left_canonical_form(result) result = tt.mps.contract_pairwise(result, mpo2) 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, mpo1) result = tt.mps.right_canonical_form(result) result = tt.mps.contract_pairwise(result, mpo2) 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, mpo1) result, norm1 = tt.mps.truncate(result) result = tt.mps.contract_pairwise(result, mpo2) result, norm2 = tt.mps.truncate(result) 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 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, mpo1) result, norm2 = tt.mps.left_canonical_form(result, normalise=True) result = tt.mps.contract_pairwise(result, mpo2) result, norm3 = tt.mps.left_canonical_form(result, normalise=True) result = tt.mps.inner_product(result, ket) result *= norm1 * norm2 * norm3 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, mpo1) result, norm2 = tt.mps.right_canonical_form(result, normalise=True) result = tt.mps.contract_pairwise(result, mpo2) result, norm3 = tt.mps.right_canonical_form(result, normalise=True) result = tt.mps.inner_product(result, ket) result *= norm1 * norm2 * norm3 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, mpo1) result, norm1 = tt.mps.truncate(result, chi=4) result = tt.mps.contract_pairwise(result, mpo2) result, norm2 = tt.mps.truncate(result, chi=4) 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), 'Approx. contraction with truncate (chi) not as expected' # approximate contraction with truncate (tol) result = tt.mps.contract_pairwise(bra, mpo1) result, norm1 = tt.mps.truncate(result, tol=1e-8) result = tt.mps.contract_pairwise(result, mpo2) result, norm2 = tt.mps.truncate(result, tol=1e-8) 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), 'Approx. contraction with truncate (tol) not as expected' # reversed exact contraction for expected result = tt.mps.contract_pairwise(mpo2, ket) result = tt.mps.contract_pairwise(mpo1, result) result = tt.mps.inner_product(bra, result) print('#result=', result, '#rtol=', abs(result - expected) / abs(expected)) assert _is_close(expected, result, rtol=1e-14, atol=0), 'Reversed exact contraction not as expected' # reversed approximate contraction with truncate (chi) result = tt.mps.contract_pairwise(mpo2, ket) result, norm1 = tt.mps.truncate(result, chi=4) result = tt.mps.contract_pairwise(mpo1, result) result, norm2 = tt.mps.truncate(result, chi=4) result = tt.mps.inner_product(bra, result) result *= norm1 * norm2 print('#result=', result, '#rtol=', abs(result - expected) / abs(expected)) assert _is_close(expected, result, rtol=1e-14, atol=0), ( 'Reversed approx. contraction with truncate (chi) not as expected')