Exemplo n.º 1
0
def mock_ORBIT(
    params: List[Quantity],
) -> Tuple[float, List[float], List[float], List[List[str]], List[int]]:
    """A function to mock ORBIT behaviour but return fixed non-changing values for
    the goal and results

    Parameters
    ----------
    params : List[Quantity]
        List of c3 Quantity style parameters that the black-box optimizer is working on

    Returns
    -------
    Tuple[float, List[float], List[float], List[List[str]], List[int]]
        goal : Result of goal function calculation, eg, mean of all results
        results : Averaged Readout of individial ORBIT sequences
        results_std : Standard deviation for each averaged readout
        seqs : ORBIT sequence that was run, eg, ["rx90p", "ry90p"...]
        shots_num : Number of shots for averaging the readout
    """
    results = [RESULT_VAL] * RB_NUMBER
    goal: float = np.mean(results)
    results_std = [RESULTS_STD] * RB_NUMBER
    seqs = single_length_RB(RB_number=RB_NUMBER, RB_length=RB_LENGTH, target=TARGET)
    shots_nums = [SHOTS] * RB_NUMBER
    return goal, results, results_std, seqs, shots_nums
Exemplo n.º 2
0
def orbit_infid(
    U_dict,
    RB_number: int = 30,
    RB_length: int = 20,
    lindbladian=False,
    shots: int = None,
    seqs=None,
    noise=None
):
    if not seqs:
        seqs = single_length_RB(RB_number=RB_number, RB_length=RB_length)
    Us = evaluate_sequences(U_dict, seqs)
    infids = []
    for U in Us:
        dim = int(U.shape[0])
        psi_init = tf.constant(basis(dim, 0), dtype=tf.complex128)
        psi_actual = tf.matmul(U, psi_init)
        pop0 = tf_abs(psi_actual[0])**2
        p1 = 1 - pop0
        if shots:
            vals = tf.keras.backend.random_binomial(
                [shots],
                p=p1,
                dtype=tf.float64,
            )
            # if noise:
            #     vals = vals + (np.random.randn(shots) * noise)
            infid = tf.reduce_mean(vals)
        else:
            infid = p1
            # if noise:
            #     infid = infid + (np.random.randn() * noise)
        if noise:
            infid = infid + (np.random.randn() * noise)

        infids.append(infid)
    return tf_ave(infids)
