def test_ffft_1mode_error(self): eng = MainEngine() reg = eng.allocate_qureg(1) with self.assertRaises(ValueError): ffft(eng, reg, 1)
from projectq.ops import H, Measure,StatePreparation from projectq import MainEngine import numpy as np from qutip import Bloch #Intialization ME = MainEngine() #Input x,y = map(complex,input("enter the state: ").split()) #Normalization norm = np.sqrt(np.abs(x**2) + np.abs(y**2)) x /= norm y /= norm #Qubit allocation , define a state for the qubit,and measure it. qubit = ME.allocate_qubit() StatePreparation([x,y]) | qubit Measure | qubit read = int(qubit) #Measuring output ME.flush() print(read) #State vector to sphereical coordinates phi = np.angle(y) - np.angle(x)
def setUp(self): self.eng = MainEngine() self.reg = self.eng.allocate_qureg(3)
def main_engine(): return MainEngine(backend=DummyEngine(), engine_list=[DummyEngine()])
# written by Ryan LaRose <*****@*****.**> # at Michigan State University September 2018. """ # ============================================================================= # imports # ============================================================================= from projectq import MainEngine import projectq.ops as ops # ============================================================================= # declare an engine and get some qubits # ============================================================================= eng = MainEngine() qbits = eng.allocate_qureg(1) # ============================================================================= # define a custom one-qubit gate # ============================================================================= class MyGate(ops.BasicGate): """Custom one-qubit gate defined via matrix elements.""" def __str__(self): return "my_gate" @property def matrix(self): """Defines the gate in terms of it's matrix elements.""" return ops.np.matrix([[0, 1], [-1j, 0]])
import os from pathlib import Path import projectq.setups.ibm # Imports the default compiler to map to IBM QE from dotenv import load_dotenv from projectq.backends import IBMBackend from projectq.ops import All, Entangle, Measure from projectq import MainEngine try: current_path = Path('.') / '.env' load_dotenv(current_path) token = os.environ['IBM_QUANTUM_API_KEY'] device = device = 'ibmq_rome' compiler_engines = projectq.setups.ibm.get_engine_list(token=token, device=device) engine = MainEngine(IBMBackend(token=token, use_hardware=True, num_runs=1024, verbose=True, device=device), engine_list=compiler_engines) qureg = engine.allocate_qureg(3) Entangle | qureg All(Measure) | qureg engine.flush() print([int(q) for q in qureg]) except KeyError: print("Please define the environment variables: IBM_QUANTUM_API_KEY")
def main(argv=None): # Store results to this CSV file file = open('projectq_out.csv', 'w') file.write('theta, Z0_pq, Z0_tnqvm\n') #, Z1, Z0Z1\n') # Initialize XACC xacc.Initialize() # Indicate that we want to use the ProjectQ QASM # Compiler/Transpiler xacc.setOption('compiler', 'projectq-qasm') # Get reference to the TNQVM Accelerator tnqvm = xacc.getAccelerator('tnqvm') # Allocate and AcceleratorBuffer xacc_qbits = tnqvm.createBuffer('qreg', 2) # Loop over H2 state prep variational parameters for theta in np.linspace(-np.pi, np.pi, 100): # Create a ProjectQ Engine with our CommandPrinter output = StringIO.StringIO() eng = MainEngine(Simulator(), [XaccCommandPrinter(output)]) # Allocate some ProjectQ qubits qreg = eng.allocate_qureg(2) # Run Init State Circuit and Generate the Z0 QubitOperator op = Z0Term(qreg, theta) eng.flush() # Get Expectation Value of Z0 operator e_pq = eng.backend.get_expectation_value(op, qreg) Measure | qreg[0] # Get the ProjectQ QASM qasm = output.getvalue() # Generate an XACC Kernel xaccKernel = getXACCKernel(qasm, tnqvm) # Execute, no params since theta has # already been input to Z0Term function xaccKernel.execute(xacc_qbits, []) # Get the expectation value e_tnqvm = xacc_qbits.getExpectationValueZ() # Reset the qubits for the next iteration xacc_qbits.resetBuffer() # Store the results to a CSV file file.write(str(theta) + ', ' + str(e_pq) + ', ' + str(e_tnqvm) + '\n') file.flush() file.close() # Finalize the framework xacc.Finalize()
def run_circuit(self, circuit): """Run a circuit and return a single Result. Args: circuit (QobjExperiment): Qobj experiment Returns: dict: A dictionary of results which looks something like: { "data": { #### DATA CAN BE A DIFFERENT DICTIONARY FOR EACH BACKEND #### "counts": {'00000': XXXX, '00001': XXXXX}, "time" : xx.xxxxxxxx }, "status": --status (string)-- } Raises: ProjectQSimulatorError: if an error occurred. """ # pylint: disable=expression-not-assigned,pointless-statement self._number_of_qubits = circuit.config.n_qubits self._number_of_clbits = circuit.config.memory_slots self._classical_state = 0 cl_reg_index = [] # starting bit index of classical register cl_reg_nbits = [] # number of bits in classical register clbit_index = 0 qobj_quregs = OrderedDict( _get_register_specs(circuit.header.qubit_labels)) eng = MainEngine(backend=self._sim) for cl_reg in circuit.header.clbit_labels: cl_reg_nbits.append(cl_reg[1]) cl_reg_index.append(clbit_index) clbit_index += cl_reg[1] # let circuit seed override qobj default if hasattr(circuit, 'config'): if hasattr(circuit.config, 'seed'): if circuit.config.seed is not None: self._sim._simulator = CppSim(circuit.config.seed) outcomes = [] snapshots = {} projq_qureg_dict = OrderedDict(((key, eng.allocate_qureg(size)) for key, size in qobj_quregs.items())) if self._shots > 1: ground_state = np.zeros(1 << self._number_of_qubits, dtype=complex) ground_state[0] = 1 start = time.time() for i in range(self._shots): # initialize starting state self._classical_state = 0 qureg = [ qubit for sublist in projq_qureg_dict.values() for qubit in sublist ] if i > 0: eng.flush() eng.backend.set_wavefunction(ground_state, qureg) # Do each operation in this shot for operation in circuit.instructions: if hasattr(operation, 'conditional'): mask = int(operation.conditional.mask, 16) if mask > 0: value = self._classical_state & mask while (mask & 0x1) == 0: mask >>= 1 value >>= 1 if value != int(operation.conditional.val, 16): continue # Check if single gate if operation.name in ['U', 'u3']: params = operation.params qubit = qureg[operation.qubits[0]] Rz(params[2]) | qubit Ry(params[0]) | qubit Rz(params[1]) | qubit elif operation.name in ['u1']: params = operation.params qubit = qureg[operation.qubits[0]] Rz(params[0]) | qubit elif operation.name in ['u2']: params = operation.params qubit = qureg[operation.qubits[0]] Rz(params[1] - np.pi / 2) | qubit Rx(np.pi / 2) | qubit Rz(params[0] + np.pi / 2) | qubit elif operation.name == 't': qubit = qureg[operation.qubits[0]] T | qubit elif operation.name == 'h': qubit = qureg[operation.qubits[0]] H | qubit elif operation.name == 's': qubit = qureg[operation.qubits[0]] S | qubit elif operation.name in ['CX', 'cx']: qubit0 = qureg[operation.qubits[0]] qubit1 = qureg[operation.qubits[1]] CX | (qubit0, qubit1) elif operation.name in ['id', 'u0']: pass # Check if measure elif operation.name == 'measure': qubit_index = operation.qubits[0] qubit = qureg[qubit_index] clbit = operation.memory[0] Measure | qubit bit = 1 << clbit self._classical_state = (self._classical_state & (~bit)) | (int(qubit) << clbit) # Check if reset elif operation.name == 'reset': qubit = operation.qubits[0] raise ProjectQSimulatorError( 'Reset operation not yet implemented ' 'for ProjectQ C++ backend') # Check if snapshot elif operation.name == 'snapshot': eng.flush() location = str(operation.params[0]) statevector = np.array(eng.backend.cheat()[1], dtype=complex) formatted_state = [[x.real, x.imag] for x in statevector] if location in snapshots: snapshots[location]['statevector'].append( formatted_state) else: snapshots[location] = { 'statevector': [formatted_state] } elif operation.name == 'barrier': pass else: backend = self._configuration.backend_name err_msg = '{0} encountered unrecognized operation "{1}"' raise ProjectQSimulatorError( err_msg.format(backend, operation.name)) # Before the program terminates, all the qubits must be measured, # including those that have not been measured by the circuit. # Otherwise ProjectQ throws an exception about qubits in superposition. for ind in list(range(self._number_of_qubits)): qubit = qureg[ind] Measure | qubit eng.flush() # Turn classical_state (int) into bit string state = format(self._classical_state, 'b') outcomes.append(state.zfill(self._number_of_clbits)) # Return the results counts = dict(Counter(outcomes)) data = {'counts': _format_result(counts, cl_reg_nbits)} if snapshots != {}: data['snapshots'] = snapshots if self._shots == 1: data['classical_state'] = self._classical_state end = time.time() # Calculate creg_sizes pre_creg_sizes = {} for clbit_label in circuit.header.clbit_labels: if clbit_label[0] in pre_creg_sizes: pre_creg_sizes[clbit_label[0]] += 1 else: pre_creg_sizes[clbit_label[0]] = 1 creg_sizes = [] for clbit_label in pre_creg_sizes: creg_sizes.append([clbit_label, pre_creg_sizes[clbit_label]]) return { 'header': { 'name': circuit.header.name, 'memory_slots': circuit.header.memory_slots, 'creg_sizes': creg_sizes }, 'seed': self._seed, 'shots': self._shots, 'data': data, 'status': 'DONE', 'success': True, 'time_taken': (end - start) }
def predict_data(data, probs, count=100): quantum_engine = MainEngine() print("Data") print(data) print("Probs") print(probs) print("Sending ===>") rx = [] ry = [] count = 10 for i in range(count): percent = (i / count) * 100 if percent % count / count == 0: print("{0}% Completed...".format(percent)) #w = np.random.choice(data) w = np.random.choice( data, 1, p=probs)[0] # record the values for comparison with predicted rx.append( send_full_message(message=w, quantum_engine=quantum_engine).split(",")[0]) ry.append( send_full_message(message=w, quantum_engine=quantum_engine).split(",")[1]) # prep the data to learn on it... # ["A,B","B,D","B,C"], sent from this # dataset at random from alice... # the resulting dataset that is generated # is a 2D dictionary that contains the # words as the keys and the counts as the # values. First level is the label, the second # is the word and the occurances of that combination learn = {} for i in range(len(rx)): for j in range(len(rx)): if i == j: if rx[i] in learn.keys(): if ry[j] in learn[rx[i]].keys(): learn[rx[i]][ry[j]] += 1 else: learn[rx[i]][ry[j]] = 1 else: learn[rx[i]] = {ry[j]: 1} print("Recieved <===") print("Collected Data:") print(learn) # calculate the probs for each "event" that occurs fl_k = learn.keys() for fk in fl_k: sl_k = learn[fk].keys() for sk in sl_k: learn[fk][sk] = learn[fk][sk] / count # predict the word based on a random word that alice decides to send to bob w_predict = send_full_message(message=np.random.choice(list(learn.keys())), quantum_engine=quantum_engine) prob_dict = learn[w_predict] print("Probabilities:") print(prob_dict) print("Prediction on word: {0} results in expected word: {1}".format( w_predict, np.random.choice(list(prob_dict.keys()), 1, p=list(prob_dict.values()))))
Returns: measurement (list<int>): List of measurement outcomes. """ # allocate the quantum register to entangle qureg = eng.allocate_qureg(num_qubits) # entangle the qureg Entangle | qureg # measure; should be all-0 or all-1 Measure | qureg # run the circuit eng.flush() # access the probabilities via the back-end: results = eng.backend.get_probabilities(qureg) for state in results: print("Measured {} with p = {}.".format(state, results[state])) # return one (random) measurement outcome. return [int(q) for q in qureg] if __name__ == "__main__": # create main compiler engine for the IBM back-end eng = MainEngine(IBMBackend(use_hardware=True, num_runs=1024, verbose=False, device='ibmqx4')) # run the circuit and print the result print(run_entangle(eng))