Ejemplo n.º 1
0
    def test_sparse_matrix(self):

        from qulacs import QuantumState
        from qulacs.gate import SparseMatrix
        from scipy.sparse import lil_matrix
        n = 5
        state = QuantumState(n)
        matrix = lil_matrix((4, 4), dtype=np.complex128)
        matrix[0, 0] = 1 + 1.j
        matrix[1, 1] = 1. + 1.j
        gate = SparseMatrix([0, 1], matrix)
        gate.update_quantum_state(state)
        del gate
        del state
Ejemplo n.º 2
0
    def apply_circuit(self, x, theta):
        """
        Apply unitary gates U(x) and U(theta) to |0>
        
        Argument:
        x: dx1 numpy array (vector), the sample vector to be encoded.
        theta: n_qubitsx(3*D) numpy array, the decision variables.
        
        Return:
        circuit: quantum state after applying the circuit with the given theta.
        """

        state = QuantumState(self.n_qubits)
        state.set_zero_state()

        # Construct a circuit
        circuit = QuantumCircuit(self.n_qubits)
        circuit = self.unitary_x(circuit, x)
        circuit = self.unitary_theta(circuit, theta)

        # apply the circuit to the zero state
        circuit.update_quantum_state(state)
        return state
Ejemplo n.º 3
0
def cost_uhf_sample(Quket, print_level, qulacs_hamiltonian, qulacs_s2,
                    kappa_list, samplelist):
    """Function:
    Sample Hamiltonian and S**2 expectation values with UHF.
    Write out the statistics in csv files.

    Author(s): Takashi Tsuchimochi
    """
    noa = Quket.noa
    nob = Quket.nob
    nva = Quket.nva
    nvb = Quket.nvb
    n_electrons = Quket.n_electrons
    n_qubit_system = n_qubits
    n_qubits = Quket.n_qubits + 1
    anc = n_qubit_system

    ncyc = 13
    opt = f"0{n_qubit_system}b"
    prints("", filepath="./log.txt", opentype="w")
    for i_sample in samplelist:
        sampleEn = np.zeros((ncyc, 1))
        sampleS2 = np.zeros((ncyc, 1))

        for icyc in range(ncyc):
            prints(f"n_sample = {i_sample}  ({icyc:3d} / {ncyc})",
                   filepath="./log.txt")
            state = QuantumState(n_qubit_system)
            circuit_rhf = set_circuit_rhf(n_qubit_system, n_electrons)
            circuit_rhf.update_quantum_state(state)
            circuit = set_circuit_uhf(n_qubit_system, noa, nob, nva, nvb,
                                      kappa_list)
            circuit.update_quantum_state(state)
            Euhf = sample_observable(state, qulacs_hamiltonian, i_sample).real
            #S2 = sample_observable(state, qulacs_s2, i_sample).real
            #Euhf = adaptive_sample_observable(state,
            #                                  qulacs_hamiltonian,
            #                                  i_sample).real
            #S2 = adaptive_sample_observable(state, qulacs_s2, i_sample).real
            sampleEn[icyc, 0] = Euhf
            #sampleS2[icyc,0] = S2
            S2 = 0
        with open(f"./UEn_{i_sample}.csv", "w") as fEn:
            writer = csv.writer(fEn)
            writer.writerows(sampleEn)
        #with open('./US2_%d.csv' % i_sample, 'w') as fS2:
        #    writer = csv.writer(fS2)
        #    writer.writerows(sampleS2)
    return Euhf, S2
Ejemplo n.º 4
0
    def test_state_reflection(self):
        from qulacs import QuantumState
        from qulacs.gate import StateReflection
        n = 5
        s1 = QuantumState(n)

        def gen_gate():
            s2 = QuantumState(n)
            gate = StateReflection(s2)
            del s2
            return gate
        gate = gen_gate()
        gate.update_quantum_state(s1)
        del gate
        del s1
Ejemplo n.º 5
0
def test_ibm_gateset() -> None:
    state = QuantumState(3)
    state.set_zero_state()
    circ = Circuit(3)
    circ.add_gate(OpType.U1, 0.19, [0])
    circ.add_gate(OpType.U2, [0.19, 0.24], [1])
    circ.add_gate(OpType.U3, [0.19, 0.24, 0.32], [2])
    qulacs_circ = tk_to_qulacs(circ)
    qulacs_circ.update_quantum_state(state)

    state1 = QuantumState(3)
    state1.set_zero_state()
    qulacs_circ1 = QuantumCircuit(3)
    qulacs_circ1.add_U1_gate(0, 0.19 * np.pi)
    qulacs_circ1.add_U2_gate(1, 0.19 * np.pi, 0.24 * np.pi)
    qulacs_circ1.add_U3_gate(2, 0.19 * np.pi, 0.24 * np.pi, 0.32 * np.pi)
    qulacs_circ1.update_quantum_state(state1)
    overlap = inner_product(state1, state)
    assert np.isclose(1, overlap)
Ejemplo n.º 6
0
    def test_copied_parametric_gate(self):

        from qulacs import ParametricQuantumCircuit, QuantumState
        from qulacs.gate import ParametricRX

        def f():
            circuit = ParametricQuantumCircuit(1)
            gate = ParametricRX(0, 0.1)
            circuit.add_parametric_gate(gate)
            circuit.add_parametric_gate(gate)
            circuit.add_gate(gate)
            gate.set_parameter_value(0.2)
            circuit.add_parametric_gate(gate)
            circuit.add_parametric_RX_gate(0, 0.3)
            gate2 = gate.copy()
            gate2.set_parameter_value(0.4)
            gate.set_parameter_value(1.0)
            del gate
            circuit.add_parametric_gate(gate2)
            circuit.remove_gate(1)
            del gate2
            return circuit

        c = f()
        for gc in range(c.get_parameter_count()):
            val = c.get_parameter(gc)
            c.set_parameter(gc, val + 1.0)
            self.assertAlmostEqual(val,
                                   gc * 0.1 + 0.1,
                                   msg="check vector size")

        d = c.copy()
        del c
        for gc in range(d.get_parameter_count()):
            val = d.get_parameter(gc)
            d.set_parameter(gc, val + 10)
            val = d.get_parameter(gc)
            self.assertAlmostEqual(val,
                                   11.1 + gc * 0.1,
                                   msg="check vector size")

        qs = QuantumState(1)
        d.update_quantum_state(qs)
        del d
        del qs
Ejemplo n.º 7
0
def cost_uccd(Quket, print_level, kappa_list, theta_list, threshold=1e-2):
    """Function:
    Energy functional of UCCD
    !!!!! Not maintained and thus may fail !!!!!

    Author(s): Takashi Tsuchimochi
    """
    from .hflib import set_circuit_rhf

    t1 = time.time()

    rho = Quket.rho
    noa = Quket.noa
    nob = Quket.nob
    nva = Quket.nva
    nvb = Quket.nvb
    n_qubits = Quket.n_qubits
    n_electrons = Quket.n_electrons
    ndim = Quket.ndim

    state = QuantumState(n_qubits)
    set_circuit = set_circuit_rhf(n_qubits, n_electrons)
    set_circuit.update_quantum_state(state)

    circuit = set_circuit_uccd(n_qubits, noa, nob, nva, nvb, theta_list)
    for i in range(rho):
        circuit.update_quantum_state(state)
    Euccd = Quket.qulacs.Hamiltonian.get_expectation_value(state)
    S2 = Quket.qulacs.S2.get_expectation_value(state)

    t2 = time.time()
    cput = t2 - t1
    if print_level > 0:
        cf.icyc += 1
        prints(f"{cf.icyc:5d}: E[UCCD] = {Euccd:.12f}  <S**2> = {S2:17.15f}  "
               f"CPU Time = {cput:2.5f}")
        SaveTheta(ndim, theta_list, cf.tmp)
    if print_level > 1:
        prints("\n(UCCD state)")
        print_state(state)

    # Store UCCD wave function
    Quket.state = state
    return Euccd, S2
Ejemplo n.º 8
0
def qite_anti(Quket, id_set, size):
    ### Parameter setting
    ansatz = Quket.ansatz
    n = Quket.n_qubits
    db = Quket.dt
    qbit = Quket.det
    ntime = Quket.maxiter
    observable = Quket.qulacs.Hamiltonian
    S2_observable = Quket.qulacs.S2
    threshold = Quket.ftol
    S2 = 0

    prints(f"QITE: Pauli operator group size = {size}")
    if ansatz != "cite":
        sigma_list, sigma_ij_index, sigma_ij_coef = qite_s_operators(id_set, n)
        len_list = len(sigma_list)
        prints(f"    Unique sigma list = {len_list}")

    index = np.arange(n)
    delta = QuantumState(n)
    first_state = QuantumState(n)
    first_state.set_computational_basis(qbit)

    energy = []
    psi_dash = first_state.copy()

    t1 = time.time()
    cf.t_old = t1

    En = observable.get_expectation_value(psi_dash)
    energy.append(En)
    if S2_observable is not None:
        S2 = S2_observable.get_expectation_value(psi_dash)

    dE = 100
    for t in range(ntime):
        t2 = time.time()
        cput = t2 - cf.t_old
        cf.t_old = t2
        if cf.debug:
            print_state(psi_dash)
        prints(f"{t*db:6.2f}: E = {En:.12f}  <S**2> = {S2:17.15f}  "
               f"CPU Time = {cput: 5.2f}")

        if abs(dE) < threshold:
            break
        if t == 0:
            xv = np.zeros(size)

        T0 = time.time()
        delta = calc_delta(psi_dash, observable, n, db)
        T1 = time.time()

        if ansatz == "cite":
            delta.add_state(psi_dash)
            psi_dash = delta.copy()
        else:
            #for i in range(size):
            #   pauli_id = id_set[i]
            #   circuit_i = make_gate(n, index, pauli_id)
            #   state_i = psi_dash.copy()
            #   circuit_i.update_quantum_state(state_i)
            #   print(i)
            #   for j in range(i+1):
            #       pauli_id = id_set[j]
            #       circuit_j = make_gate(n, index, pauli_id)
            #       state_j = psi_dash.copy()
            #       circuit_j.update_quantum_state(state_j)
            #       s = inner_product(state_j, state_i)
            #       S[i][j] = s
            #       S[j][i] = s

            ###  Compute Sij as expectation values of sigma_list
            Sij_list = np.zeros(len_list)
            Sij_my_list = np.zeros(len_list)
            ipos, my_ndim = mpi.myrange(len_list)
            T2 = time.time()
            for iope in range(ipos, ipos + my_ndim):
                val = sigma_list[iope].get_expectation_value(psi_dash)
                Sij_my_list[iope] = val
            T3 = time.time()
            mpi.comm.Allreduce(Sij_my_list, Sij_list, mpi.MPI.SUM)
            T4 = time.time()

            ### Distribute Sij
            ij = 0
            sizeT = size * (size - 1) // 2
            ipos, my_ndim = mpi.myrange(sizeT)
            S = np.zeros((size, size), dtype=complex)
            my_S = np.zeros((size, size), dtype=complex)
            for i in range(size):
                for j in range(i):
                    if ij in range(ipos, ipos + my_ndim):
                        ind = sigma_ij_index[ij]
                        coef = sigma_ij_coef[ij]
                        my_S[i, j] = coef * Sij_list[ind]
                        my_S[j, i] = my_S[i, j].conjugate()
                    ij += 1
            mpi.comm.Allreduce(my_S, S, mpi.MPI.SUM)
            for i in range(size):
                S[i, i] = 1

            T5 = time.time()
            sigma = []
            for i in range(size):
                pauli_id = id_set[i]
                circuit_i = make_gate(n, index, pauli_id)
                state_i = psi_dash.copy()
                circuit_i.update_quantum_state(state_i)
                sigma.append(state_i)
            T6 = time.time()

            b_l = np.empty(size)
            for i in range(size):
                b_i = inner_product(sigma[i], delta)
                b_i = -2 * b_i.imag
                b_l[i] = b_i
            Amat = 2 * np.real(S)
            T7 = time.time()

            zct = b_l @ Amat

            def cost_fun(vct):
                return LA.norm(Amat @ vct - b_l)**2

            def J_cost_fun(vct):
                wct = Amat.T @ Amat @ vct
                return 2.0 * (wct - zct)

            #x = sp.optimize.minimize(cost_fun, x0=xv, method='Newton-CG',
            #                         jac=J_cost_fun, tol=1e-8).x
            #xv = x.copy()
            #x = sp.optimize.least_squares(cost_fun, x0=xv, ftol=1e-8).x
            #xv = x.copy()
            x, res, rnk, s = lstsq(Amat, b_l, cond=1e-8)
            a = x.copy()
            ### Just in case, broadcast a...
            mpi.comm.Bcast(a, root=0)

            T8 = time.time()
            psi_dash = calc_psi_lessH(psi_dash, n, index, a, id_set)
            T9 = time.time()

            if cf.debug:
                prints(f"T0 -> T1  {T1-T0}")
                prints(f"T1 -> T2  {T2-T1}")
                prints(f"T2 -> T3  {T3-T2}")
                prints(f"T3 -> T4  {T4-T3}")
                prints(f"T4 -> T5  {T5-T4}")
                prints(f"T5 -> T6  {T6-T5}")
                prints(f"T6 -> T7  {T7-T6}")
                prints(f"T7 -> T8  {T8-T7}")
                prints(f"T8 -> T9  {T9-T8}")

        En = observable.get_expectation_value(psi_dash)
        if S2_observable is not None:
            S2 = S2_observable.get_expectation_value(psi_dash)
        energy.append(En)
        dE = energy[t + 1] - energy[t]

    print_state(psi_dash, name="QITE")
