def load_data(train, N, average, runs, Tcrit=0.0, h=0.0):
    X_train = []
    Y_train = []
    magn_list = []
    for t in temp:
        if train:
            filename = ('data_no_field/uniform_field_spin_hmax_' + str(h) +
                        'T_' + str(t) + 'N_' + str(N) +
                        '_number_of_config_per_temp_' + str(average) +
                        'runs_' + str(runs) + '_0')
        else:
            filename = ('data_field_h1_5/uniform_field_spin_hmax_' + str(h) +
                        'T_' + str(t) + 'N_' + str(N) +
                        '_number_of_config_per_temp_' + str(average) +
                        'runs_' + str(runs) + '_0')
        a = qt.qload(filename)
        magn = 0
        for i in a:
            magn += abs(np.sum(i))
            i = (i + 1) / 2  # renormalize
            X_train.append(i.reshape(1, 20, 20))
            if t < Tcrit:
                Y_train.append([1, 0])
            else:
                Y_train.append([0, 1])
        magn_list.append(magn / (N**2 * average))
    X_train = np.array(X_train)
    return X_train, Y_train
def test_evolution_operator(n_qubits, n_levels):
    #generate random parameters
    params = 0.01*np.random.rand(2, n_levels)
    gammas = params[0]
    betas = params[1]
    #generate random graph
    edges = []
    while len(edges) < 1:
        prob = 0.5
        graph = erdos_renyi_graph(n_qubits, prob)
        edges = list(graph.edges)
    #generate random n-qubits state
    list_gen_state = qucs.n_rand_qubits(n_qubits)
    gen_state = qu.tensor(list_gen_state)
    #Test if it works as expected
    obs = qaoa.evolution_operator(n_qubits, edges, gammas, betas)*gen_state
    exp = gen_state
    for i in range(len(gammas)):
        u_mix_hamilt_i = (-complex(0,betas[i])*qaoa.mix_hamilt(n_qubits)).expm()
        u_prob_hamilt_i = (-complex(0,gammas[i])*qaoa.prob_hamilt(n_qubits, edges)).expm()
        exp = u_mix_hamilt_i*u_prob_hamilt_i*exp
    assert (np.round(np.array(exp.full()), 8) == (np.round(np.array(obs.full()), 8))).all()
    #test if it evolves a state for known parameters
    exp = qu.qload('final_state_simple_graph_p=1')
    obs = qaoa.evolution_operator(3, [(0,1),(1,2)], [1.0], [0.4])*qaoa.initial_state(3)
Exemplo n.º 3
0
    def steadystate_parfor(self,
                           Deltas,
                           num_cpus=None,
                           recalc=True,
                           savefile=None):

        savefile_exists = os.path.isfile(str(savefile) + '.qu')

        # If 1) we ask for it to be recalculated or 2) it *must* be calculated
        # because no savefile exists: do the steady state calc. Else load file.
        if (recalc or not savefile_exists):

            # Reset rho_Delta in case of multiple calcs
            self.rho_Delta = [None] * len(self.Delta_range)
            Deltas_i = list(Deltas)  # Make copy, don't modify in place

            Delta_steps = len(self.Delta_range) - 1

            self.rho_Delta = qu.parfor(steadystate_parfor_func,
                                       self.Delta_range,
                                       Delta_idx=self.Delta_idx,
                                       Deltas=Deltas_i,
                                       ob_obj=self.ob_obj,
                                       num_cpus=num_cpus)

            # Only save the file if we have a place to save it
            if (savefile != None):
                qu.qsave(self.rho_Delta, savefile)

        # Otherwise load the steady state rho_v_delta from file
        else:
            self.rho_Delta = qu.qload(savefile)

        return self.rho_Delta
Exemplo n.º 4
0
    def mesolve(self,
                tlist,
                rho0=None,
                td=False,
                e_ops=[],
                args={},
                opts=qu.Options(),
                recalc=True,
                savefile=None,
                show_pbar=False):

        if not rho0:
            rho0 = self.ground_state()

        savefile_exists = os.path.isfile(str(savefile) + '.qu')

        # Solve if 1) we ask for it to be recalculated or 2) it *must* be
        # calculated because no savefile exists.
        if recalc or not savefile_exists:

            # Is the Hamiltonian time-dependent?
            if td:  # If so H is a list of [H_i, t_func_i] pairs.
                H = [self.H_0, self.H_Delta]
                H.extend(self.H_I_list())
            else:  # If not it's a single QObj
                H = self.H_0 + self.H_Delta + self.H_I_sum()

            if show_pbar:
                pbar = qu.ui.progressbar.TextProgressBar()
            else:
                pbar = qu.ui.progressbar.BaseProgressBar()

            self.result = qu.mesolve(H,
                                     rho0,
                                     tlist,
                                     self.c_ops,
                                     e_ops,
                                     args=args,
                                     options=opts,
                                     progress_bar=pbar)

            self.rho = self.result.states[-1]  #  Set rho to the final state.

            # Only save the file if we have a place to save it.
            if savefile:

                print('Saving OBBase to {0}.qu'.format(savefile))

                qu.qsave(self.result, savefile)

        # Otherwise load the steady state rho_v_delta from file
        else:

            print('Loading from {0}.qu'.format(savefile))

            self.result = qu.qload(savefile)
            self.rho = self.result.states[-1]

        return self.result