Exemplo n.º 3
0
def leakage_RB(
   U_dict,
   min_length: int = 5,
   max_length: int = 500,
   num_lengths: int = 20,
   num_seqs: int = 30,
   logspace=False,
   lindbladian=False
):
    # print('Performing leakage RB fit experiment.')
    gate = list(U_dict.keys())[0]
    U = U_dict[gate]
    dim = int(U.shape[0])
    psi_init = tf.constant(basis(dim, 0), dtype=tf.complex128)
    if logspace:
        lengths = np.rint(
                    np.logspace(
                        np.log10(min_length),
                        np.log10(max_length),
                        num=num_lengths
                        )
                    ).astype(int)
    else:
        lengths = np.rint(
                    np.linspace(
                        min_length,
                        max_length,
                        num=num_lengths
                        )
                    ).astype(int)
    comp_surv = []
    surv_prob = []
    for L in lengths:
        seqs = single_length_RB(num_seqs, L)
        Us = evaluate_sequences(U_dict, seqs)
        pop0s = []
        pop_comps = []
        for U in Us:
            pops = populations(tf.matmul(U, psi_init), lindbladian)
            pop0s.append(float(pops[0]))
            pop_comps.append(float(pops[0])+float(pops[1]))
        surv_prob.append(pop0s)
        comp_surv.append(pop_comps)

    def RB_leakage(len, r_leak, A_leak, B_leak):
        return A_leak + B_leak * r_leak**(len)
    bounds = (0, 1)
    init_guess = [0.9, 0.5, 0.5]
    fitted = False
    while not fitted:
        try:
            comp_means = np.mean(comp_surv, axis=1)
            comp_stds = np.std(comp_surv, axis=1) / np.sqrt(len(comp_surv[0]))
            solution, cov = curve_fit(RB_leakage,
                                      lengths,
                                      comp_means,
                                      sigma=comp_stds,
                                      bounds=bounds,
                                      p0=init_guess)
            r_leak, A_leak, B_leak = solution
            fitted = True
        except Exception as message:
            print(message)
            if logspace:
                new_lengths = np.rint(
                            np.logspace(
                                np.log10(max_length + min_length),
                                np.log10(max_length * 2),
                                num=num_lengths
                                )
                            ).astype(int)
            else:
                new_lengths = np.rint(
                            np.linspace(
                                max_length + min_length,
                                max_length*2,
                                num=num_lengths
                                )
                            ).astype(int)
            max_length = max_length * 2
            for L in new_lengths:
                seqs = single_length_RB(num_seqs, L)
                Us = evaluate_sequences(U_dict, seqs)
                pop0s = []
                pop_comps = []
                for U in Us:
                    pops = populations(tf.matmul(U, psi_init), lindbladian)
                    pop0s.append(float(pops[0]))
                    pop_comps.append(float(pops[0]))
                surv_prob.append(pop0s)
                comp_surv.append(pop_comps)
            lengths = np.append(lengths, new_lengths)

    def RB_surv(len, r, A, C):
        return A + B_leak * r_leak**(len) + C * r**(len)
    bounds = (0, 1)
    init_guess = [0.9, 0.5, 0.5]

    fitted = False
    while not fitted:
        try:
            surv_means = np.mean(surv_prob, axis=1)
            surv_stds = np.std(surv_prob, axis=1) / np.sqrt(len(surv_prob[0]))
            solution, cov = curve_fit(RB_surv,
                                      lengths,
                                      surv_means,
                                      sigma=surv_stds,
                                      bounds=bounds,
                                      p0=init_guess)
            r, A, C = solution
            fitted = True
        except Exception as message:
            print(message)
            if logspace:
                new_lengths = np.rint(
                            np.logspace(
                                np.log10(max_length + min_length),
                                np.log10(max_length * 2),
                                num=num_lengths
                                )
                            ).astype(int)
            else:
                new_lengths = np.rint(
                            np.linspace(
                                max_length + min_length,
                                max_length*2,
                                num=num_lengths
                                )
                            ).astype(int)
            max_length = max_length * 2
            for L in new_lengths:
                seqs = single_length_RB(num_seqs, L)
                Us = evaluate_sequences(U_dict, seqs)
                pop0s = []
                pop_comps = []
                for U in Us:
                    pops = populations(tf.matmul(U, psi_init), lindbladian)
                    pop0s.append(float(pops[0]))
                    pop_comps.append(float(pops[0]))
                surv_prob.append(pop0s)
                comp_surv.append(pop_comps)
            lengths = np.append(lengths, new_lengths)

    leakage = (1-A_leak)*(1-r_leak)
    seepage = A_leak*(1-r_leak)
    fid = 0.5*(r+1-leakage)
    epc = 1 - fid
    return epc, leakage, seepage, r_leak, A_leak, B_leak, r, A, C