Ejemplo n.º 9
0
 def func2():
     qs = QuantumState(2)
     circuit = func()
     circuit.update_quantum_state(qs)
Ejemplo n.º 10
0
 def gen_gate():
     s2 = QuantumState(n)
     gate = StateReflection(s2)
     del s2
     return gate
Ejemplo n.º 11
0
def qite_exact(Quket):
    nspin = Quket.n_qubits
    db = Quket.dt
    ntime = Quket.maxiter
    qbit = Quket.det
    observable = Quket.qulacs.Hamiltonian
    threshold = Quket.ftol

    active_qubit = [x for x in range(nspin)]
    n = nspin
    size = 4**nspin
    index = np.arange(n)
    delta = QuantumState(n)
    first_state = QuantumState(n)
    first_state.set_computational_basis(qbit)

    prints(f"Exact QITE: Pauli operator group size = {size}")

    energy = []
    psi_dash = first_state.copy()
    value = observable.get_expectation_value(psi_dash)
    energy.append(value)

    t1 = time.time()
    cf.t_old = t1
    dE = 100
    for t in range(ntime):
        t2 = time.time()
        cput = t2 - cf.t_old
        cf.t_old = t2
        if cf.debug:
            print_state(psi_dash)
        prints(f"{t*db:6.2f}: E = {value:.12f}  CPU Time = {cput:5.2f}")

        if abs(dE) < threshold:
            break
        #if t == 0:
        #    xv = np.zeros(size)
        psi_dash_copy = psi_dash.copy()

        #mpi.comm.bcast(size, root=0)
        #S_part = np.zeros((size, size), dtype=complex)
        #S = np.zeros((size, size), dtype=complex)
        #sizeT = size*(size+1)//2
        #nblock = sizeT//mpi.nprocs

        #ij = mpi.rank*nblock
        #start = int(np.sqrt(2*ij + 1/4) - 1/2)
        #end = int(np.sqrt(2*(ij+nblock) + 1/4) - 1/2)
        #for i in range(start, end):
        #    for j in range(i+1):
        #        S_part[i, j] = calc_inner1(i, j, n, active_qubit,
        #                                   index, psi_dash)
        #        ij += 1
        #    S[:i, i] = S[i, :i]
        #mpi.comm.Allreduce(S_part, S, mpi.MPI.SUM)

        S_part = np.zeros((size, size), dtype=complex)
        S = np.zeros((size, size), dtype=complex)
        sizeT = size * (size - 1) // 2
        ipos, my_ndim = mpi.myrange(sizeT)
        ij = 0
        for i in range(size):
            for j in range(i):
                if ij in range(ipos, ipos + my_ndim):
                    S_part[i, j] = calc_inner1(i, j, n, active_qubit, index,
                                               psi_dash)
                    S_part[j, i] = S_part[i, j].conjugate()
                ij += 1
        mpi.comm.Allreduce(S_part, S, mpi.MPI.SUM)
        for i in range(size):
            S[i, i] = 1

        sigma = []
        for i in range(size):
            state_i = make_state1(i, n, active_qubit, index, psi_dash)
            sigma.append(state_i)

        delta = calc_delta(psi_dash, observable, n, db)
        b_l = []
        b_l = np.empty(size)
        for i in range(size):
            b_i = inner_product(sigma[i], delta)
            b_i = -2 * b_i.imag
            b_l[i] = b_i

        Amat = 2 * np.real(S)
        zct = b_l @ Amat

        #def cost_fun(vct):
        #    return LA.norm(Amat@vct - b_l)**2

        #def J_cost_fun(vct):
        #    wct = Amat.T@Amat@vct
        #    return 2.0*(wct-zct)

        #x = sp.optimize.minimize(cost_fun, x0=xv, method="Newton-CG",
        #                         jac=J_cost_fun, tol=1e-8).x
        #xv = x.copy()
        x, res, rnk, s = lstsq(Amat, b_l, cond=1.0e-8)
        a = x.copy()
        ### Just in case, broadcast a...
        mpi.comm.Bcast(a, root=0)
        psi_dash = calc_psi(psi_dash_copy, n, index, a, active_qubit)

        value = observable.get_expectation_value(psi_dash)
        energy.append(value)
        dE = energy[t + 1] - energy[t]