Exemplo n.º 5
0
 def load_results(self):
     """ Loads the solution from a QuTiP pickle file. 
     
     Notes:
         - The path from which the results will be loaded is taken from
             self.savefile.
     """
     self.Omegas_zt, self.states_zt = qu.qload(self.savefile)
Exemplo n.º 6
0
    def essolve(self, tlist, rho0=None, recalc=True, savefile=None):
        """ 
        Evolution of the density matrix by
        expressing the ODE as an exponential series.

        Args:
            tlist: The list of times for which to find the density matrix.
            rho0: Define an initial density matrix. Default is ground state.
            recalc: Rerun the calculation if a saved file exists?
            savefile: (string) Save the data to savefile.qu

        Returns:
            result: qutip result object containing the solved data.

        Notes:
            QuTiP essolve method doesn't return the states properly so I use
            the underlying ode2es method.

            Unlike the mesolve method, the tlist here doesn't have any need 
            for high resolution to solve. So better when the density matrix 
            is only needed at a few points.

        """

        if not rho0:
            rho0 = self.ground_state() * self.ground_state().dag()

        savefile_exists = os.path.isfile(str(savefile) + '.qu')

        # Solve if 1) we ask for it to be recalculated or 2) it *must* be
        # calculated because no savefile exists.
        if (recalc or not savefile_exists):

            H = self.H_0 + self.H_Delta + self.H_I_sum()
            L = qu.liouvillian(H, self.c_ops)

            es = qu.ode2es(L, rho0)
            states = es.value(tlist)

            self.result = qu.solver.Result()
            self.result.states = states
            self.result.solver = "essolve"
            self.result.times = tlist

            self.rho = self.result.states[-1]  # Set rho to the final state.

            # Only save the file if we have a place to save it.
            if (savefile != None):
                qu.qsave(self.result, savefile)

        # Otherwise load the steady state rho_v_delta from file
        else:
            self.result = qu.qload(savefile)
            self.rho = self.result.states[-1]

        return self.result
Exemplo n.º 7
0
def test_qsave_qload():
    ops_in = [
        qutip.sigmax(),
        qutip.num(_dimension),
        qutip.coherent_dm(_dimension, 1j)
    ]
    filename = _random_file_name()
    qutip.qsave(ops_in, filename)
    ops_out = qutip.qload(filename)
    assert ops_in == ops_out
Exemplo n.º 8
0
def test_qsave_qload(use_path, suffix):
    ops_in = [
        qutip.sigmax(),
        qutip.num(_dimension),
        qutip.coherent_dm(_dimension, 1j)
    ]
    filename = _random_file_name() + suffix
    if use_path:
        filename = Path.cwd() / filename
    qutip.qsave(ops_in, filename)
    ops_out = qutip.qload(filename)
    assert ops_in == ops_out
Exemplo n.º 9
0
def test_qsave_qload():
    # qsave _always_ appends a suffix to the file name at the time of writing,
    # but in case this changes in the future, to ensure that we never leak a
    # temporary file into the user's folders, we simply apply this test in a
    # temporary directory rather than manually creating a temporary file and
    # modifying the name.
    ops_in = [
        qutip.sigmax(),
        qutip.num(_dimension),
        qutip.coherent_dm(_dimension, 1j)
    ]
    filename = "qsave_qload_test"
    qutip.qsave(ops_in, filename)
    ops_out = qutip.qload(filename)
    assert ops_in == ops_out