Exemplo n.º 4
0
def RB(
       U_dict,
       min_length: int = 5,
       max_length: int = 500,
       num_lengths: int = 20,
       num_seqs: int = 30,
       logspace=False,
       lindbladian=False,
       padding=""
       ):
    # print('Performing RB fit experiment.')
    gate = list(U_dict.keys())[0]
    U = U_dict[gate]
    dim = int(U.shape[0])
    psi_init = tf.constant(basis(dim, 0), dtype=tf.complex128)
    if logspace:
        lengths = np.rint(
                    np.logspace(
                        np.log10(min_length),
                        np.log10(max_length),
                        num=num_lengths
                        )
                    ).astype(int)
    else:
        lengths = np.rint(
                    np.linspace(
                        min_length,
                        max_length,
                        num=num_lengths
                        )
                    ).astype(int)
    surv_prob = []
    for L in lengths:
        seqs = single_length_RB(num_seqs, L, padding)
        Us = evaluate_sequences(U_dict, seqs)
        pop0s = []
        for U in Us:
            pops = populations(tf.matmul(U, psi_init), lindbladian)
            pop0s.append(float(pops[0]+pops[1]))
        surv_prob.append(pop0s)

    def RB_fit(len, r, A, B):
        return A * r**(len) + B
    bounds = (0, 1)
    init_guess = [0.9, 0.5, 0.5]
    fitted = False
    while not fitted:
        try:
            means = np.mean(surv_prob, axis=1)
            stds = np.std(surv_prob, axis=1) / np.sqrt(len(surv_prob[0]))
            solution, cov = curve_fit(RB_fit,
                                      lengths,
                                      means,
                                      sigma=stds,
                                      bounds=bounds,
                                      p0=init_guess)
            r, A, B = solution
            fitted = True
        except Exception as message:
            print(message)
            if logspace:
                new_lengths = np.rint(
                            np.logspace(
                                np.log10(max_length + min_length),
                                np.log10(max_length * 2),
                                num=num_lengths
                                )
                            ).astype(int)
            else:
                new_lengths = np.rint(
                            np.linspace(
                                max_length + min_length,
                                max_length*2,
                                num=num_lengths
                                )
                            ).astype(int)
            max_length = max_length * 2
            for L in new_lengths:
                seqs = single_length_RB(num_seqs, L, padding)
                Us = evaluate_sequences(U_dict, seqs)
                pop0s = []
                for U in Us:
                    pops = populations(tf.matmul(U, psi_init), lindbladian)
                    pop0s.append(float(pops[0]+pops[1]))
                surv_prob.append(pop0s)
            lengths = np.append(lengths, new_lengths)
    epc = 0.5 * (1 - r)
    print("epc:", epc)
    epg = 1 - ((1-epc)**(1/4))
    print("epg:", epg)
    # print('example seq: ', seqs[0])

    fig, ax = plt.subplots()
    ax.plot(lengths,
            surv_prob,
            marker='o',
            color='red',
            linestyle='None')
    ax.errorbar(lengths,
                means,
                yerr=stds,
                color='blue',
                marker='x',
                linestyle='None')
    plt.title('RB results')
    plt.ylabel('Population in 0')
    plt.xlabel('\# Cliffords')
    plt.ylim(0, 1)
    plt.xlim(0, lengths[-1])
    fitted = RB_fit(lengths, r, A, B)
    ax.plot(lengths, fitted)
    plt.text(0.1, 0.1,
             'r={:.4f}, A={:.3f}, B={:.3f}'.format(r, A, B),
             size=16,
             transform=ax.transAxes)
    plt.show()
    # return epc, r, A, B, fig, ax
    return epg
Exemplo n.º 5
0
def RB(
    U_dict,
    min_length: int = 5,
    max_length: int = 500,
    num_lengths: int = 20,
    num_seqs: int = 30,
    logspace=False,
    lindbladian=False,
    padding="",
):
    gate = list(U_dict.keys())[0]
    U = U_dict[gate]
    dim = int(U.shape[0])
    psi_init = tf.constant(basis(dim, 0), dtype=tf.complex128)
    if logspace:
        lengths = np.rint(
            np.logspace(np.log10(min_length),
                        np.log10(max_length),
                        num=num_lengths)).astype(int)
    else:
        lengths = np.rint(np.linspace(min_length, max_length,
                                      num=num_lengths)).astype(int)
    surv_prob = []
    for L in lengths:
        seqs = single_length_RB(num_seqs, L, padding)
        Us = evaluate_sequences(U_dict, seqs)
        pop0s = []
        for U in Us:
            pops = populations(tf.matmul(U, psi_init), lindbladian)
            pop0s.append(float(pops[0]))
        surv_prob.append(pop0s)

    def RB_fit(len, r, A, B):
        return A * r**(len) + B

    bounds = (0, 1)
    init_guess = [0.9, 0.5, 0.5]
    fitted = False
    while not fitted:
        try:
            means = np.mean(surv_prob, axis=1)
            stds = np.std(surv_prob, axis=1) / np.sqrt(len(surv_prob[0]))
            solution, cov = curve_fit(RB_fit,
                                      lengths,
                                      means,
                                      sigma=stds,
                                      bounds=bounds,
                                      p0=init_guess)
            r, A, B = solution
            fitted = True
        except Exception as message:
            print(message)
            if logspace:
                new_lengths = np.rint(
                    np.logspace(
                        np.log10(max_length + min_length),
                        np.log10(max_length * 2),
                        num=num_lengths,
                    )).astype(int)
            else:
                new_lengths = np.rint(
                    np.linspace(max_length + min_length,
                                max_length * 2,
                                num=num_lengths)).astype(int)
            max_length = max_length * 2
            for L in new_lengths:
                seqs = single_length_RB(num_seqs, L, padding)
                Us = evaluate_sequences(U_dict, seqs)
                pop0s = []
                for U in Us:
                    pops = populations(tf.matmul(U, psi_init), lindbladian)
                    pop0s.append(float(pops[0]))
                surv_prob.append(pop0s)
            lengths = np.append(lengths, new_lengths)
    epc = 0.5 * (1 - r)
    epg = 1 - ((1 - epc)**(1 / 4))  # TODO: adjust to be mean length of
    return epg