Ejemplo n.º 12
0
def cost_phf_sample(Quket, print_level,
                    qulacs_hamiltonian, qulacs_hamiltonianZ, qulacs_s2Z,
                    qulacs_ancZ, coef0_H, coef0_S2, ref, theta_list,
                    samplelist):
    """Function:
    Sample Hamiltonian and S**2 expectation values with PHF and PUCCSD.
    Write out the statistics in csv files.

    Author(s): Takashi Tsuchimochi
    """
    t1 = time.time()

    noa = Quket.noa
    nob = Quket.nob
    nva = Quket.nva
    nvb = Quket.nvb
    n_electrons = Quket.n_electrons
    n_qubit_system = n_qubits
    n_qubits = Quket.n_qubits + 1
    anc = n_qubit_system
    ndim1 = Quket.ndim1

    state = QuantumState(n_qubits)
    circuit_rhf = set_circuit_rhfZ(n_qubits, n_electrons)
    circuit_rhf.update_quantum_state(state)

    if ref == "phf":
        circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb, theta_list)
        circuit_uhf.update_quantum_state(state)
        print("pHF")
    elif ref == "puccsd":
        circuit = set_circuit_uccsd(n_qubits, noa, nob, nva, nvb, theta_list,
                                    ndim1)
        for i in range(rho):
            circuit.update_quantum_state(state)
        print("UCCSD")

    if print_level > -1:
        print("State before projection")
        utils.print_state(state, n_qubit_system)
    #### Set post-measurement states ####
    #poststate0 = state.copy()
    #poststate1 = state.copy()
    #circuit0 = QuantumCircuit(n_qubits)
    #circuit1 = QuantumCircuit(n_qubits)
    #### Projection to anc = 0 or anc = 1 ###
    #circuit0.add_gate(P0(0))
    #circuit1.add_gate(P1(0))
    #circuit0.update_quantum_state(poststate0)
    #circuit1.update_quantum_state(poststate1)
    #### Renormalize each state ###
    #norm0 = poststate0.get_squared_norm()
    #norm1 = poststate1.get_squared_norm()
    #poststate0.normalize(norm0)
    #poststate1.normalize(norm1)

    ### grid loop ###
    Ng = 4
    beta = [-0.861136311594053, -0.339981043584856,
             0.339981043584856,  0.861136311594053]
    wg = [0.173927422568724, 0.326072577431273,
          0.326072577431273, 0.173927422568724]

    Ng = 2
    beta = [0.577350269189626, -0.577350269189626]
    wg = [0.5, 0.5]

    ### a list to compute the probability to observe 0 in ancilla qubit
    p0_list = np.full(n_qubits, 2)
    p0_list[-1] = 0

    ### Array for <HUg>, <S2Ug>, <Ug>
    # samplelist = [10,100,1000,10000,100000,1000000,10000000]
    ncyc = 4
    prints("", filepath="./log2.txt")
    for i_sample in samplelist:
        i_sample_x = i_sample
        if i_sample == 10000000:
            print("OK")
            ncyc = ncyc*10
            i_sample_x = 1000000
        sampleHUg1 = []
        sampleHUg2 = []
        sampleHUg3 = []
        sampleHUg4 = []
        sampleS2Ug1 = []
        sampleS2Ug2 = []
        sampleS2Ug3 = []
        sampleS2Ug4 = []
        sampleUg1 = []
        sampleUg2 = []
        sampleUg3 = []
        sampleUg4 = []
        # sampleEn = []
        # sampleS2 = []
        sampleHUg = np.zeros((ncyc, Ng))
        sampleS2Ug = np.zeros((ncyc, Ng))
        sampleUg = np.zeros((ncyc, Ng))
        sampleEn = np.zeros((ncyc, 1))
        sampleS2 = np.zeros((ncyc, 1))

        for icyc in range(ncyc):
            prints(f"n_sample = {i_sample_x}  ({icyc} / {ncyc})",
                   filepath="./log2.txt")
            HUg = []
            S2Ug = []
            Ug = []
            Ephf = S2 = Norm = 0
            for i in range(Ng):
                ### Copy quantum state of UHF (cannot be done in real device) ###
                state_g = QuantumState(n_qubits)
                state_g.load(state)
                ### Construct Ug test
                circuit_ug = QuantumCircuit(n_qubits)
                ### Hadamard on anc
                circuit_ug.add_H_gate(anc)
                controlled_Ug(circuit_ug, n_qubits, anc, np.arccos(beta[i]))
                circuit_ug.add_H_gate(anc)
                circuit_ug.update_quantum_state(state_g)

                ### Set post-measurement states ####
                poststate0 = state_g.copy()
                poststate1 = state_g.copy()
                circuit0 = QuantumCircuit(n_qubits)
                circuit1 = QuantumCircuit(n_qubits)
                ### Projection to anc = 0 or anc = 1 ###
                circuit0.add_gate(P0(anc))
                circuit1.add_gate(P1(anc))
                circuit0.update_quantum_state(poststate0)
                circuit1.update_quantum_state(poststate1)
                ### Renormalize each state ###
                norm0 = poststate0.get_squared_norm()
                norm1 = poststate1.get_squared_norm()
                poststate0.normalize(norm0)
                poststate1.normalize(norm1)
                ### Set ancilla qubit of poststate1 to zero (so that it won't be used) ###
                circuit_anc = QuantumCircuit(n_qubits)
                circuit_anc.add_X_gate(anc)
                circuit_anc.update_quantum_state(poststate1)
                print(
                        test_transition_observable(
                            state_g, qulacs_hamiltonianZ,
                            poststate0, poststate1, 100000))
                # exit()

                ### Probabilities for getting 0 and 1 in ancilla qubit ###
                p0 = state_g.get_marginal_probability(p0_list)
                p1 = 1 - p0

                ### Compute expectation value <HUg> ###
                HUg.append(sample_observable(state_g,
                                             qulacs_hamiltonianZ,
                                             i_sample_x).real)
                #HUg.append(adaptive_sample_observable(state_g,
                #                                      qulacs_hamiltonianZ,
                #                                      i_sample_x).real)
                ### <S2Ug> ###
                S2Ug.append(sample_observable(state_g,
                                              qulacs_s2Z,
                                              i_sample_x).real)
                #S2Ug.append(adaptive_sample_observable(state_g,
                #                                       qulacs_s2Z,
                #                                       i_sample_x).real)
                #S2Ug.append(qulacs_s2Z.get_expectation_value(state_g))
                #HUg.append(0)
                #S2Ug.append(0)

                #Ug.append(p0 - p1)
                n_term = qulacs_hamiltonianZ.get_term_count()
                n_sample_total = i_sample_x * n_term
                # in the worst-case scenario,
                # Ug is measured as many times as n_sample_total
                #(required to evaluate HUg)
                Ug.append(sample_observable(state_g,
                                            qulacs_ancZ,
                                            i_sample_x*n_term).real)
                #p0_sample = 0
                #for j_sample in range(n_sample_total):
                #   if(p0 > np.random.rand()):
                #      p0_sample += 1
                #Ug.append(2*p0_sample/n_sample_total - 1)
                ### Norm accumulation ###
                Norm += wg[i]*Ug[i]
                sampleHUg[icyc, i] = HUg[i]
                sampleS2Ug[icyc, i] = S2Ug[i]
                sampleUg[icyc, i] = Ug[i]
            #print('p0 : ',p0,'  p1 : ',p1,  '  p0 - p1 : ',p0-p1)

            sampleHUg1.append(HUg[0])
            sampleHUg2.append(HUg[1])
            #sampleHUg3.append(HUg[2])
            #sampleHUg4.append(HUg[3])
            sampleS2Ug1.append(S2Ug[0])
            sampleS2Ug2.append(S2Ug[1])
            #sampleS2Ug3.append(S2Ug[2])
            #sampleS2Ug4.append(S2Ug[3])
            sampleUg1.append(Ug[0])
            sampleUg2.append(Ug[1])
            #sampleUg3.append(Ug[2])
            #sampleUg4.append(Ug[3])

            ### Energy calculation <HP>/<P> and <S**2P>/<P> ###
            Ephf = 0
            for i in range(Ng):
                Ephf += wg[i]*HUg[i]/Norm
                S2 += wg[i]*S2Ug[i]/Norm
            # print(" <S**2> = ", S2, '\n')
            Ephf += coef0_H
            S2 += coef0_S2
            sampleEn[icyc, 0] = Ephf
            sampleS2[icyc, 0] = S2
            # print(" <E[PHF]> (Nsample = ",i_sample,") = ", Ephf)
        #print(f"(n_sample = {i_sample}):  sample HUg1\n",sampleHUg1)
        #print(f"(n_sample = {i_sample}):  sample HUg2\n",sampleHUg2)
        #print(f"(n_sample = {i_sample}):  sample HUg3\n",sampleHUg3)
        #print(f"(n_sample = {i_sample}):  sample HUg4\n",sampleHUg4)
        #print(f"(n_sample = {i_sample}):  sample S2Ug1\n",sampleS2Ug1)
        #print(f"(n_sample = {i_sample}):  sample S2Ug2\n",sampleS2Ug2)
        #print(f"(n_sample = {i_sample}):  sample S2Ug3\n",sampleS2Ug3)
        #print(f"(n_sample = {i_sample}):  sample S2Ug4\n",sampleS2Ug4)
        #print(f"(n_sample = {i_sample}):  sample Ug1\n",sampleUg1)
        #print(f"(n_sample = {i_sample}):  sample Ug2\n",sampleUg2)
        #print(f"(n_sample = {i_sample}):  sample Ug3\n",sampleUg3)
        #print(f"(n_sample = {i_sample}):  sample Ug4\n",sampleUg4)
        #print(f"(n_sample = {i_sample}):  sample HUg1\n",sampleHUg1)
        #print(f"(n_sample = {i_sample}):  sample HUg2\n",sampleHUg2)
        #print(f"(n_sample = {i_sample}):  sample HUg3\n",sampleHUg3)
        #print(f"(n_sample = {i_sample}):  sample HUg4\n",sampleHUg4)
        #print(f"(n_sample = {i_sample}):  sample En\n",sampleEn)
        #print(f"(n_sample = {i_sample}):  sample S2\n",sampleS2)
        with open(f"./Ug_{i_sample}.csv", "w") as fUg:
            writer = csv.writer(fUg)
            writer.writerows(sampleUg)
        with open(f"./HUg_{i_sample}.csv", "w") as fHUg:
            writer = csv.writer(fHUg)
            writer.writerows(sampleHUg)
        with open(f"./S2Ug_{i_sample}.csv", "w") as fS2Ug:
            writer = csv.writer(fS2Ug)
            writer.writerows(sampleS2Ug)
        with open(f"./En_{i_sample}.csv", "w") as fEn:
            writer = csv.writer(fEn)
            writer.writerows(sampleEn)
        with open(f"./S2_{i_smaple}.csv", "w") as fS2:
            writer = csv.writer(fS2)
            writer.writerows(sampleS2)
    return Ephf, S2
Ejemplo n.º 13
0
def test_observable(state, obs, obsZ, n_sample):
    """Function

    Args:
        state (qulacs.QuantumState): This includes entangled ancilla
                                     (n_qubits = n_qubit_system + 1)
        obs (qulacs.Observable): This does not include ancilla Z
                                 (n_qubit_system)
        obsZ (qulacs.Observable): Single Pauli Z for ancilla (1)
        poststate0 (qulacs.QuantumState): post-measurement state
                                          when ancilla = 0 (n_qubit_system)
        poststate1 (qulacs.QuantumState): post-measurement state
                                          when ancilla = 1 (n_qubit_system)
        n_sample (int):  number of samples for each observable

    Return:
        :float: sampled expectation value of the observable

    Author(s): Takashi Tsuchimochi
    """
    n_term = obs.get_term_count()
    n_qubits = obs.get_qubit_count()
    p0 = state.get_zero_probability(n_qubits)
    p1 = 1 - p0
    opt = f"0{n_qubits}b"

    expH = 0
    exp = []
    coef = []
    buf_state = QuantumState(n_qubits)
    for i in range(n_term):
        pauli_term = obs.get_term(i)
        coef.append(pauli_term.get_coef().real)
        pauli_id = pauli_term.get_pauli_id_list()
        pauli_index = pauli_term.get_index_list()

        if len(pauli_id) == 0:  # means identity
            exp.extend(coef)
            continue

        buf_state.load(state)
        measurement_circuit = QuantumCircuit(n_qubits)
        mask = "".join(["1" if n_qubits - 1 - k in pauli_index else "0"
                        for k in range(n_qubits)])
        measure_observable = QubitOperator((), 1)
        for single_pauli, index in zip(pauli_id, pauli_index):
            if single_pauli == 1:
                ###  X
                measurement_circuit.add_H_gate(index)
                measure_observable *= QubitOperator(f"X{index}")
            elif single_pauli == 2:
                ###  Y
                measurement_circuit.add_Sdag_gate(index)
                measurement_circuit.add_H_gate(index)
                measure_observable *= QubitOperator(f"Y{index}")
            elif single_pauli == 3:
                ###  Z
                measure_observable *= QubitOperator(f"Z{index}")
        qulacs_measure_observable \
                = create_observable_from_openfermion_text(
                        str(measure_observable))
        measurement_circuit.update_quantum_state(buf_state)
        #exp.append(obsZ.get_expectation_value(buf_state).real)
        samples = buf_state.sampling(n_sample)
        #print(f"samples? {format(samples[0], opt)}")
        #print(f"I = {i:5d}  h_I = {coef[i]:10.5f}  <P_I> = {exp[i]:10.5f}")
        #mask = int(mask, 2)
        #print(sum(list(map(lambda x: (-1)**(bin(x & mask).count('1')),
        #                   samples))))
        #print(coef*sum(list(map(lambda x: (-1)**(bin(x & mask).count('1')),
        #                        samples))))
        expH += coef[i]*exp[i]
        samples = buf_state.sampling(n_sample)

        mask = int(mask, 2)
        prob = (sum(list(map(lambda x: (-1)**(bin(x & mask).count("1")),
                             samples)))
                /n_sample)
        measure_list = list(map(int, np.ones(n_qubits)*2))
        for j in pauli_index:
            measure_list[j] = 1
        #print(qulacs_measure_observable.get_expectation_value(state))
        expH += coef[i]*prob
        #print(f"coef: {coef[i]:10.5f}  prob: {prob:10.5f}")
    return expH
Ejemplo n.º 14
0
def NProj(Quket, Q, threshold=1e-8):
    """Function
    Perform number-projection to QuantumState |Q>
            |Q'>  =  PN |Q>
    where PN is a number-projection operator (non-unitary).
            PN = \sum_i^ng   wg[i] Ug[i]
    This function provides a shortcut to |Q'>, which is unreal.
    One actually needs to develop a quantum circuit for this
    (See QST 6, 014004 (2021)).

    Author(s): Takashi Tsuchimochi
    """
    n_qubits = Q.get_qubit_count()
    state_P = QuantumState(n_qubits)
    state_P.multiply_coef(0)
    state_g = QuantumState(n_qubits)
    nphi = max(Quket.projection.number_ngrids, 1)
    #print_state(Q)
    for iphi in range(nphi):
        coef = (Quket.projection.np_weight[iphi] *
                np.exp(1j * Quket.projection.np_angle[iphi] *
                       (Quket.projection.n_active_electrons -
                        Quket.projection.n_active_orbitals)))

        state_g = Q.copy()
        circuit = QuantumCircuit(n_qubits)
        set_circuit_ExpNa(circuit, n_qubits, Quket.projection.np_angle[iphi])
        set_circuit_ExpNb(circuit, n_qubits, Quket.projection.np_angle[iphi])
        circuit.update_quantum_state(state_g)
        state_g.multiply_coef(coef)
        state_P.add_state(state_g)

    norm2 = state_P.get_squared_norm()
    if norm2 < threshold:
        error(
            "Norm of number-projected state is too small!\n",
            "This usually means the broken-symmetry state has NO component ",
            "of the target number.")
    state_P.normalize(norm2)
    return state_P
