def initialize(self, options): self.qobj_compiler = xacc.getCompiler('qobj') if 'shots' in options: self.shots = options['shots'] if 'backend' in options: self.backend = options['backend'] import json from qiskit.providers.models.backendproperties import BackendProperties from qiskit.providers.aer import noise self.modeled_qpu = xacc.getAccelerator('ibm:' + self.backend) props = self.modeled_qpu.getProperties() jsonStr = props['total-json'] # print("jsonStr: \n", jsonStr) properties = BackendProperties.from_dict(json.loads(jsonStr)) ro_error = True if 'readout_error' in options and options[ 'readout_error'] else False rel = True if 'thermal_relaxation' in options and options[ 'thermal_relaxation'] else False ge = True if 'gate_error' in options and options[ 'gate_error'] else False self.noise_model = noise.NoiseModel.from_backend( backend, readout_error=ro_error, thermal_relaxation=rel, gate_error=ge)
def setUp(self): self.qpu = xacc.getAccelerator('local-ibm') self.buffer = self.qpu.createBuffer('q', 2) self.ham = PauliOperator(5.906709445) + \ PauliOperator({0: 'X', 1: 'X'}, -2.1433) + \ PauliOperator({0: 'Y', 1: 'Y'}, -2.1433) + \ PauliOperator({0: 'Z'}, .21829) + \ PauliOperator({1: 'Z'}, -6.125)
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
async def execute_qpu_request(*args, **kwargs): fin = open('.tmp_quil_code', 'r') lines = fin.readlines() fin.close() seen_quil_code = '__qpu__ void test(qreg q) {\n' for l in lines: if 'num_shots' in l: shots = int(l.split('=')[1]) elif 'DECLARE' in l: continue else: seen_quil_code += l seen_quil_code += '}' os.remove('.tmp_quil_code') program = xacc.getCompiler('quil').compile( seen_quil_code).getComposites()[0] b = xacc.qalloc(program.nLogicalBits()) xacc.getAccelerator('qpp', {'shots': shots}).execute(b, program) print(b) fout = open('.tmp_results', 'w') fout.write(str(b)) fout.close() return "JOBIDHERE"
def test_generic(self): qpu = xacc.getAccelerator('tnqvm') buffer = qpu.createBuffer('q', 4) @xacc.qpu(accelerator=qpu) def entangle(buffer): H(0) CNOT(0, 1) Measure(0, 0) Measure(1, 1) xacc.Initialize() entangle(buffer) self.assertEqual(entangle.nParameters(), 0) self.assertEqual(entangle.getFunction().toString(), 'H q0\nCNOT q0,q1\nMeasure q0\nMeasure q1\n')
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')
def testExecuteVQE(self): src = """__qpu__ kernel() { 0.7137758743754461 -1.252477303982147 0 1 0 0 0.337246551663004 0 1 1 1 1 0 0 0 0.0906437679061661 0 1 1 1 3 0 2 0 0.0906437679061661 0 1 2 1 0 0 2 0 0.3317360224302783 0 1 2 1 2 0 0 0 0.0906437679061661 0 1 3 1 1 0 2 0 0.3317360224302783 0 1 3 1 3 0 0 0 0.337246551663004 1 1 0 1 0 0 1 0 0.0906437679061661 1 1 0 1 2 0 3 0 -1.252477303982147 1 1 1 0 0.0906437679061661 1 1 2 1 0 0 3 0 0.3317360224302783 1 1 2 1 2 0 1 0 0.0906437679061661 1 1 3 1 1 0 3 0 0.3317360224302783 1 1 3 1 3 0 1 0 0.3317360224302783 2 1 0 1 0 0 2 0 0.0906437679061661 2 1 0 1 2 0 0 0 0.3317360224302783 2 1 1 1 1 0 2 0 0.0906437679061661 2 1 1 1 3 0 0 0 -0.4759344611440753 2 1 2 0 0.0906437679061661 2 1 3 1 1 0 0 0 0.3486989747346679 2 1 3 1 3 0 2 0 0.3317360224302783 3 1 0 1 0 0 3 0 0.0906437679061661 3 1 0 1 2 0 1 0 0.3317360224302783 3 1 1 1 1 0 3 0 0.0906437679061661 3 1 1 1 3 0 1 0 0.0906437679061661 3 1 2 1 0 0 1 0 0.3486989747346679 3 1 2 1 2 0 3 0 -0.4759344611440753 3 1 3 0 }""" op = vqe.compile(src) buffer = xacc.getAccelerator('tnqvm').createBuffer('q',4) self.assertAlmostEqual(vqe.execute(op, buffer, **{'task':'vqe', 'n-electrons':2}).energy, -1.13727, places=5)
import xacc # Noise model string for a simple depolarizing noise. depol_json = """{"gate_noise": [{"gate_name": "X", "register_location": ["0"], "noise_channels": [{"matrix": [[[[0.99498743710662, 0.0], [0.0, 0.0]], [[0.0, 0.0], [0.99498743710662, 0.0]]], [[[0.0, 0.0], [0.05773502691896258, 0.0]], [[0.05773502691896258, 0.0], [0.0, 0.0]]], [[[0.0, 0.0], [0.0, -0.05773502691896258]], [[0.0, 0.05773502691896258], [0.0, 0.0]]], [[[0.05773502691896258, 0.0], [0.0, 0.0]], [[0.0, 0.0], [-0.05773502691896258, 0.0]]]]}]}], "bit_order": "MSB"}""" noise_model = xacc.getNoiseModel("json", {"noise-model": depol_json}) # Using Aer simulator in density matrix mode. # Note: toJson() will convert the noise_model to IBM format to use w/ Aer qpu = xacc.getAccelerator('aer', { "noise-model": noise_model.toJson(), "sim-type": "density_matrix" }) # Define the quantum kernel in standard Python @xacc.qpu(accelerator=qpu) def test(q): X(q[0]) q = xacc.qalloc(1) # run the circuit test(q) # print the density matrix (flattened) print(q["density_matrix"])
# Demonstrate mid-circuit measurement support # GHZ to Bell conversion # Adapted from: # https://quantum-computing.ibm.com/docs/manage/systems/midcircuit-measurement/#GHZ-to-Bell-State import xacc # 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]);
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 xacc import xaccvqe from xaccvqe import PauliOperator xacc.Initialize(['--compiler','quil']) ibm = xacc.getAccelerator('local-ibm') tnqvm = xacc.getAccelerator('tnqvm') rigetti = xacc.getAccelerator('rigetti') #buffer = ibm.createBuffer('q', 2) buffer = tnqvm.createBuffer('q', 2) h2 = PauliOperator(5.906709445) + \ PauliOperator({0:'X',1:'X'}, -2.1433) + \ PauliOperator({0:'Y',1:'Y'}, -2.1433) + \ PauliOperator({0:'Z'}, .21829) + \ PauliOperator({1:'Z'}, -6.125) h3 = h2 + PauliOperator(9.625) + \ PauliOperator({1:'X',2:'X'}, -3.913119) + \ PauliOperator({1:'Y',2:'Y'}, -3.913119) + \ PauliOperator({2:'Z'}, -9.625) @xaccvqe.qpu.vqe(accelerator=tnqvm, observable=h3) def ansatz(buffer, t0, t1): X(0) Ry(t0, 2) CNOT(2, 0) Ry(t1, 1)
def execute(self, inputParams): """ This method is intended to be inherited by vqe and vqe_energy subclasses to allow algorithm-specific implementation. This superclass method adds extra information to the buffer and allows XACC settings options to be set before executing VQE. Parameters: inputParams : dictionary a dictionary of input parameters obtained from .ini file return QPU Accelerator buffer Options used (obtained from inputParams): 'qubit-map': map of logical qubits to physical qubits 'n-execs': number of sampler executions of measurements 'initial-parameters': list of initial parameters for the VQE algorithm 'restart-from-file': AcceleratorDecorator option to allow restart of VQE algorithm 'readout-error': AcceleratorDecorator option for readout-error mitigation """ m = xacc.HeterogeneousMap() if 'shots' in inputParams: m.insert('shots', int(inputParams['shots'])) if 'backend' in inputParams: m.insert('backend', inputParams['backend']) self.qpu = xacc.getAccelerator(inputParams['accelerator'], m) xaccOp = self.hamiltonian_generators[ inputParams['hamiltonian-generator']].generate(inputParams) self.ansatz = self.ansatz_generators[inputParams['name']].generate( inputParams, xaccOp.nBits()) if 'qubit-map' in inputParams: qubit_map = ast.literal_eval(inputParams['qubit-map']) xaccOp, self.ansatz, n_qubits = xaccvqe.mapToPhysicalQubits( xaccOp, self.ansatz, qubit_map) else: n_qubits = xaccOp.nBits() self.op = xaccOp self.n_qubits = n_qubits # create buffer, add some extra info (hamiltonian, ansatz-qasm, python-ansatz-qasm) self.buffer = xacc.qalloc(n_qubits) self.buffer.addExtraInfo('hamiltonian', self.op.toString()) self.buffer.addExtraInfo( 'ansatz-qasm', self.ansatz.toString().replace('\\n', '\\\\n')) pycompiler = xacc.getCompiler('pyxasm') # self.buffer.addExtraInfo('ansatz-qasm-py', '\n'.join(pycompiler.translate(self.ansatz).split('\n')[1:])) # heres where we can set up the algorithm Parameters # all versions of vqe require: Accelerator, Ansatz, Observable # pure-vqe requires Optimizer # energy calculation has optional Parameters - can be random self.vqe_options_dict = { 'accelerator': self.qpu, 'ansatz': self.ansatz, 'observable': self.op } # get optimizers for VQE # needs to check if optimizer is a python plugin # if not, use nlopt (with options) # so we pull 'optimizer-options' out if available # Optimizer-options needs to be passed to BOTH XACC Core optimizers and to python plugins # vqe_options_dict is used to initialize the algorithms self.optimizer = None self.optimizer_options = {} if 'optimizer-options' in inputParams: self.optimizer_options = ast.literal_eval( inputParams['optimizer-options']) # initial-parameters for optimizer (vqe) # parameters for vqe-energy if 'initial-parameters' in inputParams: self.optimizer_options['initial-parameters'] = ast.literal_eval( inputParams['initial-parameters']) if 'parameters' in inputParams: self.optimizer_options['parameters'] = ast.literal_eval( inputParams['parameters']) if 'nlopt-maxeval' in inputParams: self.optimizer_options['nlopt-maxeval'] = int( inputParams['nlopt-maxeval']) # check to see if optimizer is a python plugin # if it is, we do not put it in self.vqe_options_dict # if it is not, it is put there if 'optimizer' in inputParams: if inputParams['optimizer'] in self.vqe_optimizers: self.optimizer = self.vqe_optimizers[inputParams['optimizer']] else: self.optimizer = xacc.getOptimizer(inputParams['optimizer'], self.optimizer_options) else: self.optimizer = xacc.getOptimizer('nlopt', self.optimizer_options) # vqe.py then will check vqe_options_dict for optimizer; if it isn't there, run python optimizer # and of course if it is, we run with XACC self.buffer.addExtraInfo('accelerator', inputParams['accelerator']) # need to make sure the AcceleratorDecorators work correctly if 'n-execs' in inputParams: xacc.setOption('sampler-n-execs', inputParams['n-execs']) self.qpu = xacc.getAcceleratorDecorator('improved-sampling', self.qpu) if 'restart-from-file' in inputParams: xacc.setOption('vqe-restart-file', inputParams['restart-from-file']) self.qpu = xacc.getAcceleratorDecorator('vqe-restart', self.qpu) self.qpu.initialize() if 'readout-error' in inputParams and inputParams['readout-error']: self.qpu = xacc.getAcceleratorDecorator('ro-error', self.qpu) if 'rdm-purification' in inputParams and inputParams[ 'rdm-purification']: print("setting RDM Purification") self.qpu = xacc.getAcceleratorDecorator('rdm-purification', self.qpu) m = xacc.HeterogeneousMap() m.insert('fermion-observable', self.op) self.qpu.initialize(m) self.vqe_options_dict = { 'optimizer': self.optimizer, 'accelerator': self.qpu, 'ansatz': self.ansatz, 'observable': self.op } xacc.setOptions(inputParams)
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)
import xacc xacc.Initialize() # Get access to D-Wave QPU and # allocate some qubits dwave = xacc.getAccelerator('dwave') qubits = dwave.createBuffer('q') # Define the function we'd like to # off-load to the QPU, here # we're using a the QMI low-level language @xacc.qpu(accelerator=dwave) def f(buffer, h, j): qmi(0, 0, h) qmi(1, 1, h) qmi(0, 1, j) # Execute on D-Wave f(qubits, 1., 2.) # Print the buffer, this displays # solutions and energies print(qubits) xacc.Finalize()
import xacc opstr = '''(0.174073,0) Z2 Z3 + (0.1202,0) Z1 Z3 + (0.165607,0) Z1 Z2 + (0.165607,0) Z0 Z3 + (0.1202,0) Z0 Z2 + (-0.0454063,0) Y0 Y1 X2 X3 + (-0.220041,0) Z3 + (-0.106477,0) + (0.17028,0) Z0 + (-0.220041,0) Z2 + (0.17028,0) Z1 + (-0.0454063,0) X0 X1 Y2 Y3 + (0.0454063,0) X0 Y1 Y2 X3 + (0.168336,0) Z0 Z1 + (0.0454063,0) Y0 X1 X2 Y3''' op = xacc.getObservable('pauli', opstr) qpu = xacc.getAccelerator('tnqvm') @xacc.qpu(algo='vqe', accelerator=qpu, observable=op) def ansatz_vqe(q, t0, t1): uccsd(q, {"ne": 2, "nq": 4}) print(ansatz_vqe.getFunction().toString()) buffer = xacc.qalloc(4) ansatz_vqe(buffer, 0., 0.)
from pyquil.gates import CNOT, H, MEASURE from pyquil import get_qc, Program import xacc import qiskit circ = qiskit.QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) qpu = xacc.getAccelerator('qpp', {'shots': 1024}) q = xacc.qalloc(2) qpu.execute(q, circ) print(q) p = Program() p += H(0) p += CNOT(0, 1) ro = p.declare('ro', 'BIT', 2) p += MEASURE(0, ro[0]) p += MEASURE(1, ro[1]) r = xacc.qalloc(2) qpu.execute(r, p) print(r) provider = xacc.getIRProvider('quantum')
import xacc # Get the Aer Accelerator, provides noise modeling # based on specified IBM backend. Can turn on # readout_error, thermal_relaxation, and gate_error qpu = xacc.getAccelerator('aer', { 'shots': 1024, 'backend': 'ibmq_johannesburg', 'readout_error': True }) # Define the quantum kernel in standard Python @xacc.qpu(accelerator=qpu) def bell(q): H(q[0]) CX(q[0], q[1]) Measure(q[0]) Measure(q[1]) # Allocate 2 qubits q = xacc.qalloc(2) # run the bell state computation bell(q) print(q)
import xacc import numpy as np xacc.set_verbose(True) # Choose the QPU on which to # characterize the process matrix for a Hadamard qpu = xacc.getAccelerator('ibm:ibmq_poughkeepsie') # Create the CompositeInstruction containing a # single Hadamard instruction provider = xacc.getIRProvider('quantum') circuit = provider.createComposite('U') hadamard = provider.createInstruction('H', [0]) circuit.addInstruction(hadamard) # Create the Algorithm, give it the circuit # to characterize and the backend to target qpt = xacc.getAlgorithm('qpt', {'circuit':circuit, 'accelerator':qpu}) # map logical 0 to physical 1 # Allocate a qubit, this will # store our tomography results buffer = xacc.qalloc(1) # Execute qpt.execute(buffer) # Compute the fidelity with respect to # the ideal hadamard process F = qpt.calculate('fidelity', buffer, {'chi-theoretical-real':[0., 0., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 1.]}) print('\nFidelity: ', F) # Can get the chi process matrix and print it
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
import xacc # Get the QPU and allocate a single qubit qpu = xacc.getAccelerator('local-ibm') 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(
import xacc xacc.set_verbose(True) qpu = xacc.getAccelerator('qpp') optimizer = xacc.getOptimizer('nlopt', {'nlopt-optimizer': 'l-bfgs'}) buffer = xacc.qalloc(4) opstr = ''' (-0.165606823582,-0) 1^ 2^ 1 2 + (0.120200490713,0) 1^ 0^ 0 1 + (-0.0454063328691,-0) 0^ 3^ 1 2 + (0.168335986252,0) 2^ 0^ 0 2 + (0.0454063328691,0) 1^ 2^ 3 0 + (0.168335986252,0) 0^ 2^ 2 0 + (0.165606823582,0) 0^ 3^ 3 0 + (-0.0454063328691,-0) 3^ 0^ 2 1 + (-0.0454063328691,-0) 1^ 3^ 0 2 + (-0.0454063328691,-0) 3^ 1^ 2 0 + (0.165606823582,0) 1^ 2^ 2 1 + (-0.165606823582,-0) 0^ 3^ 0 3 + (-0.479677813134,-0) 3^ 3 + (-0.0454063328691,-0) 1^ 2^ 0 3 + (-0.174072892497,-0) 1^ 3^ 1 3 + (-0.0454063328691,-0) 0^ 2^ 1 3 + (0.120200490713,0) 0^ 1^ 1 0 + (0.0454063328691,0) 0^ 2^ 3 1 + (0.174072892497,0) 1^ 3^ 3 1 + (0.165606823582,0) 2^ 1^ 1 2 + (-0.0454063328691,-0) 2^ 1^ 3 0 + (-0.120200490713,-0) 2^ 3^ 2 3 + (0.120200490713,0) 2^ 3^ 3 2 + (-0.168335986252,-0) 0^ 2^ 0 2 + (0.120200490713,0) 3^ 2^ 2 3 + (-0.120200490713,-0) 3^ 2^ 3 2 + (0.0454063328691,0) 1^ 3^ 2 0 + (-1.2488468038,-0) 0^ 0 + (0.0454063328691,0) 3^ 1^ 0 2 + (-0.168335986252,-0) 2^ 0^ 2 0 + (0.165606823582,0) 3^ 0^ 0 3 + (-0.0454063328691,-0) 2^ 0^ 3 1 + (0.0454063328691,0) 2^ 0^ 1 3 + (-1.2488468038,-0) 2^ 2 + (0.0454063328691,0) 2^ 1^ 0 3 + (0.174072892497,0) 3^ 1^ 1 3 + (-0.479677813134,-0) 1^ 1 + (-0.174072892497,-0) 3^ 1^ 3 1 + (0.0454063328691,0) 3^ 0^ 1 2 + (-0.165606823582,-0) 3^ 0^ 3 0 + (0.0454063328691,0) 0^ 3^ 2 1 + (-0.165606823582,-0) 2^ 1^ 2 1 + (-0.120200490713,-0) 0^ 1^ 0 1 + (-0.120200490713,-0) 1^ 0^ 1 0 + (0.7080240981,0) '''
import xacc # Get access to the desired QPU and # allocate some qubits to run on qpu = xacc.getAccelerator('tnqvm', {'vqe-mode': True}) buffer = xacc.qalloc(4) geom = ''' 0 1 Na 0.000000 0.0 0.0 H 0.0 0.0 1.914388 symmetry c1 ''' fo = [0, 1, 2, 3, 4, 10, 11, 12, 13, 14] ao = [5, 9, 15, 19] H = xacc.getObservable( 'psi4-frozen-core', { 'basis': 'sto-3g', 'geometry': geom, 'frozen-spin-orbitals': fo, 'active-spin-orbitals': ao }) @xacc.qpu(algo='vqe', accelerator=qpu, observable=H) def ansatz(q, x): X(q[0]) X(q[2]) ucc1(q, x[0])
import xacc accelerator = xacc.getAccelerator("qpp") buffer = xacc.qalloc(4) opstr = ''' (-0.165606823582,-0) 1^ 2^ 1 2 + (0.120200490713,0) 1^ 0^ 0 1 + (-0.0454063328691,-0) 0^ 3^ 1 2 + (0.168335986252,0) 2^ 0^ 0 2 + (0.0454063328691,0) 1^ 2^ 3 0 + (0.168335986252,0) 0^ 2^ 2 0 + (0.165606823582,0) 0^ 3^ 3 0 + (-0.0454063328691,-0) 3^ 0^ 2 1 + (-0.0454063328691,-0) 1^ 3^ 0 2 + (-0.0454063328691,-0) 3^ 1^ 2 0 + (0.165606823582,0) 1^ 2^ 2 1 + (-0.165606823582,-0) 0^ 3^ 0 3 + (-0.479677813134,-0) 3^ 3 + (-0.0454063328691,-0) 1^ 2^ 0 3 + (-0.174072892497,-0) 1^ 3^ 1 3 + (-0.0454063328691,-0) 0^ 2^ 1 3 + (0.120200490713,0) 0^ 1^ 1 0 + (0.0454063328691,0) 0^ 2^ 3 1 + (0.174072892497,0) 1^ 3^ 3 1 + (0.165606823582,0) 2^ 1^ 1 2 + (-0.0454063328691,-0) 2^ 1^ 3 0 + (-0.120200490713,-0) 2^ 3^ 2 3 + (0.120200490713,0) 2^ 3^ 3 2 + (-0.168335986252,-0) 0^ 2^ 0 2 + (0.120200490713,0) 3^ 2^ 2 3 + (-0.120200490713,-0) 3^ 2^ 3 2 + (0.0454063328691,0) 1^ 3^ 2 0 + (-1.2488468038,-0) 0^ 0 + (0.0454063328691,0) 3^ 1^ 0 2 + (-0.168335986252,-0) 2^ 0^ 2 0 + (0.165606823582,0) 3^ 0^ 0 3 + (-0.0454063328691,-0) 2^ 0^ 3 1 + (0.0454063328691,0) 2^ 0^ 1 3 + (-1.2488468038,-0) 2^ 2 + (0.0454063328691,0) 2^ 1^ 0 3 + (0.174072892497,0) 3^ 1^ 1 3 + (-0.479677813134,-0) 1^ 1 + (-0.174072892497,-0) 3^ 1^ 3 1 + (0.0454063328691,0) 3^ 0^ 1 2 + (-0.165606823582,-0) 3^ 0^ 3 0 + (0.0454063328691,0) 0^ 3^ 2 1 + (-0.165606823582,-0) 2^ 1^ 2 1 + (-0.120200490713,-0) 0^ 1^ 0 1 + (-0.120200490713,-0) 1^ 0^ 1 0 + (0.7080240981,0) ''' H = xacc.getObservable('fermion', opstr)
import xacc, sys, numpy as np # Get access to the desired QPU and # 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')
import xacc xacc.set_verbose(True) # Get access to the desired QPU and # allocate some qubits to run on qpu = xacc.getAccelerator('aer', {'vqe-mode': True}) buffer = xacc.qalloc(4) geom = ''' 0 1 Na 0.000000 0.0 0.0 H 0.0 0.0 1.914388 symmetry c1 ''' fo = [0, 1, 2, 3, 4, 10, 11, 12, 13, 14] ao = [5, 9, 15, 19] H = xacc.getObservable( 'psi4', { 'basis': 'sto-3g', 'geometry': geom, 'frozen-spin-orbitals': fo, 'active-spin-orbitals': ao }) @xacc.qpu(algo='vqe', accelerator=qpu, observable=H) def ansatz(q, x): X(q[0]) X(q[2]) ucc1(q, x[0])
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]); ''') f = xacc.getCompiled('iterative_qpe') print(f.toString()) # qpu = xacc.getAccelerator('qpp', {'shots':1024}) qpu = xacc.getAccelerator('aer', {'shots': 1024}) # With noise # Note: IBMQ doesn't support bfunc (conditional) instruction atm, # hence, we can only do simulation of the QObj. # qpu = xacc.getAccelerator('aer:ibmq_manhattan', {'shots':1024}) q = xacc.qalloc(2) qpu.execute(q, f) print(q)
def execute(self, inputParams): """ This method is intended to be inherited by vqe and vqe_energy subclasses to allow algorithm-specific implementation. This superclass method adds extra information to the buffer and allows XACC settings options to be set before executing VQE. Parameters: inputParams : dictionary a dictionary of input parameters obtained from .ini file return QPU Accelerator buffer Options used (obtained from inputParams): 'qubit-map': map of logical qubits to physical qubits 'n-execs': number of sampler executions of measurements 'initial-parameters': list of initial parameters for the VQE algorithm 'restart-from-file': AcceleratorDecorator option to allow restart of VQE algorithm 'readout-error': AcceleratorDecorator option for readout-error mitigation """ self.qpu = xacc.getAccelerator(inputParams['accelerator']) xaccOp = self.hamiltonian_generators[ inputParams['hamiltonian-generator']].generate(inputParams) self.ansatz = self.ansatz_generators[inputParams['name']].generate( inputParams, xaccOp.nQubits()) if 'qubit-map' in inputParams: qubit_map = ast.literal_eval(inputParams['qubit-map']) xaccOp, self.ansatz, n_qubits = xaccvqe.mapToPhysicalQubits( xaccOp, self.ansatz, qubit_map) else: n_qubits = xaccOp.nQubits() self.op = xaccOp self.n_qubits = n_qubits self.buffer = self.qpu.createBuffer('q', n_qubits) self.buffer.addExtraInfo('hamiltonian', str(xaccOp)) self.buffer.addExtraInfo( 'ansatz-qasm', self.ansatz.toString('q').replace('\\n', '\\\\n')) pycompiler = xacc.getCompiler('xacc-py') self.buffer.addExtraInfo( 'ansatz-qasm-py', '\n'.join(pycompiler.translate('q', self.ansatz).split('\n')[1:])) self.optimizer = None self.optimizer_options = {} if 'optimizer' in inputParams: if inputParams['optimizer'] in self.vqe_optimizers: self.optimizer = self.vqe_optimizers[inputParams['optimizer']] if 'method' in inputParams: self.optimizer_options['method'] = inputParams['method'] if 'options' in inputParams: self.optimizer_options['options'] = ast.literal_eval( inputParams['options']) if 'user-params' in inputParams: self.optimizer_options['options'][ 'user_params'] = ast.literal_eval( inputParams['user-params']) else: xacc.setOption('vqe-backend', inputParams['optimizer']) else: xacc.info( "No classical optimizer specified. Setting to default XACC optimizer." ) self.buffer.addExtraInfo('accelerator', inputParams['accelerator']) if 'n-execs' in inputParams: xacc.setOption('sampler-n-execs', inputParams['n-execs']) self.qpu = xacc.getAcceleratorDecorator('improved-sampling', self.qpu) if 'restart-from-file' in inputParams: xacc.setOption('vqe-restart-file', inputParams['restart-from-file']) self.qpu = xacc.getAcceleratorDecorator('vqe-restart', self.qpu) self.qpu.initialize() if 'readout-error' in inputParams and inputParams['readout-error']: self.qpu = xacc.getAcceleratorDecorator('ro-error', self.qpu) if 'rdm-purification' in inputParams and inputParams[ 'rdm-purification']: self.qpu = xacc.getAcceleratorDecorator('rdm-purification', self.qpu) self.vqe_options_dict = { 'accelerator': self.qpu, 'ansatz': self.ansatz } if 'initial-parameters' in inputParams: self.vqe_options_dict['vqe-params'] = ','.join([ str(x) for x in ast.literal_eval(inputParams['initial-parameters']) ]) xacc.setOptions(inputParams)
program.addInstruction(gaussian) # Measure instructions (to be lowered to pulses) m0 = provider.createInstruction("Measure", [0]) m1 = provider.createInstruction("Measure", [1]) m2 = provider.createInstruction("Measure", [2]) m3 = provider.createInstruction("Measure", [3]) m4 = provider.createInstruction("Measure", [4]) program.addInstruction(m0) program.addInstruction(m1) program.addInstruction(m2) program.addInstruction(m3) program.addInstruction(m4) # Execute on the Aer simulator (bogota 5-qubit device) qpu = xacc.getAccelerator("aer:ibmq_bogota", {"sim-type": "pulse"}) buffer = xacc.qalloc(5) qpu.execute(buffer, program) # print(buffer) # Aer simulator will also return the state vector: # Note: it looks like the state-vector is in the qutrit space... # and the leaked state |2> is measured as 0. state_vec = buffer.getInformation("state") print(len(state_vec))
import xacc import numpy as np 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)