Exemplo n.º 6
0
def create_c1_opt_hk(optimizer_config, lindblad, RB_number, RB_length, shots,
                     noise):
    with open(optimizer_config, "r") as cfg_file:
        try:
            cfg = json.loads(cfg_file.read())
        except json.decoder.JSONDecodeError:
            raise Exception(f"Config {optimizer_config} is invalid.")

    if lindblad:

        def unit_X90p(U_dict):
            return fidelities.lindbladian_unitary_infid(U_dict,
                                                        'X90p',
                                                        proj=True)

        def avfid_X90p(U_dict):
            return fidelities.lindbladian_average_infid(U_dict,
                                                        'X90p',
                                                        proj=True)

        def epc_ana(U_dict):
            return fidelities.lindbladian_epc_analytical(U_dict, proj=True)
    else:

        def unit_X90p(U_dict):
            return fidelities.unitary_infid(U_dict, 'X90p', proj=True)

        # def unit_Y90p(U_dict):
        #     return fidelities.unitary_infid(U_dict, 'Y90p', proj=True)
        # def unit_X90m(U_dict):
        #     return fidelities.unitary_infid(U_dict, 'X90m', proj=True)
        # def unit_Y90m(U_dict):
        #     return fidelities.unitary_infid(U_dict, 'Y90m', proj=True)
        def avfid_X90p(U_dict):
            return fidelities.average_infid(U_dict, 'X90p', proj=True)

        def epc_ana(U_dict):
            return fidelities.epc_analytical(U_dict, proj=True)

    seqs = qt_utils.single_length_RB(RB_number=RB_number, RB_length=RB_length)

    def orbit_no_noise(U_dict):
        return fidelities.orbit_infid(U_dict, lindbladian=lindblad, seqs=seqs)

    def orbit_seq_noise(U_dict):
        return fidelities.orbit_infid(U_dict,
                                      lindbladian=lindblad,
                                      RB_number=RB_number,
                                      RB_length=RB_length)

    def orbit_shot_noise(U_dict):
        return fidelities.orbit_infid(U_dict,
                                      lindbladian=lindblad,
                                      seqs=seqs,
                                      shots=shots,
                                      noise=noise)

    def orbit_seq_shot_noise(U_dict):
        return fidelities.orbit_infid(U_dict,
                                      lindbladian=lindblad,
                                      shots=shots,
                                      noise=noise,
                                      RB_number=RB_number,
                                      RB_length=RB_length)

    def epc_RB(U_dict):
        return fidelities.RB(U_dict, logspace=True, lindbladian=lindblad)[0]

    def epc_leakage_RB(U_dict):
        return fidelities.leakage_RB(U_dict,
                                     logspace=True,
                                     lindbladian=lindblad)[0]

    seqs100 = qt_utils.single_length_RB(RB_number=100, RB_length=RB_length)

    def maw_orbit(U_dict):
        sampled_seqs = random.sample(seqs100, k=RB_number)
        return fidelities.orbit_infid(U_dict,
                                      lindbladian=lindblad,
                                      seqs=sampled_seqs,
                                      shots=shots,
                                      noise=noise)

    fids = {
        'unitary_infid': unit_X90p,
        # 'unitary_infid_Y90p': unit_Y90p,
        # 'unitary_infid_X90m': unit_X90m,
        # 'unitary_infid_Y90m': unit_Y90m,
        'average_infid': avfid_X90p,
        'orbit_no_noise': orbit_no_noise,
        'orbit_seq_noise': orbit_seq_noise,
        'orbit_shot_noise': orbit_shot_noise,
        'orbit_seq_shot_noise': orbit_seq_shot_noise,
        'maw_orbit': maw_orbit,
        'epc_RB': epc_RB,
        'epc_leakage_RB': epc_leakage_RB,
        'epc_ana': epc_ana
    }
    fid = cfg['fid_func']
    cb_fids = cfg['callback_fids']
    fid_func = fids[fid]
    callback_fids = []
    for cb_fid in cb_fids:
        callback_fids.append(fids[cb_fid])
    gateset_opt_map = [[tuple(par) for par in set]
                       for set in cfg['gateset_opt_map']]
    algorithm = algorithms[cfg['algorithm']]
    options = {}
    if 'options' in cfg:
        options = cfg['options']
    opt = C1(dir_path=cfg['dir_path'],
             fid_func=fid_func,
             gateset_opt_map=gateset_opt_map,
             callback_fids=callback_fids,
             algorithm=algorithm,
             options=options)
    return opt