Ejemplo n.º 15
0
class QulacsDevice(Device):
    """Qulacs device"""
    name = 'Qulacs device'
    short_name = 'qulacs.simulator'
    pennylane_requires = '>=0.5.0'
    version = __version__
    author = 'Steven Oud'

    _capabilities = {'model': 'qubit', 'tensor_observables': True}

    _operations_map = {
        'QubitStateVector': None,
        'BasisState': None,
        'QubitUnitary': None,
        'Toffoli': toffoli,
        'CSWAP': CSWAP,
        'CRZ': crz,
        'Rot': None,
        'SWAP': gate.SWAP,
        'CNOT': gate.CNOT,
        'CZ': gate.CZ,
        'S': gate.S,
        'Sdg': gate.Sdag,
        'T': gate.T,
        'Tdg': gate.Tdag,
        'RX': gate.RX,
        'RY': gate.RY,
        'RZ': gate.RZ,
        'PauliX': gate.X,
        'PauliY': gate.Y,
        'PauliZ': gate.Z,
        'Hadamard': gate.H
    }
    _observable_map = {
        'PauliX': X,
        'PauliY': Y,
        'PauliZ': Z,
        'Hadamard': H,
        'Identity': I,
        'Hermitian': hermitian
    }

    operations = _operations_map.keys()
    observables = _observable_map.keys()

    def __init__(self, wires, gpu=False, **kwargs):
        super().__init__(wires=wires)

        if gpu:
            if not GPU_SUPPORTED:
                raise DeviceError(
                    'GPU not supported with installed version of qulacs. '
                    'Please install "qulacs-gpu" to use GPU simulation.')

            self._state = QuantumStateGpu(wires)
        else:
            self._state = QuantumState(wires)

        self._circuit = QuantumCircuit(wires)
        self._first_operation = True

    def apply(self, operation, wires, par):
        par = np.negative(par)
        if operation == 'BasisState' and not self._first_operation:
            raise DeviceError(
                'Operation {} cannot be used after other Operations have already been applied '
                'on a {} device.'.format(operation, self.short_name))

        self._first_operation = False

        if operation == 'QubitStateVector':
            if len(par[0]) != 2**len(wires):
                raise ValueError('State vector must be of length 2**wires.')

            self._state.load(par[0])
        elif operation == 'BasisState':
            if len(par[0]) != len(wires):
                raise ValueError('Basis state must prepare all qubits.')

            basis_state = 0
            for bit in reversed(par[0]):
                basis_state = (basis_state << 1) | bit

            self._state.set_computational_basis(basis_state)
        elif operation == 'QubitUnitary':
            if len(par[0]) != 2**len(wires):
                raise ValueError(
                    'Unitary matrix must be of shape (2**wires, 2**wires).')

            unitary_gate = gate.DenseMatrix(wires, par[0])
            self._circuit.add_gate(unitary_gate)
        elif operation == 'Rot':
            self._circuit.add_gate(
                gate.merge([
                    gate.RZ(wires[0], par[0]),
                    gate.RY(wires[0], par[1]),
                    gate.RZ(wires[0], par[2])
                ]))
        elif operation in ('CRZ', 'Toffoli', 'CSWAP'):
            mapped_operation = self._operations_map[operation]
            if callable(mapped_operation):
                gate_matrix = mapped_operation(*par)
            else:
                gate_matrix = mapped_operation

            dense_gate = gate.DenseMatrix(wires, gate_matrix)
            self._circuit.add_gate(dense_gate)
        else:
            mapped_operation = self._operations_map[operation]
            self._circuit.add_gate(mapped_operation(*wires, *par))

    @property
    def state(self):
        return self._state.get_vector()

    def pre_measure(self):
        self._circuit.update_quantum_state(self._state)

    def expval(self, observable, wires, par):
        bra = self._state.copy()

        if isinstance(observable, list):
            A = self._get_tensor_operator_matrix(observable, par)
            wires = [item for sublist in wires for item in sublist]
        else:
            A = self._get_operator_matrix(observable, par)

        dense_gate = gate.DenseMatrix(wires, A)
        dense_gate.update_quantum_state(self._state)

        expectation = inner_product(bra, self._state)

        return expectation.real

    def probabilities(self):
        states = itertools.product(range(2), repeat=self.num_wires)
        probs = np.abs(self.state)**2

        return OrderedDict(zip(states, probs))

    def reset(self):
        self._state.set_zero_state()
        self._circuit = QuantumCircuit(self.num_wires)

    def _get_operator_matrix(self, operation, par):
        A = self._observable_map[operation]
        if not callable(A):
            return A

        return A(*par)

    def _get_tensor_operator_matrix(self, obs, par):
        ops = [self._get_operator_matrix(o, p) for o, p in zip(obs, par)]
        return functools.reduce(np.kron, ops)
Ejemplo n.º 16
0
value_train = list()

input_test = list()
value_test = list()

with open('Training.data', 'rb') as f:
    data = pickle.load(f)


training_data = data[0:80]
test_data = data[80:100]

f = open('loss2.txt',"w" )

print(training_data[0])
state = QuantumState(nqubit)

for d in data:
    input_train.append(d[0] )
    value_train.append(d[1])

# To have a basic training and cross validation set
for d in training_data:
    input_train.append(d[0])
    value_train.append(d[1])

for d in test_data:
    input_test.append(d[0])
    value_test.append(d[1])

Ejemplo n.º 17
0
        for j in range(n_qubit - 1):
            circuit.add_CNOT_gate(j, j + 1)
            circuit.add_gate(RY(j, theta_list[n_qubit * (1 + d) + j]))
            circuit.add_H_gate(j + 1)
        circuit.add_gate(
            RY(n_qubit - 1, theta_list[n_qubit * (1 + d) + n_qubit - 1]))

    return circuit


n_qubit = nvar
depth = 2
init_theta_list = np.random.randn(n_qubit * (depth + 1))
print("n_qubit =", n_qubit)

input_state = QuantumState(n_qubit)
input_state.set_zero_state()
#input_state.set_Haar_random_state()


def cost(theta_list):
    #input_state.set_zero_state()
    input_state.set_computational_basis(
        int('0b' + '1' * (n_qubit / 2) + '0' * (n_qubit / 2), 2))
    circ = ansatz_circuit(n_qubit, depth, theta_list)
    circ.update_quantum_state(input_state)
    value = qulacs_hamiltonian.get_expectation_value(input_state)
    print("  cost -->", value)
    return value

Ejemplo n.º 18
0
"""
probabilistic bit flip noise
"""

from qulacs import Observable
from qulacs import QuantumState, QuantumCircuit
from qulacs.gate import Probabilistic, X

import matplotlib.pyplot as plt

obs = Observable(1)
obs.add_operator(1, "Z 0")
state = QuantumState(1)
circuit = QuantumCircuit(1)
p = 0.1  # probability of bit flip
n_circuit_sample = 10000
n_depth = 20  # the number of probabilistic gate

probabilistic_pauli_gate = Probabilistic([p],
                                         [X(0)])  #define probabilistic gate

circuit.add_gate(probabilistic_pauli_gate)  # add the prob. gate to the circuit

