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
def test_pointer_del(self): from qulacs import QuantumCircuit from qulacs.gate import X qc = QuantumCircuit(1) gate = X(0) qc.add_gate(gate) del gate del qc
def test_add_gate(self): from qulacs import QuantumCircuit from qulacs.gate import X circuit = QuantumCircuit(1) gate = X(0) circuit.add_gate(gate) del gate s = circuit.to_string() del circuit
def set_circuit_rhf(n_qubit_system, n_electrons): """Function: Construct circuit for RHF |0000...1111> Author(s): Yuto Mori """ circuit = QuantumCircuit(n_qubit_system) for i in range(n_electrons): circuit.add_X_gate(i) return circuit
def set_circuit_rhfZ(n_qubits, n_electrons): """Function: Construct circuit for RHF |0000...1111> with one ancilla Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubits) for i in range(n_electrons): circuit.add_X_gate(i) return circuit
def tk_to_qulacs(circuit: Circuit) -> QuantumCircuit: """ Convert a pytket circuit to a qulacs circuit object. """ qulacs_circ = QuantumCircuit(circuit.n_qubits) for com in circuit: optype = com.op.type if optype in _IBM_GATES: qulacs_gate = _IBM_GATES[optype] index = com.qubits[0].index[0] if optype == OpType.U1: param = com.op.params[0] add_gate = qulacs_gate(index, param * np.pi) elif optype == OpType.U2: param0, param1 = com.op.params add_gate = qulacs_gate(index, param0 * np.pi, param1 * np.pi) elif optype == OpType.U3: param0, param1, param2 = com.op.params add_gate = qulacs_gate(index, param0 * np.pi, param1 * np.pi, param2 * np.pi) elif optype in _ONE_QUBIT_GATES: qulacs_gate = _ONE_QUBIT_GATES[optype] index = com.qubits[0].index[0] add_gate = qulacs_gate(index) elif optype in _ONE_QUBIT_ROTATIONS: qulacs_gate = _ONE_QUBIT_ROTATIONS[optype] index = com.qubits[0].index[0] param = com.op.params[0] * np.pi add_gate = qulacs_gate(index, -param) # parameter negated for qulacs elif optype in _TWO_QUBIT_GATES: qulacs_gate = _TWO_QUBIT_GATES[optype] id1 = com.qubits[0].index[0] id2 = com.qubits[1].index[0] add_gate = qulacs_gate(id1, id2) elif optype in _MEASURE_GATES: continue # gate = _MEASURE_GATES[optype] # qubit = com.qubits[0].index[0] # bit = com.bits[0].index[0] # add_gate = (gate(qubit, bit)) elif optype == OpType.Barrier: continue else: raise NotImplementedError( "Gate: {} Not Implemented in Qulacs!".format(optype)) qulacs_circ.add_gate(add_gate) return qulacs_circ
def _simulate_on_qulacs( self, data: _StateAndBuffer, shape: tuple, qulacs_state: qulacs.QuantumState, qulacs_circuit: qulacs.QuantumCircuit, ) -> None: data.buffer = data.state cirq_state = np.array(data.state).flatten().astype(np.complex64) qulacs_state.load(cirq_state) qulacs_circuit.update_quantum_state(qulacs_state) data.state = qulacs_state.get_vector().reshape(shape)
def time_evolution_operator(n_qubits, a_idx, t, hamiltonian, n_trotter_step): circuit = QuantumCircuit(n_qubits) n_terms = hamiltonian.get_term_count() for _ in range(n_trotter_step): for i in range(n_terms): pauli_term = hamiltonian.get_term(i) c = pauli_term.get_coef() pauli_ids = pauli_term.get_pauli_id_list() pauli_indices = pauli_term.get_index_list() param = -c * t / n_trotter_step circuit.add_multi_Pauli_rotation_gate(pauli_indices, pauli_ids, angle) return circuit
def set_circuit_bcs(ansatz, n_qubits, n_orbitals, ndim1, ndim, theta_list, k): circuit = QuantumCircuit(n_qubits) target_list = np.empty(2) pauli_index = np.empty(2) for i in range(k): ioff = i * ndim for p in range(n_orbitals): pa = 2 * p pb = 2 * p + 1 target_list = pa, pb pauli_index = 1, 2 gate = PauliRotation(target_list, pauli_index, -theta_list[p + ioff]) circuit.add_gate(gate) pauli_index = 2, 1 gate = PauliRotation(target_list, pauli_index, -theta_list[p + ioff]) circuit.add_gate(gate) if "ebcs" in ansatz: if p < n_orbitals - 1: circuit.add_CNOT_gate(pa, pa + 2) circuit.add_CNOT_gate(pb, pb + 2) upcc_Gsingles(circuit, n_orbitals, theta_list, ndim1, n_orbitals, i) return circuit
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 qtest(angle): state = QuantumState(3) state.set_Haar_random_state() circuit = QuantumCircuit(3) circuit.add_X_gate(0) merged_gate = merge(CNOT(0, 1), Y(1)) circuit.add_gate(merged_gate) circuit.add_RX_gate(1, angle) circuit.update_quantum_state(state) observable = Observable(3) observable.add_operator(2.0, "X 2 Y 1 Z 0") observable.add_operator(-3.0, "Z 2") result = observable.get_expectation_value(state) output = {'energy': result} return (output)
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 exp_iHt(H, t, n_qubits=None): """ ハミルトニアンH = sum_i h[i] に対して、一次のTrotter近似 Exp[-iHt] ~ Prod_i Exp[-i h[i] t] を行う量子回路を生成する 使われてない? """ nterms = H.get_term_count() if n_qubits is None: n_qubits = H.get_qubit_count() circuit = QuantumCircuit(n_qubits) for i in nterms: h = H.get_term(i) circuit.add_gate(exp_iht(h, t)) return circuit
def set_circuit_uhf(n_qubit_system, noa, nob, nva, nvb, kappa_list): """Function: Construct circuit for UHF by orbital rotation Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubit_system) ucc_singles(circuit, noa, nob, nva, nvb, kappa_list) return circuit
def create_input_gate(self, x): # 単一のxをエンコードするゲートを作成する関数 # xは入力特徴量(2次元) # xの要素は[-1, 1]の範囲内 u = QuantumCircuit(self.nqubit) angle_y = np.arcsin(x) angle_z = np.arccos(x**2) for i in range(self.nqubit): if i % 2 == 0: u.add_RY_gate(i, angle_y[0]) u.add_RZ_gate(i, angle_z[0]) else: u.add_RY_gate(i, angle_y[1]) u.add_RZ_gate(i, angle_z[1]) return u
def set_circuit_uccd(n_qubits, noa, nob, nva, nvb, theta_list): """Function: Construct new circuit for UCCD Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubits) ucc_doubles(circuit, noa, nob, nva, nvb, theta_list) return circuit
def set_circuit_ghfZ(n_qubits, no, nv, theta_list): """Function: Construct circuit for GHF with one ancilla Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubits) ucc_singles_g(circuit, no, nv, theta_list) return circuit
def set_circuit_GS(n_qubit_system, noa, nob, nva, nvb, theta1): """Function: Construct new circuit for generalized singles, prod_pq exp[theta (p!q - q!p )] Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubit_system) ucc_Gsingles(circuit, norbs, theta1) return circuit
def set_circuit_occrot(n_qubit_system, noa, nob, nva, nvb, theta1): """Function: Construct new circuit for occ-occ rotation, prod_ij exp[theta (i!j - j!i )] Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubit_system) ucc_occrot(circuit, noa, nob, nva, nvb, theta1) return circuit
def set_circuit_sauccd(n_qubits, no, nv, theta_list): """Function: Construct new circuit for spin-adapted UCCD Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubits) ucc_doubles_spinfree1(circuit, no, no, nv, nv, theta_list, 0) return circuit
def sample_observable(state, obs, n_sample): """Function Args: state (qulacs.QuantumState): obs (qulacs.Observable) 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() exp = 0 buf_state = QuantumState(n_qubits) for i in range(n_term): 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) mask = int(mask, 2) exp += (coef *sum(list(map(lambda x: (-1)**(bin(x & mask).count("1")), samples))) /n_sample) return exp
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)
def make_gate(n, index, pauli_id): """ゲートを作る関数""" circuit = QuantumCircuit(n) for i in range(len(index)): gate_number = index[i] if pauli_id[i] == 1: circuit.add_X_gate(gate_number) elif pauli_id[i] == 2: circuit.add_Y_gate(gate_number) elif pauli_id[i] == 3: circuit.add_Z_gate(gate_number) return circuit
def 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_qubit = obs.get_qubit_count() pauli_terms = [obs.get_term(i) for i in range(n_term)] coefs = [p.get_coef() for p in pauli_terms] pauli_ids = [p.get_pauli_id_list() for p in pauli_terms] pauli_indices = [p.get_index_list() for p in pauli_terms] exp = 0 measured_state = state.copy() for i in range(n_term): state.load(measured_state) measurement_circuit = QuantumCircuit(n_qubit) if len(pauli_ids[i]) == 0: # means identity exp += coefs[i] continue mask = ''.join([ '1' if n_qubit - 1 - k in pauli_indices[i] else '0' for k in range(n_qubit) ]) for single_pauli, index in zip(pauli_ids[i], pauli_indices[i]): 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(state) samples = state.sampling(n_sample) mask = int(mask, 2) exp += coefs[i] * sum( list(map(lambda x: (-1)**(bin(x & mask).count('1')), samples))) / n_sample return exp
def build_circuit(nqubits, depth, pairs): circuit = QuantumCircuit(nqubits) first_rotation(circuit, nqubits) entangler(circuit, nqubits, pairs) for k in range(depth): mid_rotation(circuit, nqubits) entangler(circuit, nqubits, pairs) last_rotation(circuit, nqubits) return circuit
def sample_observable_noisy_circuit(circuit, initial_state, obs, n_circuit_sample=1000, n_sample_per_circuit=1): """ Args: circuit (:class:`qulacs.QuantumCircuit`) initial_state (:class:`qulacs.QuantumState`) obs (:class:`qulacs.Observable`) n_circuit_sample (:class:`int`): number of circuit samples n_sample (:class:`int`): number of samples per one circuit samples Return: :float: sampled expectation value of the observable """ n_term = obs.get_term_count() n_qubit = obs.get_qubit_count() pauli_terms = [obs.get_term(i) for i in range(n_term)] coefs = [p.get_coef() for p in pauli_terms] pauli_ids = [p.get_pauli_id_list() for p in pauli_terms] pauli_indices = [p.get_index_list() for p in pauli_terms] exp = 0 state = initial_state.copy() for c in range(n_circuit_sample): state.load(initial_state) circuit.update_quantum_state(state) for i in range(n_term): measurement_circuit = QuantumCircuit(n_qubit) if len(pauli_ids[i]) == 0: # means identity exp += coefs[i] continue mask = ''.join([ '1' if n_qubit - 1 - k in pauli_indices[i] else '0' for k in range(n_qubit) ]) for single_pauli, index in zip(pauli_ids[i], pauli_indices[i]): if single_pauli == 1: measurement_circuit.add_H_gate(index) elif single_pauli == 2: measurement_circuit.add_Sdag_gate(index) uncompute_circuit.add_H_gate(index) measurement_circuit.update_quantum_state(state) samples = state.sampling(n_sample_per_circuit) mask = int(mask, 2) exp += coefs[i] * sum( list(map(lambda x: (-1)**(bin(x & mask).count('1')), samples))) / n_sample_per_circuit exp /= n_circuit_sample return exp
def test_reset(self, tol): """Test the reset() function.""" dev = QulacsDevice(4) state = np.array((0, 1, 0, 1)) op = qml.BasisState(state, wires=[0, 1, 2, 3]) dev.apply([op]) dev.reset() expected = [0.0] * 16 expected[0] = 1.0 assert np.allclose(dev._state.get_vector(), expected) assert QuantumCircuit(4).calculate_depth() == 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
def set_circuit_ghf(n_qubit_system, kappa_list): """Function: Construct circuit for GHF by general spin orbital rotation Author(s): Takashi Tsuchimochi """ circuit = QuantumCircuit(n_qubit_system) pq = 0 for p in range(n_qubit_system): for q in range(p): single_ope_Pauli(p, q, circuit, kappa_list[pq]) pq += 1 return circuit
def test_circuit_add_gate(self): from qulacs import QuantumCircuit, 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 scipy.sparse import lil_matrix qc = QuantumCircuit(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])) ref = None for gate in gates: qc.add_gate(gate) for gate in gates: qc.add_gate(gate) qc.update_quantum_state(qs) qc = None qs = None for gate in gates: gate = None gates = None parametric_gates = None