Exemplo n.º 10
0
    def essolve(self, Deltas, tlist, rho0=None, recalc=True, savefile=None):

        savefile_exists = os.path.isfile(str(savefile) + '.qu')

        # If 1) we ask for it to be recalculated or 2) it *must* be calculated
        # because no savefile exists: do the steady state calc. Else load file.
        if (recalc or not savefile_exists):

            # Reset rho_Delta in case of multiple calcs
            self.rho_Delta = [None] * len(self.Delta_range)
            self.result_Delta = [None] * len(self.Delta_range)

            Deltas_i = list(Deltas)  # Make copy, don't modify in place

            Delta_steps = len(self.Delta_range) - 1

            for i, Delta_i in enumerate(self.Delta_range):

                print("\rDelta: " + str(Delta_i) + ", " + str(i) + "/" +
                      str(Delta_steps))

                # Set the omega of the chosen beam to the current delta step.
                Deltas_i[self.Delta_idx] = Delta_i
                self.ob_obj.set_H_Delta(Deltas_i)

                try:
                    result = self.ob_obj.essolve(tlist, rho0=rho0)

                except ValueError:
                    print("Failed to solve.")

                self.result_Delta[i] = result
                self.rho_Delta[i] = result.states[-1]

            # Only save the file if we have a place to save it
            if (savefile != None):
                qu.qsave((self.rho_Delta, self.result_Delta), savefile)

        # Otherwise load the steady state rho_v_delta from file
        else:
            (self.rho_Delta, self.result_Delta) = qu.qload(savefile)

        return self.rho_Delta, self.result_Delta
Exemplo n.º 11
0
def excitation(args):
    H0 = args['parity']*args['vFermi']*(args['kpoint'][0]*qp.sigmax() + args['kpoint'][1]*qp.sigmay())
    H1 = qp.sigmax()
    H2 = qp.sigmay()
    Hamiltonian = [H0,[H1,HCoeff]]
    states = H0.eigenstates()  
    psi0 = states[1][0]
    psi1 = states[1][1]
    import hashlib
    label = hashlib.sha224(str(args)).hexdigest()
    import os
    if os.path.exists('Data/'+label+'.qu'):
      result = qp.qload('Data/'+label)
      print 'Loading'
    else:
      result = qp.mesolve(Hamiltonian, psi0, args['times'], [], [], args=args)
      print 'Recalculate'
      qp.qsave(result, 'Data/'+   label)
    proj0 =  np.array([(state.dag()*psi0).norm() for state in result.states])
    proj1 =  np.array([(state.dag()*psi1).norm() for state in result.states])
    return result, proj0, proj1
Exemplo n.º 12
0
pm = 0.003
pg = 0.003
a0 = 5.0
a1 = 1 / 30.
eta = 1 / 100.
theta = .63

ghz_size = 4
protocol = "thres_eta"
ghz_ref = qt.ghz_state(4) * qt.ghz_state(4).dag()

ghz_file = names.ghz(ps, pm, pg, eta, a0, a1, theta, ghz_size, protocol)
times_file = names.ghz_times(ps, pm, pg, eta, a0, a1, theta, ghz_size,
                             protocol)

ghzs = qt.qload(ghz_file)
times = np.load(times_file)
print("N: ", len(times))

fidelities = []
for i in ghzs:
    fidelities += [qt.fidelity(i, ghz_ref)]
fidelities = np.array(fidelities)

indices_sorted = np.argsort(times)
times = times[indices_sorted][:-1]
fidelities = fidelities[indices_sorted][:-1]

ignore_number = int(len(times) / 100 * 5.)
t_max = times[:-ignore_number][-1]
Exemplo n.º 13
0
    def load_results(self):

        self.Omegas_zt, self.states_zt = qu.qload(self.savefile)