exp_array = []
for depth in range(n_depth):
    exp = 0
    for i in [0] * n_circuit_sample:
        state.set_zero_state()
        for _ in range(depth):
            circuit.update_quantum_state(state)  # apply the prob. gate
        exp += obs.get_expectation_value(
Ejemplo n.º 19
0
        # partial trace
        p0 = psi.get_marginal_probability(
            [lambda i: 0 if i == a_idx else 2 for i in range(n_qubits)])
        p1 = psi.get_marginal_probability(
            [lambda i: 1 if i == a_idx else 2 for i in range(n_qubits)])
        # update kickback phase
        kth_digit = 1 if (p0 < p1) else 0
        kickback_phase = kickback_phase / 2 + kth_digit
    return -0.5 * np.pi * kickback_phase


if __name__ == "__main__":
    n_qubits = 3  # 2 for electron configurations and 1 for ancilla
    g_list = [0.3593, 0.0896, -0.4826, 0.0896]
    pauli_strings = ['Z 0', 'Y 0 Y 1', 'Z 1', 'X 0 X 1']
    hf_state = QuantumState(n_qubits)
    hf_state.set_computational_basis(0b001)  # |0>|01>
    t = 0.640
    n_itter = 16  # determine precission

    # validity check
    _, eigs = reduced_term_hamiltonian()
    e_exact = eigs[0]
    print('e_exact:{}'.format(e_exact))
    print('n, e_matrix, e_iqpe, |e_matrix-e_iqpe|, |e_exact-e_iqpe|')
    for n in range(1, 10, 2):
        iqpe_phase = iterative_phase_estimation(g_list,
                                                t,
                                                n_itter,
                                                hf_state,
                                                n_trotter_step=n,
Ejemplo n.º 20
0
def cost_proj(Quket,
              print_level,
              qulacs_hamiltonianZ,
              qulacs_s2Z,
              coef0_H,
              coef0_S2,
              kappa_list,
              theta_list=0,
              threshold=0.01):
    """Function:
    Energy functional for projected methods (phf, puccsd, puccd, opt_puccd)

    Author(s): Takashi Tsuchimochi
    """
    t1 = time.time()

    noa = Quket.noa
    nob = Quket.nob
    nva = Quket.nva
    nvb = Quket.nvb
    n_electrons = Quket.n_electrons
    rho = Quket.rho
    DS = Quket.DS
    anc = Quket.anc
    n_qubit_system = Quket.n_qubits
    n_qubits = n_qubit_system + 1
    # opt_psauccdとかはndimの計算が異なるけどこっちを使う?
    #ndim1 = noa * nva + nob * nvb
    #ndim2aa = int(noa * (noa - 1) * nva * (nva - 1) / 4)
    #ndim2ab = int(noa * nob * nva * nvb)
    #ndim2bb = int(nob * (nob - 1) * nvb * (nvb - 1) / 4)
    #ndim2 = ndim2aa + ndim2ab + ndim2bb
    ndim1 = Quket.ndim1
    ndim2 = Quket.ndim2
    ndim = Quket.ndim
    ref = Quket.ansatz

    state = QuantumState(n_qubits)
    if noa == nob:
        circuit_rhf = set_circuit_rhfZ(n_qubits, n_electrons)
    else:
        circuit_rhf = set_circuit_rohfZ(n_qubits, noa, nob)
    circuit_rhf.update_quantum_state(state)

    if ref == "phf":
        circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb,
                                       kappa_list)
        circuit_uhf.update_quantum_state(state)
    elif ref == "sghf":
        circuit_ghf = set_circuit_ghfZ(n_qubits, noa + nob, nva + nvb,
                                       kappa_list)
        circuit_ghf.update_quantum_state(state)
    elif ref == "puccsd":
        # First prepare UHF determinant
        circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb,
                                       kappa_list)
        circuit_uhf.update_quantum_state(state)
        # Then prepare UCCSD
        theta_list_rho = theta_list / rho
        circuit = set_circuit_uccsd(n_qubits, noa, nob, nva, nvb, 0,
                                    theta_list_rho, ndim1)
        for i in range(rho):
            circuit.update_quantum_state(state)
    elif ref == "puccd":
        # First prepare UHF determinant
        circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb,
                                       kappa_list)
        circuit_uhf.update_quantum_state(state)
        # Then prepare UCCD
        theta_list_rho = theta_list / rho
        circuit = set_circuit_uccd(n_qubits, noa, nob, nva, nvb,
                                   theta_list_rho)
        for i in range(rho):
            circuit.update_quantum_state(state)
    elif ref == "opt_puccd":
        if DS:
            # First prepare UHF determinant
            circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb,
                                           theta_list)
            circuit_uhf.update_quantum_state(state)
            # Then prepare UCCD
            theta_list_rho = theta_list[ndim1:] / rho
            circuit = set_circuit_uccd(n_qubits, noa, nob, nva, nvb,
                                       theta_list_rho)
            for i in range(rho):
                circuit.update_quantum_state(state)
        else:
            # First prepare UCCD
            theta_list_rho = theta_list[ndim1:] / rho
            circuit = set_circuit_uccd(n_qubits, noa, nob, nva, nvb,
                                       theta_list_rho)
            for i in range(rho):
                circuit.update_quantum_state(state)
            # then rotate
            circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb,
                                           theta_list)
            circuit_uhf.update_quantum_state(state)
    elif ref == "opt_psauccd":
        # ここが問題
        # ndim2が他と異なる
        #theta_list_rho = theta_list[ndim1 : ndim1+ndim2]/rho
        theta_list_rho = theta_list[ndim1:] / rho
        circuit = set_circuit_sauccd(n_qubits, noa, nva, theta_list_rho)
        for i in range(rho):
            circuit.update_quantum_state(state)
        circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb,
                                       theta_list)
        circuit_uhf.update_quantum_state(state)

    if print_level > 0:
        if ref in ("uhf", "phf", "suhf", "sghf"):
            SaveTheta(ndim, kappa_list, cf.tmp)
        else:
            SaveTheta(ndim, theta_list, cf.tmp)
    if print_level > 1:
        prints("State before projection")
        print_state(state, n_qubits=n_qubit_system)
        if ref in ("puccsd", "opt_puccd"):
            print_amplitudes(theta_list, noa, nob, nva, nvb, threshold)

    ### grid loop ###
    ### a list to compute the probability to observe 0 in ancilla qubit
    ### Array for <HUg>, <S2Ug>, <Ug>
    Ep = S2 = Norm = 0
    nalpha = max(Quket.projection.euler_ngrids[0], 1)
    nbeta = max(Quket.projection.euler_ngrids[1], 1)
    ngamma = max(Quket.projection.euler_ngrids[2], 1)
    HUg = np.empty(nalpha * nbeta * ngamma)
    S2Ug = np.empty(nalpha * nbeta * ngamma)
    Ug = np.empty(nalpha * nbeta * ngamma)
    ig = 0
    for ialpha in range(nalpha):
        alpha = Quket.projection.sp_angle[0][ialpha]
        alpha_coef = Quket.projection.sp_weight[0][ialpha]

        for ibeta in range(nbeta):
            beta = Quket.projection.sp_angle[1][ibeta]
            beta_coef = (Quket.projection.sp_weight[1][ibeta] *
                         Quket.projection.dmm[ibeta])

            for igamma in range(ngamma):
                gamma = Quket.projection.sp_angle[2][igamma]
                gamma_coef = Quket.projection.sp_weight[2][igamma]

                ### Copy quantum state of UHF (cannot be done in real device) ###
                state_g = QuantumState(n_qubits)
                state_g.load(state)
                ### Construct Ug test
                circuit_ug = QuantumCircuit(n_qubits)
                ### Hadamard on anc
                circuit_ug.add_H_gate(anc)
                #circuit_ug.add_X_gate(anc)
                #controlled_Ug(circuit_ug, n_qubits, anc, beta)
                controlled_Ug_gen(circuit_ug, n_qubits, anc, alpha, beta,
                                  gamma)
                #circuit_ug.add_X_gate(anc)
                circuit_ug.add_H_gate(anc)
                circuit_ug.update_quantum_state(state_g)

                ### Compute expectation value <HUg> ###
                HUg[ig] = qulacs_hamiltonianZ.get_expectation_value(state_g)
                ### <S2Ug> ###
                # print_state(state_g)
                S2Ug[ig] = qulacs_s2Z.get_expectation_value(state_g)
                ### <Ug> ###
                p0 = state_g.get_zero_probability(anc)
                p1 = 1 - p0
                Ug[ig] = p0 - p1

                ### Norm accumulation ###
                Norm += alpha_coef * beta_coef * gamma_coef * Ug[ig]
                Ep += alpha_coef * beta_coef * gamma_coef * HUg[ig]
                S2 += alpha_coef * beta_coef * gamma_coef * S2Ug[ig]
                ig += 1
    #        print('p0 : ',p0,'  p1 : ',p1,  '  p0 - p1 : ',p0-p1)
    #    print("Time: ",t2-t1)
    ### Energy calculation <HP>/<P> and <S**2P>/<P> ###
    Ep /= Norm
    S2 /= Norm
    Ep += coef0_H
    S2 += coef0_S2

    t2 = time.time()
    cpu1 = t2 - t1
    if print_level == -1:
        prints(f"Initial E[{ref}] = {Ep:.12f}  <S**2> = {S2:17.15f}  "
               f"rho = {rho}")
    elif print_level == 1:
        cput = t2 - cf.t_old
        cf.t_old = t2
        cf.icyc += 1
        prints(f"{cf.icyc:5d}: E[{ref}] = {Ep:.12f}  <S**2> = {S2:17.15f}  "
               f"CPU Time = {cput:5.2f}  ({cpu1:2.2f} / step)")
    elif print_level > 1:
        prints(f"Final: E[{ref}] = {Ep:.12f}  <S**2> = {S2:17.15f}  "
               f"rho = {rho}")
        print_state(state, n_qubits=n_qubits - 1)
        if ref in ("puccsd", "opt_puccd"):
            print_amplitudes(theta_list, noa, nob, nva, nvb)
        prints("HUg", HUg)
        prints("Ug", Ug)

    # Store wave function
    Quket.state = state
    return Ep, S2
Ejemplo n.º 21
0
def S2Proj(Quket, Q, threshold=1e-8):
    """Function
    Perform spin-projection to QuantumState |Q>
            |Q'>  =  Ps |Q>
    where Ps is a spin-projection operator (non-unitary).
            Ps = \sum_i^ng   wg[i] Ug[i]
    This function provides a shortcut to |Q'>, which is unreal.
    One actually needs to develop a quantum circuit for this
    (See PRR 2, 043142 (2020)).

    Author(s): Takashi Tsuchimochi
    """
    spin = Quket.projection.spin
    s = (spin - 1) / 2
    Ms = Quket.projection.Ms / 2

    n_qubits = Q.get_qubit_count()
    state_P = QuantumState(n_qubits)
    state_P.multiply_coef(0)

    nalpha = max(Quket.projection.euler_ngrids[0], 1)
    nbeta = max(Quket.projection.euler_ngrids[1], 1)
    ngamma = max(Quket.projection.euler_ngrids[2], 1)
    for ialpha in range(nalpha):
        alpha = Quket.projection.sp_angle[0][ialpha]
        alpha_coef = Quket.projection.sp_weight[0][ialpha] * np.exp(
            1j * alpha * Ms)

        for ibeta in range(nbeta):
            beta = Quket.projection.sp_angle[1][ibeta]
            beta_coef = (Quket.projection.sp_weight[1][ibeta] *
                         Quket.projection.dmm[ibeta])

            for igamma in range(ngamma):
                gamma = Quket.projection.sp_angle[2][igamma]
                gamma_coef = (Quket.projection.sp_weight[2][igamma] *
                              np.exp(1j * gamma * Ms))

                # Total Weight
                coef = (2 * s + 1) / (8 * np.pi) * (alpha_coef * beta_coef *
                                                    gamma_coef)

                state_g = QuantumState(n_qubits)
                state_g.load(Q)
                circuit_Rg = QuantumCircuit(n_qubits)
                set_circuit_Rg(circuit_Rg, n_qubits, alpha, beta, gamma)
                circuit_Rg.update_quantum_state(state_g)
                state_g.multiply_coef(coef)
                state_P.add_state(state_g)

    # Normalize
    norm2 = state_P.get_squared_norm()
    if norm2 < threshold:
        error(
            "Norm of spin-projected state is too small!\n",
            "This usually means the broken-symmetry state has NO component ",
            "of the target spin.")
    state_P.normalize(norm2)
    # print_state(state_P,name="P|Q>",threshold=1e-6)
    return state_P
