def runVqeGradientDescent(gradientStrategy): # Get access to the desired QPU and # allocate some qubits to run on qpu = xacc.getAccelerator('qpp') # Construct the Hamiltonian as an XACC PauliOperator ham = xacc.getObservable('pauli', '1.0 Y0') # Ansatz circuit: xacc.qasm('''.compiler xasm .circuit ansatz .qbit q .parameters t0, t1, t2, t3 // State-prep Ry(q[0], pi/4); Ry(q[1], pi/3); Ry(q[2], pi/7); // Parametrized gates (layer 1) Rz(q[0], t0); Rz(q[1], t1); CX(q[0], q[1]); CX(q[1], q[2]); // Parametrized gates (layer 2) Ry(q[1], t2); Rx(q[2], t3); CX(q[0], q[1]); CX(q[1], q[2]); ''') # We need 4 qubits buffer = xacc.qalloc(4) ansatz_circuit = xacc.getCompiled('ansatz') initParams = [0.432, -0.123, 0.543, 0.233] opt = xacc.getOptimizer( 'mlpack', { # Using gradient descent: 'mlpack-optimizer': 'gd', 'initial-parameters': initParams, 'mlpack-step-size': 0.01, 'mlpack-max-iter': 200 }) # Create the VQE algorithm with the requested gradient strategy vqe = xacc.getAlgorithm( 'vqe', { 'ansatz': ansatz_circuit, 'accelerator': qpu, 'observable': ham, 'optimizer': opt, 'gradient_strategy': gradientStrategy }) vqe.execute(buffer) energies = buffer.getInformation('params-energy') return energies
def execute(self, inputParams): xacc_opts = inputParams['XACC'] acc_name = xacc_opts['accelerator'] if 'verbose' in xacc_opts and xacc_opts['verbose']: xacc.set_verbose(True) if 'Benchmark' not in inputParams: xacc.error( 'Invalid benchmark input - must have Benchmark description') if 'Circuit' not in inputParams: xacc.error( 'Invalid benchmark input - must have circuit description') self.qpu = xacc.getAccelerator(acc_name, xacc_opts) if 'Decorators' in inputParams: if 'readout_error' in inputParams['Decorators']: qpu = xacc.getAcceleratorDecorator('ro-error', qpu) provider = xacc.getIRProvider('quantum') if 'source' in inputParams['Circuit']: # here assume this is xasm always src = inputParams['Circuit']['source'] xacc.qasm(src) # get the name of the circuit circuit_name = None for l in src.split('\n'): if '.circuit' in l: circuit_name = l.split(' ')[1] self.circuit_name = circuit_name ansatz = xacc.getCompiled(circuit_name) opts = {'circuit': ansatz, 'accelerator': self.qpu} if 'qubit-map' in inputParams['Circuit']: raw_qbit_map = inputParams['Circuit']['qubit-map'] if not isinstance(raw_qbit_map, list): raw_qbit_map = ast.literal_eval(raw_qbit_map) self.qubit_map = raw_qbit_map opts['qubit-map'] = self.qubit_map self.qpt = xacc.getAlgorithm('qpt', opts) self.nq = ansatz.nLogicalBits() buffer = xacc.qalloc(ansatz.nLogicalBits()) self.qpt.execute(buffer) return buffer
def setUpClass(self): print('setting up class') self.process = subprocess.Popen([ sys.executable, CURRENT_TEST_DIR + '/qcs_integration_mock_servers.py', CURRENT_TEST_DIR ]) time.sleep(2) forest_url = 'http://localhost:64574' engagement_url = forest_url compiler_url = forest_url try: self.qpu = xacc.getAccelerator( 'qcs:FakeAspen-8', { 'shots': 500, 'auth_token': 'user-fake-auth', 'forest_server_url': forest_url, 'engagement_url': engagement_url, 'qpu_compiler_url': compiler_url, 'use_rpcq_auth_config': False }) except: print('Failure in setup - shutting down the server') requests.post("http://localhost:64574/shutdown") time.sleep(2) xacc.qasm('''.compiler xasm .circuit super .parameters t0 .qbit q H(q[0]); Measure(q[0]); ''') self.super = xacc.getCompiled('super') xacc.qasm('''.compiler xasm .circuit bell .parameters t0 .qbit q H(q[0]); CX(q[0], q[1]); Measure(q[0]); Measure(q[1]); ''') self.bell = xacc.getCompiled('bell')
import xacc qpu = xacc.getAccelerator('aer') qbits = xacc.qalloc(2) # Create a bell state program with too many cnots xacc.qasm(''' .compiler xasm .circuit foo .parameters x,y,z .qbit q H(q[0]); CX(q[0], q[1]); CX(q[0], q[1]); CX(q[0], q[1]); Measure(q[0]); Measure(q[1]); ''') f = xacc.getCompiled('foo') # Run the python contributed IRTransformation that uses qiskit optimizer = xacc.getIRTransformation('qiskit-cx-cancellation') optimizer.apply(f, None, {}) # should have 4 instructions, not 6 assert (4 == f.nInstructions()) print(f.toString()) qbits = xacc.qalloc(2) qpu.execute(qbits, f)
# allocate some qubits to run on qpu = xacc.getAccelerator('qpp', {'shots': 4096}) # In this example: we want to estimate the *phase* of an arbitrary 'oracle' # i.e. Oracle(|State>) = exp(i*Phase)*|State> # and we need to estimate that Phase. # The oracle is a simple T gate, and the eigenstate is |1> # T|1> = e^(i*pi/4)|1> # The phase value of pi/4 = 2pi * (1/8) # i.e. if we use a 3-bit register for estimation, # we will get the correct answer of 1 deterministically. xacc.qasm('''.compiler xasm .circuit oracle .qbit q T(q[0]); ''') oracle = xacc.getCompiled('oracle') # We need to prepare the eigenstate |1> xacc.qasm('''.compiler xasm .circuit prep .qbit q X(q[0]); ''') statePrep = xacc.getCompiled('prep') # We need 4 qubits (3-bit precision) buffer = xacc.qalloc(4)
# Mid-circuit measurement is supportted by: # - Simulator: qpp, qsim, aer # - Selected IBM backends. # qpu = xacc.getAccelerator('aer', {"shots": 1024}) qpu = xacc.getAccelerator('qpp', {"shots": 1024}) q = xacc.qalloc(3) xacc.qasm(''' .compiler xasm .circuit ghz_to_bell .qbit q H(q[2]); CX(q[2], q[1]); CX(q[1], q[0]); // Z -> X basis H(q[0]); // Mid-circuit measurement => Bell state Measure(q[0]); CX(q[2], q[1]); H(q[2]); X(q[0]); Measure(q[0]); Measure(q[1]); Measure(q[2]); ''') f = xacc.getCompiled('ghz_to_bell') qpu.execute(q, f) print(q) # Note: QPP is using a LSB bit-ordering sim_counts_ghz_bell_1 = q.getMarginalCounts([0], xacc.BitOrder.LSB) sim_counts_ghz_bell_2 = q.getMarginalCounts([1, 2, 3], xacc.BitOrder.LSB)
# Get the QPU and allocate a single qubit qpu = xacc.getAccelerator('qpp') qbits = xacc.qalloc(2) # Get the MLPack Optimizer, default is Adam optimizer = xacc.getOptimizer( 'mlpack', {'initial-parameters': [0., 0., 0., 0., 0., 0., 0., 0.]}) xacc.qasm(''' .compiler xasm .circuit qubit2_depth1 .parameters x .qbit q U(q[0], x[0], -pi/2, pi/2 ); U(q[0], 0, 0, x[1]); U(q[1], x[2], -pi/2, pi/2); U(q[1], 0, 0, x[3]); CNOT(q[0], q[1]); U(q[0], 0, 0, x[4]); U(q[0], x[5], -pi/2, pi/2); U(q[1], 0, 0, x[6]); U(q[1], x[7], -pi/2, pi/2); ''') f = xacc.getCompiled('qubit2_depth1') # Get the DDCL Algorithm, initialize it # with necessary parameters ddcl = xacc.getAlgorithm( 'ddcl', { 'ansatz': f,
qpu = xacc.getAccelerator('aer', {'readout_error': True, 'shots': 4096,\ 'backend':'ibmq_20_tokyo'}) qbits = xacc.qalloc(3) layout = np.array([1, 2, 3], dtype=np.uintp) decorator = xacc.getAcceleratorDecorator('assignment-error-kernel', qpu, { 'gen-kernel': True, 'layout': layout }) xacc.qasm(''' .compiler xasm .circuit foo .qbit q H(q[0]); H(q[1]); CNOT(q[0], q[2]); CNOT(q[1], q[2]); Measure(q[0]); Measure(q[1]); Measure(q[2]); ''') ansatz = xacc.getCompiled('foo') decorator.execute(qbits, ansatz) print(qbits) kernel = qbits.getInformation("error-kernel") original = qbits.getInformation("unmitigated-counts") mitigated = qbits.getMeasurementCounts()
xacc.qasm(''' .compiler xasm .circuit iterative_qpe .qbit q H(q[0]); X(q[1]); // Prepare the state: CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); H(q[0]); // Measure and reset Measure(q[0], c[0]); Reset(q[0]); H(q[0]); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); // Conditional rotation if(c[0]) { Rz(q[0], -pi/2); } H(q[0]); Measure(q[0], c[1]); Reset(q[0]); H(q[0]); CPhase(q[0], q[1], -5*pi/8); CPhase(q[0], q[1], -5*pi/8); if(c[0]) { Rz(q[0], -pi/4); } if(c[1]) { Rz(q[0], -pi/2); } H(q[0]); Measure(q[0], c[2]); Reset(q[0]); H(q[0]); CPhase(q[0], q[1], -5*pi/8); if(c[0]) { Rz(q[0], -pi/8); } if(c[1]) { Rz(q[0], -pi/4); } if(c[2]) { Rz(q[0], -pi/2); } H(q[0]); Measure(q[0], c[3]); ''')
def execute(self, inputParams): xacc_opts = inputParams['XACC'] acc_name = xacc_opts['accelerator'] qpu = xacc.getAccelerator(acc_name, xacc_opts) if 'verbose' in xacc_opts and xacc_opts['verbose']: xacc.set_verbose(True) if 'Benchmark' not in inputParams: xacc.error('Invalid benchmark input - must have Benchmark description') if 'Observable' not in inputParams: xacc.error('Invalid benchmark input - must have Observable description') if 'Ansatz' not in inputParams: xacc.error('Invalid benchmark input - must have Ansatz circuit description') if 'Decorators' in inputParams: if 'readout_error' in inputParams['Decorators']: qpu = xacc.getAcceleratorDecorator('ro-error', qpu) H = None if inputParams['Observable']['name'] == 'pauli': obs_str = inputParams['Observable']['obs_str'] H = xacc.getObservable('pauli', obs_str) elif inputParams['Observable']['name'] == 'fermion': obs_str = inputParams['Observable']['obs_str'] H = xacc.getObservable('fermion', obs_str) elif inputParams['Observable']['name'] == 'psi4': opts = {'basis':inputParams['Observable']['basis'], 'geometry':inputParams['Observable']['geometry']} if 'fo' in inputParams['Observable'] and 'ao' in inputParams['Observable']: opts['frozen-spin-orbitals'] = ast.literal_eval(inputParams['Observable']['fo']) opts['active-spin-orbitals'] = ast.literal_eval(inputParams['Observable']['ao']) H = xacc.getObservable('psi4', opts) #print('Ham: ', H.toString()) buffer = xacc.qalloc(H.nBits()) optimizer = None if 'Optimizer' in inputParams: # check that values that can be ints/floats are opts = inputParams['Optimizer'] for k,v in inputParams['Optimizer'].items(): try: i = int(v) opts[k] = i continue except: pass try: f = float(v) opts[k] = f continue except: pass optimizer = xacc.getOptimizer(inputParams['Optimizer']['name'] if 'Optimizer' in inputParams else 'nlopt', opts) else: optimizer = xacc.getOptimizer('nlopt') provider = xacc.getIRProvider('quantum') if 'source' in inputParams['Ansatz']: # here assume this is xasm always src = inputParams['Ansatz']['source'] xacc.qasm(src) # get the name of the circuit circuit_name = None for l in src.split('\n'): if '.circuit' in l: circuit_name = l.split(' ')[1] ansatz = xacc.getCompiled(circuit_name) else: ansatz = provider.createInstruction(inputParams['Ansatz']['ansatz']) ansatz = xacc.asComposite(ansatz) alg = xacc.getAlgorithm(inputParams['Benchmark']['algorithm'], { 'ansatz': ansatz, 'accelerator': qpu, 'observable': H, 'optimizer': optimizer, }) alg.execute(buffer) return buffer
qpu = xacc.getAccelerator('qpp', {'shots': 100}) xacc.qasm(''' .compiler xasm .circuit teleport .qbit q X(q[0]); // Bell channel setup H(q[1]); CX(q[1], q[2]); // Alice Bell measurement CX(q[0], q[1]); H(q[0]); Measure(q[0]); Measure(q[1]); // Correction if (q[0]) { Z(q[2]); } if (q[1]) { X(q[2]); } // Measure teleported qubit Measure(q[2]); ''') teleport = xacc.getCompiled('teleport')
import xacc noiseModelJson = '{"errors": [{"type": "qerror", "operations": ["u1"], "instructions": [[{"name": "x", "qubits": [0]}], [{"name": "y", "qubits": [0]}], [{"name": "z", "qubits": [0]}], [{"name": "id", "qubits": [0]}]], "probabilities": [0.00025, 0.00025, 0.00025, 0.99925]}, {"type": "qerror", "operations": ["u2"], "instructions": [[{"name": "x", "qubits": [0]}], [{"name": "y", "qubits": [0]}], [{"name": "z", "qubits": [0]}], [{"name": "id", "qubits": [0]}]], "probabilities": [0.00025, 0.00025, 0.00025, 0.99925]}, {"type": "qerror", "operations": ["u3"], "instructions": [[{"name": "x", "qubits": [0]}], [{"name": "y", "qubits": [0]}], [{"name": "z", "qubits": [0]}], [{"name": "id", "qubits": [0]}]], "probabilities": [0.00025, 0.00025, 0.00025, 0.99925]}], "x90_gates": []}' qpu = xacc.getAccelerator('aer', { 'noise-model': noiseModelJson, 'shots': 4096 }) qpu = xacc.getAcceleratorDecorator('mitiq', qpu) q = xacc.qalloc(1) xacc.qasm('''.compiler xasm .circuit foo .parameters x .qbit q for (int i = 0; i < 10; i++) { X(q[0]); } Measure(q[0]); ''') foo = xacc.getCompiled('foo') qpu.execute(q, foo) print(q) print(q.getExpectationValueZ())
import sys from pathlib import Path sys.path.insert(1, str(Path.home()) + '/.xacc') import xacc xacc.qasm(''' .compiler xasm .circuit ansatz .qbit q U(q[1], 1.5708,0,3.14159); U(q[0], 1.5708,1.5708,4.71239); CNOT(q[0], q[1]); U(q[2], 1.5708,-3.14159,3.14159); U(q[3], 1.5708,0,3.14159); CNOT(q[2], q[3]); Rz(q[3], 0.101476); CNOT(q[2], q[3]); CNOT(q[1], q[2]); CNOT(q[0], q[1]); U(q[3], 1.5708,0,3.14159); U(q[2], 1.5708,0,3.14159); U(q[0], 1.5708,1.5708,4.71239); U(q[1], 1.5708,0,3.14159); ''') ansatz = xacc.getCompiled('ansatz') #qpu = xacc.getAccelerator('qsim') qpu = xacc.getAccelerator('tnqvm:exatn', { "exp-val-by-conjugate": True, "max-qubit": 2 }) print("QPU:", qpu.name()) buffer = xacc.qalloc(4)
import xacc qpu = xacc.getAccelerator( 'ibm', {'shots': 256, 'backend': 'lowest-queue-count', 'n-qubits': 5, 'check-jobs-limit': True}) print(qpu.getProperties()["total-json"]) xacc.qasm('''.compiler xasm .circuit bell .qbit q H(q[0]); CX(q[0],q[1]); Measure(q[0]); Measure(q[1]); ''') bell = xacc.getCompiled('bell') q = xacc.qalloc(2) qpu.execute(q, bell) print(q)
Ry(q[1], t0) CNOT(q[1], q[0]) ansatz(buffer) print('Energy = ', buffer.getInformation('opt-val')) print('Opt Angles = ', buffer.getInformation('opt-params')) # Define the ansatz and decorate it to indicate # you'd like to run VQE xacc.qasm('''.compiler xasm .circuit ansatz2 .parameters t0 .qbit q X(q[0]); Ry(q[1],t0); CX(q[1],q[0]); ''') ansatz2 = xacc.getCompiled('ansatz2') opt = xacc.getOptimizer('nlopt') # Create the VQE algorithm vqe = xacc.getAlgorithm('vqe', { 'ansatz': ansatz2, 'accelerator': qpu, 'observable': ham, 'optimizer': opt }) vqe.execute(buffer)
import xacc # xacc.set_verbose(True) # Get the QPU and allocate a single qubit qpu = xacc.getAccelerator('aer') qbits = xacc.qalloc(1) # Get the MLPack Optimizer, default is Adam optimizer = xacc.getOptimizer('mlpack') # Create a simple quantum program xacc.qasm(''' .compiler xasm .circuit foo .parameters x,y,z .qbit q Ry(q[0], x); Ry(q[0], y); Ry(q[0], z); ''') f = xacc.getCompiled('foo') f.defaultPlacement(qpu, {'qubit-map': [0]}) print(f.toString()) # exit(0) # Get the DDCL Algorithm, initialize it # with necessary parameters ddcl = xacc.getAlgorithm( 'ddcl', { 'ansatz': f, 'accelerator': qpu,