Exemplo n.º 14
0
"""

import qutip
import sys

if len(sys.argv) ==5:
    inputfilenameA = str(sys.argv[1])
    indexA = int(sys.argv[2])
    inputfilenameB = str(sys.argv[3])
    indexB = int(sys.argv[4])
    if inputfilenameA[-3:]==".qu":
        inputfilenameA = inputfilenameA[:-3]
    if inputfilenameB[-3:]==".qu":
        inputfilenameB = inputfilenameB[:-3]
    
    listA=qutip.qload(inputfilenameA)
    A=listA[indexA]
    listB=qutip.qload(inputfilenameB)
    B=listB[indexB]
elif len(sys.argv) ==4:
    inputfilename = str(sys.argv[1])
    indexA = int(sys.argv[2])
    indexB = int(sys.argv[3])
    if inputfilename[-3:]==".qu":
        inputfilename = inputfilename[:-3]
    
    mylist=qutip.qload(inputfilename)
    A=mylist[indexA]
    B=mylist[indexB]

print("Loaded two objects")
Exemplo n.º 15
0
def get_state(system_size, time_index):
    return qt.qload(get_state_path(system_size, time_index))
Exemplo n.º 16
0
    #Set the time of simulation
    T = np.pi / delta
    Tgate_tab.append(T)
    T1 = 0
    T2 = T1 + T
    T_final = T2 + T / 4
    if ratio < 10:
        n_t = 301  #number of points from T1 to T2
    elif ratio <= 20:
        n_t = 401
    elif ratio <= 40:
        n_t = 501
    elif ratio <= 50:
        nt = 601
    res_CNOT = qt.qload(
        path + 'Simus_CNOT_without_lossdensity_without_loss_k2_over_%d' %
        (ratio))
    tlist = np.linspace(0, T_final, n_t)
    tlist = np.array(tlist)

    #States
    Na = trunc
    Nb = trunc
    alpha = size_cat  #alpha of initial state
    beta = size_cat
    C_alpha_plus = qt.coherent(Na, alpha) + qt.coherent(Na, -alpha)
    C_alpha_plus = C_alpha_plus / C_alpha_plus.norm()
    C_beta_plus = qt.coherent(Nb, beta) + qt.coherent(Nb, -beta)
    C_beta_plus = C_beta_plus / C_beta_plus.norm()
    final_state_C = C_alpha_plus
    final_state_T = C_beta_plus
# for pg in [0.0031, 0.0032, 0.0033, 0.0034, 0.0035, 0.0036, 0.0037, 0.0038, 0.0039, 0.0040, 0.0041]:
# for pg in [0.0032, 0.0033, 0.0034, 0.0035, 0.0036, 0.0037, 0.0038, 0.0039, 0.0040, 0.0041, 0.0042, 0.0043, 0.0044, 0.0045]:
for tau in range(10):
    f, g, h = fgh.fgh(mode)
    a0 = f(tau)
    eta = g(tau)
    pg = h(tau)

    ps = pg
    pm = pg
    # Load GHZ state files
    ghz_file = names.ghz(ps, pm, pg, eta, a0, a12, theta, ghz_size, protocol)
    times_file = names.ghz_times(ps, pm, pg, eta, a0, a12, theta, ghz_size,
                                 protocol)

    ghzs = qt.qload(ghz_file)
    times = np.load(times_file)
    if extra:
        ghz_file2 = names.ghz(ps, pm, pg, eta, a0, a1, theta, ghz_size,
                              protocol + "2")
        times_file2 = names.ghz_times(ps, pm, pg, eta, a0, a1, theta, ghz_size,
                                      protocol + "2")

        ghzs = np.append(ghzs, qt.qload(ghz_file2))
        times = np.append(times, np.load(times_file2))

    ###################################################################
    # CHOSE PERCENTILE
    N = len(times)
    ignore_number = int(N * ignore_percent / 100)
Exemplo n.º 18
0
def get_state(state_name, L):
    return qt.qload(get_state_path(state_name, L))
Exemplo n.º 19
0
if 0: # squeezed
    N = 70
    db_val = 8
    z = db_val / (20 * np.log10(np.e))
    target_state = qt.tensor(qt.basis(2,0), qt.squeeze(N,z)*qt.basis(N,0))

if 0: # binomial
    N = 60
    pz = (qt.basis(N,0) + qt.basis(N,4))/np.sqrt(2.0)
    mz = qt.basis(N,2)
    py = (pz + 1j*mz)/np.sqrt(2.0)
    target_state = qt.tensor(qt.basis(2,0), py)

if 0: # GKP
    target_state_cav = qt.qload('E:\data\gkp_sims\PPO\ECD\GKP_state_delta_0p25')
    target_state = qt.tensor(qt.basis(2,0), target_state_cav)
    N = target_state_cav.dims[0][0] # 200


# reward_kwargs = {'reward_mode' : 'tomography',
#                   'tomography' : 'characteristic_fn',
#                   'target_state' : target_state,
#                   'window_size' : 16}

reward_kwargs = {'reward_mode' : 'tomography',
                  'tomography' : 'wigner',
                  'target_state' : target_state,
                  'sampling_type' : 'abs',
                  'N_alpha' : 100,
                  'N_msmt' : 10,
    path +
    'wigner_TARGET_size%.0f_trunc%.0f_k1_%.0f_coefspeed_%.1f_control_on%r.png'
    % (size_cat, trunc, k1, prop, control_on))

ind_T2 = int(n_t * T2 / T_final)

#partial trace

#res_tab=np.load(path+'tab_size2_k2isdeltaover10.npy')
#ptrace_T=[]
#p_trace_C=[]
#for (ii, res) in enumerate res_tab:
#    p_trace_T.append()

path = 'C:/Users/berdou/Documents/Thèse/Posters/Images-poster/Images_CNOT/'
res_CNOT = qt.qload(path + 'density_plus_k2over10')
# Draw indiv Wigner
fig, ax = plt.subplots()
ii = int(n_t * T2 * 1.1 * 1 / T_final)
space_size = [-4, 4, 1001]
space_size = np.linspace(space_size[0], space_size[1], space_size[2])
wig = qt.wigner(res_CNOT.states[ii].ptrace(1), space_size, space_size, g=2)
ax.pcolor(space_size,
          space_size,
          wig,
          cmap='bwr',
          vmin=[-2 / np.pi, 2 / np.pi])
ax.set_aspect('equal')
#
#class compute_Wigner:
#    def __init__(self, space_size, nbWigner,nbCols, tempsSimul, syst):