Ejemplo n.º 22
0
class QulacsDevice(QubitDevice):
    """Qulacs device"""

    name = "Qulacs device"
    short_name = "qulacs.simulator"
    pennylane_requires = ">=0.11.0"
    version = __version__
    author = "Steven Oud and Xanadu"
    gpu_supported = GPU_SUPPORTED

    _capabilities = {
        "model": "qubit",
        "tensor_observables": True,
        "inverse_operations": True
    }

    _operation_map = {
        "QubitStateVector": None,
        "BasisState": None,
        "QubitUnitary": None,
        "Toffoli": gate.TOFFOLI,
        "CSWAP": gate.FREDKIN,
        "CRZ": crz,
        "SWAP": gate.SWAP,
        "CNOT": gate.CNOT,
        "CZ": gate.CZ,
        "S": gate.S,
        "T": gate.T,
        "RX": gate.RX,
        "RY": gate.RY,
        "RZ": gate.RZ,
        "PauliX": gate.X,
        "PauliY": gate.Y,
        "PauliZ": gate.Z,
        "Hadamard": gate.H,
        "PhaseShift": phase_shift,
    }

    _observable_map = {
        "PauliX": "X",
        "PauliY": "Y",
        "PauliZ": "Z",
        "Identity": "I",
        "Hadamard": None,
        "Hermitian": None,
    }

    operations = _operation_map.keys()
    observables = _observable_map.keys()

    # Add inverse gates to _operation_map
    _operation_map.update({k + ".inv": v for k, v in _operation_map.items()})

    def __init__(self, wires, shots=1000, analytic=True, gpu=False, **kwargs):
        super().__init__(wires=wires, shots=shots, analytic=analytic)

        if gpu:
            if not QulacsDevice.gpu_supported:
                raise DeviceError(
                    "GPU not supported with installed version of qulacs. "
                    "Please install 'qulacs-gpu' to use GPU simulation.")

            self._state = QuantumStateGpu(self.num_wires)
        else:
            self._state = QuantumState(self.num_wires)

        self._circuit = QuantumCircuit(self.num_wires)

        self._pre_rotated_state = self._state.copy()

    def apply(self, operations, **kwargs):
        rotations = kwargs.get("rotations", [])

        self.apply_operations(operations)
        self._pre_rotated_state = self._state.copy()

        # Rotating the state for measurement in the computational basis
        if rotations:
            self.apply_operations(rotations)

    def apply_operations(self, operations):
        """Apply the circuit operations to the state.

        This method serves as an auxiliary method to :meth:`~.QulacsDevice.apply`.

        Args:
            operations (List[pennylane.Operation]): operations to be applied
        """

        for i, op in enumerate(operations):
            if i > 0 and isinstance(op, (QubitStateVector, BasisState)):
                raise DeviceError(
                    "Operation {} cannot be used after other Operations have already been applied "
                    "on a {} device.".format(op.name, self.short_name))

            if isinstance(op, QubitStateVector):
                self._apply_qubit_state_vector(op)
            elif isinstance(op, BasisState):
                self._apply_basis_state(op)
            elif isinstance(op, QubitUnitary):
                self._apply_qubit_unitary(op)
            elif isinstance(op, (CRZ, PhaseShift)):
                self._apply_matrix(op)
            else:
                self._apply_gate(op)

    def _apply_qubit_state_vector(self, op):
        """Initialize state with a state vector"""
        wires = op.wires
        input_state = op.parameters[0]

        if len(input_state) != 2**len(wires):
            raise ValueError("State vector must be of length 2**wires.")
        if input_state.ndim != 1 or len(input_state) != 2**len(wires):
            raise ValueError("State vector must be of length 2**wires.")
        if not np.isclose(np.linalg.norm(input_state, 2), 1.0, atol=tolerance):
            raise ValueError("Sum of amplitudes-squared does not equal one.")

        input_state = _reverse_state(input_state)

        # call qulacs' state initialization
        self._state.load(input_state)

    def _apply_basis_state(self, op):
        """Initialize a basis state"""
        wires = op.wires
        par = op.parameters

        # translate from PennyLane to Qulacs wire order
        bits = par[0][::-1]
        n_basis_state = len(bits)

        if not set(bits).issubset({0, 1}):
            raise ValueError(
                "BasisState parameter must consist of 0 or 1 integers.")
        if n_basis_state != len(wires):
            raise ValueError(
                "BasisState parameter and wires must be of equal length.")

        basis_state = 0
        for bit in bits:
            basis_state = (basis_state << 1) | bit

        # call qulacs' basis state initialization
        self._state.set_computational_basis(basis_state)

    def _apply_qubit_unitary(self, op):
        """Apply unitary to state"""
        # translate op wire labels to consecutive wire labels used by the device
        device_wires = self.map_wires(op.wires)
        par = op.parameters

        if len(par[0]) != 2**len(device_wires):
            raise ValueError(
                "Unitary matrix must be of shape (2**wires, 2**wires).")

        if op.inverse:
            par[0] = par[0].conj().T

        # reverse wires (could also change par[0])
        reverse_wire_labels = device_wires.tolist()[::-1]
        unitary_gate = gate.DenseMatrix(reverse_wire_labels, par[0])
        self._circuit.add_gate(unitary_gate)
        unitary_gate.update_quantum_state(self._state)

    def _apply_matrix(self, op):
        """Apply predefined gate-matrix to state (must follow qulacs convention)"""
        # translate op wire labels to consecutive wire labels used by the device
        device_wires = self.map_wires(op.wires)
        par = op.parameters

        mapped_operation = self._operation_map[op.name]
        if op.inverse:
            mapped_operation = self._get_inverse_operation(
                mapped_operation, device_wires, par)

        if callable(mapped_operation):
            gate_matrix = mapped_operation(*par)
        else:
            gate_matrix = mapped_operation

        # gate_matrix is already in correct order => no wire-reversal needed
        dense_gate = gate.DenseMatrix(device_wires.labels, gate_matrix)
        self._circuit.add_gate(dense_gate)
        gate.DenseMatrix(device_wires.labels,
                         gate_matrix).update_quantum_state(self._state)

    def _apply_gate(self, op):
        """Apply native qulacs gate"""

        # translate op wire labels to consecutive wire labels used by the device
        device_wires = self.map_wires(op.wires)
        par = op.parameters

        mapped_operation = self._operation_map[op.name]
        if op.inverse:
            mapped_operation = self._get_inverse_operation(
                mapped_operation, device_wires, par)

        # Negating the parameters such that it adheres to qulacs
        par = np.negative(par)

        # mapped_operation is already in correct order => no wire-reversal needed
        self._circuit.add_gate(mapped_operation(*device_wires.labels, *par))
        mapped_operation(*device_wires.labels,
                         *par).update_quantum_state(self._state)

    @staticmethod
    def _get_inverse_operation(mapped_operation, device_wires, par):
        """Return the inverse of an operation"""

        if mapped_operation is None:
            return mapped_operation

        # if an inverse variant of the operation exists
        try:
            inverse_operation = getattr(gate,
                                        mapped_operation.get_name() + "dag")
        except AttributeError:
            # if the operation is hard-coded
            try:
                if callable(mapped_operation):
                    inverse_operation = np.conj(mapped_operation(*par)).T
                else:
                    inverse_operation = np.conj(mapped_operation).T

            # if mapped_operation is a qulacs.gate and np.conj is applied on it
            except TypeError:
                # else, redefine the operation as the inverse matrix
                def inverse_operation(*p):
                    # embed the gate in a unitary matrix with shape (2**wires, 2**wires)
                    g = mapped_operation(*p).get_matrix()
                    mat = reduce(np.kron, [np.eye(2)] *
                                 len(device_wires)).astype(complex)
                    mat[-len(g):, -len(g):] = g

                    # mat follows PL convention => reverse wire-order
                    reverse_wire_labels = device_wires.tolist()[::-1]
                    gate_mat = gate.DenseMatrix(reverse_wire_labels,
                                                np.conj(mat).T)
                    return gate_mat

        return inverse_operation

    def analytic_probability(self, wires=None):
        """Return the (marginal) analytic probability of each computational basis state."""
        if self._state is None:
            return None

        all_probs = self._abs(self.state)**2
        prob = self.marginal_prob(all_probs, wires)
        return prob

    def expval(self, observable):
        if self.analytic:
            qulacs_observable = Observable(self.num_wires)
            if isinstance(observable.name, list):
                observables = [
                    self._observable_map[obs] for obs in observable.name
                ]
            else:
                observables = [self._observable_map[observable.name]]

            if None not in observables:
                applied_wires = self.map_wires(observable.wires).tolist()
                opp = " ".join([
                    f"{obs} {applied_wires[i]}"
                    for i, obs in enumerate(observables)
                ])

                qulacs_observable.add_operator(1.0, opp)
                return qulacs_observable.get_expectation_value(
                    self._pre_rotated_state)

            # exact expectation value
            eigvals = self._asarray(observable.eigvals, dtype=self.R_DTYPE)
            prob = self.probability(wires=observable.wires)
            return self._dot(eigvals, prob)

        # estimate the ev
        return np.mean(self.sample(observable))

    @property
    def state(self):
        # returns the state after all operations are applied
        return _reverse_state(self._state.get_vector())

    def reset(self):
        self._state.set_zero_state()
        self._pre_rotated_state = self._state.copy()
        self._circuit = QuantumCircuit(self.num_wires)
Ejemplo n.º 23
0
def test_VqeOptimizer():
    from qulacs import ParametricQuantumCircuit
    from qulacs import QuantumState
    from qulacs import Observable
    from qulacs.gate import Probabilistic, X, Y, Z
    import numpy as np
    import matplotlib.pyplot as plt

    n_qubit = 2
    p_list = [0.05, 0.1, 0.15]
    parametric_circuit_list = \
        [ParametricQuantumCircuit(n_qubit)
         for i in range(len(p_list))]
    initial_state = QuantumState(n_qubit)

    for (p, circuit) in zip(p_list, parametric_circuit_list):
        circuit.add_H_gate(0)
        circuit.add_parametric_RY_gate(1, np.pi / 6)
        circuit.add_CNOT_gate(0, 1)
        prob = Probabilistic([p / 4, p / 4, p / 4], [X(0), Y(0), Z(0)])
        circuit.add_gate(prob)

    noiseless_circuit = ParametricQuantumCircuit(n_qubit)
    noiseless_circuit.add_H_gate(0)
    noiseless_circuit.add_parametric_RY_gate(1, np.pi / 6)
    noiseless_circuit.add_CNOT_gate(0, 1)

    n_sample_per_circuit = 1
    n_circuit_sample = 1000
    obs = Observable(n_qubit)
    obs.add_operator(1.0, "Z 0 Z 1")
    obs.add_operator(0.5, "X 0 X 1")
    initial_param = np.array([np.pi / 6])

    opt = VqeOptimizer(parametric_circuit_list,
                       initial_state,
                       obs,
                       initial_param,
                       p_list,
                       n_circuit_sample=n_circuit_sample,
                       n_sample_per_circuit=n_sample_per_circuit,
                       noiseless_circuit=noiseless_circuit)

    noisy = opt.sample_output(initial_param)
    mitigated, exp_array, _ = opt.sample_mitigated_output(initial_param,
                                                          return_full=True)
    exact = opt.exact_output(initial_param)

    print(noisy, exact)
    print(exp_array, mitigated)

    opt_param = opt.optimize()
    print(opt_param)
    theta_list = np.linspace(0, np.pi, 100)
    output_list = [opt.exact_output([theta]) for theta in theta_list]
    plt.plot(theta_list,
             output_list,
             color="black",
             linestyle="dashed",
             label="exact")
    plt.scatter(opt.parameter_history,
                opt.exp_history,
                c="blue",
                label="optimization history")
    plt.xlabel("theta")
    plt.ylabel("output")
    plt.legend()
    plt.show()
Ejemplo n.º 24
0
def cost_phf_sample_oneshot(print_level, qulacs_hamiltonianZ, qulacs_s2Z,
                            qulacs_ancZ, coef0_H, coef0_S2, kappa_list):
    """Function:
    Test function for sampling Hamiltonian and S** expectation values
    with PHF just for once.

    Author(s): Takashi Tsuchimochi

    使われてない?
    """
    t1 = time.time()

    noa = Quket.noa
    nob = Quket.nob
    nva = Quket.nva
    nvb = Quket.nvb
    n_electrons = Quket.n_electrons
    n_qubit_system = n_qubits
    n_qubits = Quket.n_qubits + 1
    anc = n_qubit_system

    state = QuantumState(n_qubits)
    circuit_rhf = set_circuit_rhfZ(n_qubits, n_electrons)
    circuit_rhf.update_quantum_state(state)
    circuit_uhf = set_circuit_uhfZ(n_qubits, noa, nob, nva, nvb, kappa_list)
    circuit_uhf.update_quantum_state(state)

    ### Set post-measurement states ####
    poststate0 = state.copy()
    poststate1 = state.copy()
    circuit0 = QuantumCircuit(n_qubits)
    circuit1 = QuantumCircuit(n_qubits)
    ### Projection to anc = 0 or anc = 1 ###
    circuit0.add_gate(P0(0))
    circuit1.add_gate(P1(0))
    circuit0.update_quantum_state(poststate0)
    circuit1.update_quantum_state(poststate1)
    ### Renormalize each state ###
    norm0 = poststate0.get_squared_norm()
    norm1 = poststate1.get_squared_norm()
    poststate0.normalize(norm0)
    poststate1.normalize(norm1)

    ### grid loop ###
    Ng = 4
    beta = [-0.861136311594053, -0.339981043584856,
             0.339981043584856,  0.861136311594053]
    wg = [0.173927422568724, 0.326072577431273,
          0.326072577431273, 0.173927422568724]
    ### a list to compute the probability to observe 0 in ancilla qubit
    p0_list = np.full(n_qubits, 2)
    p0_list[-1] = 0
    ### Array for <HUg>, <S2Ug>, <Ug>
    samplelist = [5, 50, 500, 5000, 50000, 500000, 5000000]
    Ng = 4
    ncyc = 10

    prints("", filepath="./log.txt", opentype="w")
    for i_sample in samplelist:
        sampleEn = []
        sampleS2 = []

        for icyc in range(ncyc):
            prints(f"n_sample : {i_sample}  ({icyc} / {ncyc})",
                   filepath="./log.txt")

            HUg = []
            S2Ug = []
            Ug = []
            Ephf = S2 = Norm = 0
            for i in range(Ng):
                ### Copy quantum state of UHF (cannot be done in real device) ###
                state_g = QuantumState(n_qubits)
                circuit_rhf.update_quantum_state(state_g)
                circuit_uhf.update_quantum_state(state_g)
                ### Construct Ug test
                circuit_ug = QuantumCircuit(n_qubits)
                ### Hadamard on anc
                circuit_ug.add_H_gate(anc)
                controlled_Ug(circuit_ug, n_qubits, anc, np.arccos(beta[i]))
                circuit_ug.add_H_gate(anc)
                circuit_ug.update_quantum_state(state_g)

                ### Probabilities for getting 0 and 1 in ancilla qubit ###
                p0 = state_g.get_marginal_probability(p0_list)
                p1 = 1 - p0

                ### Compute expectation value <HUg> ###
                HUg.append(sample_observable(state_g,
                                             qulacs_hamiltonianZ,
                                             i_sample).real)
                ### <S2Ug> ###
                S2Ug.append(sample_observable(state_g,
                                              qulacs_s2Z,
                                              i_sample).real)
                #S2Ug.append(qulacs_s2Z.get_expectation_value(state_g))

                #Ug.append(p0 - p1)
                Ug.append(sample_observable(state_g,
                                            qulacs_ancZ,
                                            i_sample).real)
                ### Norm accumulation ###
                Norm += wg[i]*g[i]
                sampleHUg[icyc, i] = HUg[i]
                sampleS2Ug[icyc, i] = S2Ug[i]
                sampleUg[icyc, i] = Ug[i]
            #print(f"{p0=}  {p1=}  {p0-p1=}")

            sampleHUg1.append(HUg[0])
            sampleHUg2.append(HUg[1])
            sampleHUg3.append(HUg[2])
            sampleHUg4.append(HUg[3])
            sampleS2Ug1.append(S2Ug[0])
            sampleS2Ug2.append(S2Ug[1])
            sampleS2Ug3.append(S2Ug[2])
            SAMpleS2Ug4.append(S2Ug[3])
            sampleUg1.append(Ug[0])
            sampleUg2.append(Ug[1])
            sampleUg3.append(Ug[2])
            sampleUg4.append(Ug[3])

            ### Energy calculation <HP>/<P> and <S**2P>/<P> ###
            Ephf = 0
            for i in range(Ng):
                Ephf += wg[i]*HUg[i]/Norm
                S2 += wg[i]*S2Ug[i]/Norm
            #print(f" E[PHF] = {Ephf}  <S**2> = {S2}  (Nsample = {i_sample})")
            Ephf += coef0_H
            S2 += coef0_S2
            sampleEn[icyc, 0] = Ephf
            sampleS2[icyc, 0] = S2
        #print(f"(n_sample = {i_sample}): sample HUg1\n", sampleHUg1)
        #print(f"(n_sample = {i_sample}): sample HUg2\n", sampleHUg2)
        #print(f"(n_sample = {i_sample}): sample HUg3\n", sampleHUg3)
        #print(f"(n_sample = {i_sample}): sample HUg4\n", sampleHUg4)
        #print(f"(n_sample = {i_sample}): sample S2Ug1\n", sampleS2Ug1)
        #print(f"(n_sample = {i_sample}): sample S2Ug2\n", sampleS2Ug2)
        #print(f"(n_sample = {i_sample}): sample S2Ug3\n", sampleS2Ug3)
        #print(f"(n_sample = {i_sample}): sample S2Ug4\n", sampleS2Ug4)
        #print(f"(n_sample = {i_sample}): sample Ug1\n", sampleUg1)
        #print(f"(n_sample = {i_sample}): sample Ug2\n", sampleUg2)
        #print(f"(n_sample = {i_sample}): sample Ug3\n", sampleUg3)
        #print(f"(n_sample = {i_sample}): sample Ug4\n", sampleUg4)
        #print(f"(n_sample = {i_sample}): sample HUg1\n", sampleHUg1)
        #print(f"(n_sample = {i_sample}): sample HUg2\n", sampleHUg2)
        #print(f"(n_sample = {i_sample}): sample HUg3\n", sampleHUg3)
        #print(f"(n_sample = {i_sample}): sample HUg4\n", sampleHUg4)
        #print(f"(n_sample = {i_sample}): sample En\n", sampleEn)
        #print(f"(n_sample = {i_sample}): sample S2\n", sampleS2)
        with open(f"./HUg_{i_sample}.csv", "w") as fHUg:
            writer = csv.writer(fHUg)
            writer.writerows(sampleHUg)
        with open(f"./S2Ug_{i_sample}.csv", "w") as fS2Ug:
            writer = csv.writer(fS2Ug)
            writer.writerows(sampleS2Ug)
        with open(f"./Ug_{i_sample}.csv", "w") as fUg:
            writer = csv.writer(fUg)
            writer.writerows(sampleUg)
        with open(f"./En_{i_sample}.csv", "w") as fEn:
            writer = csv.writer(fEn)
            writer.writerows(sampleEn)
        with open(f"./S2_{i_sample}.csv", "w") as fS2:
            writer = csv.writer(fS2)
            writer.writerows(sampleS2)
    return Ephf, S2
Ejemplo n.º 25
0
def test_transition_observable(state, obs, poststate0, poststate1, n_sample):
    """
    Args:
        state (qulacs.QuantumState): This includes entangled ancilla
                                     (n_qubits = n_qubit_system + 1)
        obs (qulacs.Observable): This does not include ancilla Z
                                 (n_qubit_system)
        poststate0 (qulacs.QuantumState): post-measurement state
                                          when ancilla = 0 (n_qubit_system)
        poststate1 (qulacs.QuantumState): post-measurement state
                                          when ancilla = 1 (n_qubit_system)
        n_sample (int):  number of samples for each observable

    Return:
        :float: sampled expectation value of the observable
    """
    n_term = obs.get_term_count()
    n_qubits = obs.get_qubit_count()
    p0 = state.get_zero_probability(n_qubits - 1)
    p1 = 1 - p0
    opt = f"0{n_qubits}b"

    prints(f"p0: {p0}  p1: {p1}")
    print_state(poststate0, name="post(0)")
    prints("post(1)")
    print_state(poststate1, name="post(1)")

    expH = 0
    exp = []
    coef = []
    buf_state = QuantumState(n_qubits)
    for i in range(n_term):
        pauli_term = obs.get_term(i)
        coef.append(pauli_term.get_coef().real)
        pauli_id = pauli_term.get_pauli_id_list()
        pauli_index = pauli_term.get_index_list()

        if len(pauli_id) == 0:  # means identity
            exp.extend(coef)
            continue

        buf_state.load(state)
        measurement_circuit = QuantumCircuit(n_qubits)
        mask = "".join(["1" if n_qubits - 1 - k in pauli_index else "0"
                        for k in range(n_qubits)])

        measure_observable = QubitOperator((), 1)
        #measure_observable = QubitOperator('Z%d' % n_qubits)
        for single_pauli, index in zip(pauli_id, pauli_index):
            if single_pauli == 1:
                ###  X
                measurement_circuit.add_H_gate(index)
                measure_observable *= QubitOperator(f"X{index}")
            elif single_pauli == 2:
                ###  Y
                measurement_circuit.add_Sdag_gate(index)
                measurement_circuit.add_H_gate(index)
                measure_observable *= QubitOperator(f"Y{index}")
            elif single_pauli == 3:
                ###  Z
                measure_observable *= QubitOperator(f"Z{index}")
        qulacs_measure_observable \
                = create_observable_from_openfermion_text(
                        str(measure_observable))
        ### p0 ###
        H0 = qulacs_measure_observable.get_expectation_value(poststate0)
        ### p1 ###
        H1 = qulacs_measure_observable.get_expectation_value(poststate1)
        prob = p0*H0 - p1*H1
        # print(prob, qulacs_measure_observable.get_expectation_value(state), obs.get_expectation_value(state))
        prob = qulacs_measure_observable.get_expectation_value(state)
        expH += coef[i]*prob

        # measurement_circuit.update_quantum_state(buf_state)
        # samples = buf_state.sampling(n_sample)
        # print('samples? ',format(samples[0],opt))
        # print("I = :",'%5d' % i, "  h_I ", '%10.5f' % coef[i], "    <P_I> ", '%10.5f' % exp[i])
        # mask = int(mask, 2)
        # print(sum(list(map(lambda x: (-1) **(bin(x & mask).count('1')), samples))))
        # print(coef*sum(list(map(lambda x: (-1) **
        #                             (bin(x & mask).count('1')), samples))))
        # expH += coef[i] * exp[i]
        # samples = buf_state.sampling(n_sample)

        # mask = int(mask, 2)
        # prob = sum(list(map(lambda x: (-1) **
        #                             (bin(x & mask).count('1')), samples)))/n_sample
        # measure_list = list(map(int,np.ones(n_qubits)*2))
        # for j in pauli_index:
        #    measure_list[j] = 1
        # print(qulacs_measure_observable.get_expectation_value(state))
        # expH += coef[i] * prob
        print(f"coef: {coef[i]:10.5f}  prob: {prob:10.5f}")
    return expH
Ejemplo n.º 26
0
    cu_mat[x * 2 + 1][crow // 2 * 4 + 1 - crow] = 1

m = 2**num_bits
dist_mat = np.full((m, m), .5 / m)
for x in range(m):
    dist_mat[x][x] = -1 + .5 / m

if num_bits < 6:
    print("CU Gate Matrix:")
    for i in range(2**(num_bits + 1)):
        print(''.join([str(b) for b in cu_mat[i]]))
    print("Dist Gate Matrix:")
    for i in range(2**num_bits):
        print(''.join(["{:>6.2}".format(b) for b in dist_mat[i]]))

state = QuantumState(num_bits + 1)
state.set_computational_basis(0)
x_gate = X(0)
x_gate.update_quantum_state(state)

print("\nInitial State:")
show_quantum_state(state)

for i in range(0, num_bits + 1):
    h_gate = H(i)
    h_gate.update_quantum_state(state)

print("\nAfter H Gate:")
show_quantum_state(state)

ite = int(math.pow(2., num_bits * .5))
Ejemplo n.º 27
0
def cost_ic_mrucc_spinfree(Quket, print_level, theta_list):
    """ Function

    Author(s): Yuto Mori
    """
    t1 = time.time()

    nstates = Quket.multi.nstates
    n_qubits = Quket.n_qubits
    ndim = Quket.ndim
    ndim1 = Quket.ndim1
    rho = Quket.rho
    DS = Quket.DS
    v_n, a_n, c_n = calc_num_v_a_c(Quket)

    states = []
    for istate in range(nstates):
        det = Quket.multi.states[istate]
        state = create_icmr_uccsd_state_spinfree(
            n_qubits,
            v_n,
            a_n,
            c_n,
            rho,
            DS,
            theta_list,
            det,
            ndim1,
            act2act=Quket.multi.act2act_opt,
            SpinProj=Quket.projection.SpinProj)
        states.append(state)
    H, S2, S = create_HS2S(Quket, states)

    root_invS = root_inv(S.real)
    H_ortho = root_invS.T @ H @ root_invS
    nstates0 = root_invS.shape[1]

    en, dvec = np.linalg.eig(H_ortho)
    idx = np.argsort(en.real, -1)
    en = en.real[idx]
    dvec = dvec[:, idx]
    cvec = root_invS @ dvec
    S2dig = cvec.T @ S2 @ cvec
    s2 = [S2dig[i, i].real for i in range(nstates0)]

    t2 = time.time()
    cpu1 = t2 - t1
    if print_level == 1:
        cput = t2 - cf.t_old
        cf.t_old = t2
        cf.icyc += 1
        prints(f"{cf.icyc:5d}: ", end="")
        for istate in range(nstates0):
            prints(
                f"E[{istate}] = {en[istate]:.8f}  "
                f"(<S**2> = {s2[istate]:7.5f})  ",
                end="")
        prints(f"CPU Time = {cput:5.2f}  ({cpu1:2.2f} / step)")
        SaveTheta(ndim, theta_list, cf.tmp)
        # cf.iter_threshold = 0
    if print_level > 1:
        cput = t2 - cf.t_old
        cf.t_old = t2
        prints("Final: ", end="")
        for istate in range(nstates0):
            prints(
                f"E[{istate}] = {en[istate]:.8f}  "
                f"(<S**2> = {s2[istate]:7.5f})  ",
                end="")
        prints(f"CPU Time = {cput:5.2f}  ({cpu1:2.2f} / step)\n")
        prints("------------------------------------")
        for istate in range(nstates):
            prints(f"ic Basis   {istate}")
            print_state(states[istate])
            prints("")
        printmat(cvec.real, name="Coefficients: ")
        prints("------------------------------------\n\n")
        prints("###############################################")
        prints("#                  ic states                  #")
        prints("###############################################", end="")

        for istate in range(nstates0):
            prints("")
            prints(f"State         : {istate}")
            prints(f"E             : {en[istate]:.8f}")
            prints(f"<S**2>        : {s2[istate]:.5f}")
            prints(f"Superposition : ")
            spstate = QuantumState(n_qubits)
            spstate.multiply_coef(0)
            for jstate in range(nstates0):
                state = states[jstate].copy()
                coef = cvec[jstate, istate]
                state.multiply_coef(coef)
                spstate.add_state(state)
            print_state(spstate)
        prints("###############################################")
    cost = np.sum(Quket.multi.weights * en)
    norm = np.sum(Quket.multi.weights)
    cost /= norm
    return cost, s2
Ejemplo n.º 28
0
        return y_dict[x]

    fx_type = 'balanced'

cu_mat = np.zeros((2**(num_bits + 1), 2**(num_bits + 1)), np.int8)
for x in range(2**num_bits):
    crow = x * 2 + f(x)
    cu_mat[x * 2][crow] = 1
    cu_mat[x * 2 + 1][crow // 2 * 4 + 1 - crow] = 1

if num_bits < 6:
    print("CU Gate Matrix:")
    for i in range(2**(num_bits + 1)):
        print(''.join([str(b) for b in cu_mat[i]]))

state = QuantumState(num_bits + 1)
state.set_computational_basis(0)

print("\nInitial State:")
show_quantum_state(state)

for i in range(1, num_bits + 1):
    h_gate = H(i)
    h_gate.update_quantum_state(state)

print("\nAfter H Gate:")
show_quantum_state(state)

cu_gate = DenseMatrix(tuple(range(num_bits + 1)), cu_mat)
cu_gate.update_quantum_state(state)
Ejemplo n.º 29
0
def adaptive_sample_observable(state, obs, n_sample):
    """
    Args:
        state (qulacs.QuantumState):
        obs (qulacs.Observable)
        n_sample (int):  number of samples for each observable
    Return:
        :float: sampled expectation value of the observable
    """
    n_term = obs.get_term_count()
    n_qubits = obs.get_qubit_count()

    exp = 0
    buf_state = QuantumState(n_qubits)

    ### check the coefficients for each term...
    coef_list = np.array([abs(obs.get_term(i).get_coef())
                          for i in range(n_term)])
    sum_coef = np.sum(coef_list)

    ### sort
    sorted_indices = np.argsort(-coef_list)
    coef_list.sort()
    #sorted_coef_list = [coef_list[i] for i in sorted_indices]
    ### determine sampling wight
    n_sample_total = n_sample*n_term
    n_sample_list = n_sample_total*coef_list//sum_coef
    n_count = np.sum(n_sample_list)
    n_rest = n_sample_total - n_count
    n_sample_list[sorted_indices[:n_rest]] += 1

    j = 0
    for i in range(n_term):
        if n_sample_list[i] == 0:
            continue
        j += n_sample_list[i]

        pauli_term = obs.get_term(i)
        coef = pauli_term.get_coef()
        pauli_id = pauli_term.get_pauli_id_list()
        pauli_index = pauli_term.get_index_list()

        if len(pauli_id) == 0:  # means identity
            exp += coef
            continue

        buf_state.load(state)
        measurement_circuit = QuantumCircuit(n_qubits)
        mask = "".join(["1" if n_qubits - 1 - k in pauli_index else "0"
                        for k in range(n_qubits)])
        for single_pauli, index in zip(pauli_id, pauli_index):
            if single_pauli == 1:
                measurement_circuit.add_H_gate(index)
            elif single_pauli == 2:
                measurement_circuit.add_Sdag_gate(index)
                measurement_circuit.add_H_gate(index)
        measurement_circuit.update_quantum_state(buf_state)
        samples = buf_state.sampling(n_sample_list[i])
        mask = int(mask, 2)
        exp += (coef
                *sum(list(map(lambda x: (-1)**(bin(x & mask).count("1")),
                              samples)))
                /n_sample_list[i])
    return exp
Ejemplo n.º 30
0
    def test_circuit_add_parametric_gate(self):
        from qulacs import ParametricQuantumCircuit, QuantumState
        from qulacs.gate import Identity, X, Y, Z, H, S, Sdag, T, Tdag, sqrtX, sqrtXdag, sqrtY, sqrtYdag
        from qulacs.gate import P0, P1, U1, U2, U3, RX, RY, RZ, CNOT, CZ, SWAP, TOFFOLI, FREDKIN, Pauli, PauliRotation
        from qulacs.gate import DenseMatrix, SparseMatrix, DiagonalMatrix, RandomUnitary, ReversibleBoolean, StateReflection
        from qulacs.gate import BitFlipNoise, DephasingNoise, IndependentXZNoise, DepolarizingNoise, TwoQubitDepolarizingNoise, AmplitudeDampingNoise, Measurement
        from qulacs.gate import merge, add, to_matrix_gate, Probabilistic, CPTP, Instrument, Adaptive
        from qulacs.gate import ParametricRX, ParametricRY, ParametricRZ, ParametricPauliRotation
        from scipy.sparse import lil_matrix
        qc = ParametricQuantumCircuit(3)
        qs = QuantumState(3)
        ref = QuantumState(3)
        sparse_mat = lil_matrix((4, 4))
        sparse_mat[0, 0] = 1
        sparse_mat[1, 1] = 1

        def func(v, d):
            return (v + 1) % d

        def adap(v):
            return True

        gates = [
            Identity(0), X(0), Y(0), Z(0), H(0), S(0), Sdag(0), T(0), Tdag(0), sqrtX(0), sqrtXdag(0), sqrtY(0), sqrtYdag(0),
            Probabilistic([0.5, 0.5], [X(0), Y(0)]), CPTP([P0(0), P1(0)]), Instrument([P0(0), P1(0)], 1), Adaptive(X(0), adap),
            CNOT(0, 1), CZ(0, 1), SWAP(0, 1), TOFFOLI(0, 1, 2), FREDKIN(0, 1, 2), Pauli([0, 1], [1, 2]), PauliRotation([0, 1], [1, 2], 0.1),
            DenseMatrix(0, np.eye(2)), DenseMatrix([0, 1], np.eye(4)), SparseMatrix([0, 1], sparse_mat),
            DiagonalMatrix([0, 1], np.ones(4)), RandomUnitary([0, 1]), ReversibleBoolean([0, 1], func), StateReflection(ref),
            BitFlipNoise(0, 0.1), DephasingNoise(0, 0.1), IndependentXZNoise(0, 0.1), DepolarizingNoise(0, 0.1), TwoQubitDepolarizingNoise(0, 1, 0.1),
            AmplitudeDampingNoise(0, 0.1), Measurement(0, 1), merge(X(0), Y(1)), add(X(0), Y(1)), to_matrix_gate(X(0)),
            P0(0), P1(0), U1(0, 0.), U2(0, 0., 0.), U3(0, 0., 0., 0.), RX(0, 0.), RY(0, 0.), RZ(0, 0.),
        ]

        gates.append(merge(gates[0], gates[1]))
        gates.append(add(gates[0], gates[1]))

        parametric_gates = [
            ParametricRX(0, 0.1), ParametricRY(0, 0.1), ParametricRZ(0, 0.1), ParametricPauliRotation([0, 1], [1, 1], 0.1)
        ]

        ref = None
        for gate in gates:
            qc.add_gate(gate)

        for gate in gates:
            qc.add_gate(gate)

        for pgate in parametric_gates:
            qc.add_parametric_gate(pgate)

        for pgate in parametric_gates:
            qc.add_parametric_gate(pgate)

        qc.update_quantum_state(qs)
        qc = None
        qs = None
        for gate in gates:
            gate = None
        for pgate in parametric_gates:
            gate = None

        gates = None
        parametric_gates = None