Exemplo n.º 1
0
 def test_simple_bell(self):
     try:
         q = xacc.qalloc(2)
         self.qpu.execute(q, self.bell)
         print(q)
     except:
         print('Failure in bell test - shutting down the server')
         requests.post("http://localhost:64574/shutdown")
         time.sleep(2)
Exemplo n.º 2
0
 def test_simple_hadamard(self):
     try:
         q = xacc.qalloc(1)
         self.qpu.execute(q, self.super)
         print(q)
     except:
         print('Failure in hadamard test - shutting down the server')
         requests.post("http://localhost:64574/shutdown")
         time.sleep(2)
Exemplo n.º 3
0
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
Exemplo n.º 4
0
    def execute(self, buffer, programs):

        if isinstance(programs, list) and len(programs) > 1:
            for p in programs:
                tmpBuffer = xacc.qalloc(buffer.size())
                tmpBuffer.setName(p.name())
                self.execute_one_qasm(tmpBuffer, p)
                buffer.appendChild(p.name(),tmpBuffer)
        else:
            if isinstance(programs, list):
                programs = programs[0]
            self.execute_one_qasm(buffer, programs)
Exemplo n.º 5
0
 def execute(self, buffer, programs):
     # Translate IR to a Qobj Json String
     if isinstance(programs, list) and len(programs) > 1:
         for p in programs:
             tmpBuffer = xacc.qalloc(buffer.size())
             tmpBuffer.setName(p.name())
             self.execute_single(tmpBuffer, p)
             buffer.appendChild(p.name(), tmpBuffer)
     else:
         if isinstance(programs, list):
             programs = programs[0]
         self.execute_single(buffer, programs)
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
        def noisy_sim(circ: QuantumCircuit):
            # Convert circ to a CompositeInstruction
            out_src = circ.qasm()

            # print('hello src:\n', out_src)
            out_prog = self.openqasm_compiler.compile(
                out_src).getComposites()[0]

            # print('after compile:\n', out_prog.toString())
            # Execute on a tmp buffer
            tmp_buffer = xacc.qalloc(buffer.size())
            self.decoratedAccelerator.execute(tmp_buffer, out_prog)

            # record the noisy exp val
            buffer.addExtraInfo('noisy-exp-val-z',
                                tmp_buffer.getExpectationValueZ())
            buffer.appendChild('mitiq-noisy-exec-' + buffer.name(), tmp_buffer)
            return tmp_buffer.getExpectationValueZ()
Exemplo n.º 8
0
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"
Exemplo n.º 9
0
.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')

q = xacc.qalloc(3)
qq = xacc.qalloc()
qpu.execute(q, teleport)

print(q)
Exemplo n.º 10
0
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"])
Exemplo n.º 11
0
# 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]);
Exemplo n.º 12
0
# Horizontal axis: 0 -> 2.5
# The number of Trotter steps
nbSteps = 25

# The Trotter step size
stepSize = 0.1

# Create the QITE algorithm
qite = xacc.getAlgorithm('qite', {
    'accelerator': qpu,
    'observable': ham,
    'step-size': stepSize,
    'steps': nbSteps
})
# We just need 1 qubit
qiteBuffer = xacc.qalloc(1)
qiteResult = qite.execute(qiteBuffer)

# Create the QLanczos algorithm
qLanczos = xacc.getAlgorithm('QLanczos', {
    'accelerator': qpu,
    'observable': ham,
    'step-size': stepSize,
    'steps': nbSteps
})
qLanczosBuffer = xacc.qalloc(1)
qLanczosResult = qLanczos.execute(qLanczosBuffer)

# Plot the energies
qiteEnergies = qiteBuffer.getInformation('exp-vals')
qLanczosEnergies = qLanczosBuffer.getInformation('exp-vals')
Exemplo n.º 13
0
import xacc

# Get reference to the desired QPU
qpu = xacc.getAccelerator('tnqvm')

# Allocate some qubits
qbits = xacc.qalloc(4)

# Create the H2 4 qubit hamiltonian
# note, first run 'python3 -m xacc --benchmark-install chemistry'
hamiltonianService = xacc.serviceRegistry.get_service('hamiltonian_generator',
                                                      'xaccKernelH2')
obs = hamiltonianService.generate({})

# Create the UCC-1 ansatz
ansatzService = xacc.serviceRegistry.get_service('ansatz_generator', 'ucc1')
ucc1 = ansatzService.generate({'x-gates': [0, 1]}, 4)

# Create the RDM Purification decorator error mitigation strategy
# and give it the fermionic representation
qpu_decorator = xacc.getAcceleratorDecorator('rdm-purification', qpu)
qpu_decorator.initialize({'fermion-observable': obs})

# Let's use the NLOpt optimizer
opt = xacc.getOptimizer('nlopt')

# Create the VQE algorithm
vqe = xacc.getAlgorithm(
    'vqe', {
        'ansatz': ucc1,
        'accelerator': qpu_decorator,
Exemplo n.º 14
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)
Exemplo n.º 15
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')
Exemplo n.º 16
0
    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
Exemplo n.º 17
0
    def execute(self, global_buffer, features, W, bv, bh, options):
        import numpy as np
        import tensorflow as tf

        def set_dwave_couplings(w, bh, bv):
            n_visible = len(bv)
            n_hidden = len(bh)

            # Set Qubo
            Q = {}
            for i in range(n_visible):
                Q[(i, i)] = -1 * bv[i]
            for i in range(n_hidden):
                Q[(i + n_visible, i + n_visible)] = -1 * bh[i]
            for i in range(n_visible):
                for j in range(n_hidden):
                    Q[(i, n_visible + j)] = -1 * w[i][j]

            return Q

        def gibbs_sample(k, x, h, W, bh, bv):
            """
            run sampling k times and return the visible and hidden outputs
            """
            import tensorflow as tf

            def gibbs_step(xk):
                """ single gibbs step """
                # visible values -> hidden values
                xk = tf.cast(xk, tf.float32)
                hk = sample(tf.sigmoid(tf.matmul(xk, W) + bh))
                # hidden values -> visible values
                xk = sample(tf.sigmoid(tf.matmul(hk, tf.transpose(W)) + bv))
                return xk, hk

            for _ in range(k):
                x, h = gibbs_step(x)
            return x, h

        beta = 1.
        w = W.numpy()
        hidden_bias = bh.numpy()[0]
        visible_bias = bv.numpy()[0]
        n_hidden = len(hidden_bias)
        n_visible = len(visible_bias)

        backend = options['backend'] if 'backend' in options else 'dwave-neal'
        save_embed = options['save_embed'] if 'save_embed' in options else False
        load_embed = options['load_embed'] if 'load_embed' in options else None
        n_samples = options['n-samples'] if 'n-samples' in options else 100
        num_gibbs_steps = options[
            'n-gibbs-steps'] if 'n-gibbs-steps' in options else 0

        j = w / beta
        hh = hidden_bias / beta
        hv = visible_bias / beta

        # Set Qubo
        Q = set_dwave_couplings(j, hh, hv)
        QIR = xacc.annealing.create_composite_from_qubo(Q)
        QIR.setTag("qubo")

        qpu = xacc.getAccelerator(backend, {
            'shots': n_samples,
            'mode': 'qubo'
        })
        qbits = xacc.qalloc()
        if options['embedding'] is not None:
            qbits.addExtraInfo('embedding', options['embedding'])

        qpu.execute(qbits, QIR)

        global_buffer.appendChild(qbits.name(), qbits)
        # convert observed bit strings to
        # samples array
        s = []
        measurements = qbits.getMeasurementCounts()
        for k, v in measurements.items():
            arr = np.array(list(map(int, k)))
            for i in range(v):
                s.append(arr)

        samples = np.stack(s, axis=0)
        num_occurrences = np.ones(n_samples, dtype=int)

        visibles = samples[:, :n_visible]
        hidden = samples[:, n_visible:n_visible + n_hidden]
        visibles = np.repeat(visibles, num_occurrences, axis=0)
        hidden = np.repeat(hidden, num_occurrences, axis=0)
        visibles, hidden = gibbs_sample(num_gibbs_steps, visibles, hidden, w,
                                        bh, bv)
        sum_v = np.sum(visibles, axis=0)
        sum_h = np.sum(hidden, axis=0)
        sum_vh = np.matmul(np.transpose(visibles), hidden)
        sum_v = tf.reshape(tf.Variable(sum_v, dtype=tf.float32),
                           (1, n_visible))
        sum_h = tf.reshape(tf.Variable(sum_h, dtype=tf.float32), (1, n_hidden))
        sum_vh = tf.Variable(sum_vh, dtype=tf.float32)

        expectation_W = sum_vh / float(n_samples)
        expectation_v = sum_v / float(n_samples)
        expectation_h = sum_h / float(n_samples)
        return expectation_W, expectation_v, expectation_h
    optimizer = xacc.getIRTransformation('quantum-control')
    optimizer.apply(
        program,
        qpu,
        {
            # Using the Python-contributed pulse optimizer
            # This will propagate to setOptions() then optimize()
            # calls on the optimizer implementation.
            # Note: this is currently doing nothing
            'method': 'krotov',
            'max-time': T
        })

    # Verify the result
    # Run the simulation of the optimized pulse program
    qubitReg = xacc.qalloc(1)
    qpu.execute(qubitReg, program)
    print(qubitReg)
    # Retrieve time-stepping raw data
    csvFile = qubitReg['csvFile']
    data = np.genfromtxt(csvFile, delimiter=',', dtype=float, names=True)
    fig, ax = plt.subplots(2, 1, sharex=True, figsize=(8, 5))
    plt.tight_layout()
    ax[0].plot(data['Time'], data['Channel0'], 'b', label='$D_0(t)$')
    ax[1].plot(data['Time'], data['X0'], 'b', label='$\\langle X \\rangle$')
    ax[1].plot(data['Time'], data['Y0'], 'g', label='$\\langle Y \\rangle$')
    ax[1].plot(data['Time'], data['Z0'], 'r', label='$\\langle Z \\rangle$')
    ax[1].plot(data['Time'], data['Population0'], 'k', label='$Prob(1)$')

    # ax[0].set_xlim([0, 5])
    # ax[0].set_ylim([-0.1, 2.0])
Exemplo n.º 19
0
import xacc
import numpy as np

qpu = xacc.getAccelerator('qpp')
ham = xacc.getObservable('pauli', '-5.0 - 0.5 Z0 + 1.0 Z0Z1')
nbQubits = 2
steps = 1
buffer = xacc.qalloc(nbQubits)
nbTotalParams = 4
# The optimizer: nlopt
opt = xacc.getOptimizer('nlopt', { 'initial-parameters': np.random.rand(nbTotalParams)} )

# Create the QAOA algorithm
qaoa = xacc.getAlgorithm('QAOA', {
                        'accelerator': qpu,
                        'observable': ham,
                        'optimizer': opt,
                        'steps': steps,
                        'parameter-scheme': 'Extend'})
# Run
result = qaoa.execute(buffer)
print('Min value = ', buffer.getInformation('opt-val'))
print('Opt-params = ', buffer.getInformation('opt-params'))

# Get the circuit
qaoa_ansatz_std = xacc.createComposite('qaoa')
qaoa_ansatz_std.expand({'nbQubits': nbQubits, 'nbSteps': steps, 'cost-ham': ham,
    'parameter-scheme':'Extend'})
print('Extend parameterized QAOA circuit:')
print(qaoa_ansatz_std)
Exemplo n.º 20
0
def qv_circuits(qubit_lists=None, ntrials=1, qr=None, cr=None):
    """
    Return a list of square quantum volume circuits (depth=width)

    The qubit_lists is specified as a list of qubit lists. For each
    set of qubits, circuits the depth as the number of qubits in the list
    are generated

    Args:
        qubit_lists (list): list of list of qubits to apply qv circuits to. Assume
            the list is ordered in increasing number of qubits
        ntrials (int): number of random iterations
        qr (QuantumRegister): quantum register to act on (if None one is created)
        cr (ClassicalRegister): classical register to measure to (if None one is created)

    Returns:
        tuple: A tuple of the type (``circuits``, ``circuits_nomeas``) wheere:
            ``circuits`` is a list of lists of circuits for the qv sequences
            (separate list for each trial) and `` circuitss_nomeas`` is the
            same circuits but with no measurements for the ideal simulation
    """

    circuits = [[] for e in range(ntrials)]
    circuits_nomeas = [[] for e in range(ntrials)]

    # get the largest qubit number out of all the lists (for setting the
    # register)

    depth_list = [len(qubit_list) for qubit_list in qubit_lists]

    # go through for each trial
    for trial in range(ntrials):

        # go through for each depth in the depth list
        for depthidx, depth in enumerate(depth_list):

            n_q_max = np.max(qubit_lists[depthidx])

            provider = xacc.getIRProvider('quantum')

            qr = xacc.qalloc(int(n_q_max + 1))
            qr2 = xacc.qalloc(int(depth))
            #cr = qiskit.ClassicalRegister(int(depth), 'cr')

            qc = provider.createComposite('qv_depth_%d_trial_%d' %
                                          (depth, trial))
            qc2 = provider.createComposite('qv_depth_%d_trial_%d' %
                                           (depth, trial))

            # build the circuit
            for _ in range(depth):
                # Generate uniformly random permutation Pj of [0...n-1]
                perm = np.random.permutation(depth)
                # For each pair p in Pj, generate Haar random SU(4)
                for k in range(int(np.floor(depth / 2))):
                    unitary = random_unitary(4)
                    pair = int(perm[2 * k]), int(perm[2 * k + 1])
                    haar = provider.createInstruction(unitary, [
                        qr[qubit_lists[depthidx][pair[0]]],
                        qr[qubit_lists[depthidx][pair[1]]]
                    ])
                    qc.addInstructions([haar])
                    qc2.addInstructions([haar])

            # append an id to all the qubits in the ideal circuits
            # to prevent a truncation error in the statevector
            # simulators
            #qc2.u1(0, qr2)

            circuits_nomeas[trial].append(qc2)

            # add measurement
            for qind, qubit in enumerate(qubit_lists[depthidx]):
                qc.measure(qr[qubit], cr[qind])

            circuits[trial].append(qc)

    return circuits, circuits_nomeas
Exemplo n.º 21
0
import xacc,sys, numpy as np

xacc.set_verbose(True)
# Get access to the desired QPU and
# allocate some qubits to run on
qpu = xacc.getAccelerator('qsim')
graph = xacc.getGraph("boost-digraph")
nbNodes = 3
random_graph = graph.gen_random_graph(nbNodes, 3.0 / nbNodes)
print(random_graph)
nbSteps = 1
buffer = xacc.qalloc(nbNodes)
opt = xacc.getOptimizer('nlopt')
# Create QAOA
qaoa = xacc.getAlgorithm('QAOA', {
                        'accelerator': qpu,
                        'graph': random_graph,
                        'optimizer': opt,
                        'steps': nbSteps,
                        'parameter-scheme': 'Standard'
                        })
result = qaoa.execute(buffer)
print("Max-cut val:", buffer["opt-val"])
Exemplo n.º 22
0
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)
Exemplo n.º 23
0
import xacc, numpy as np

nAngles = 10

# Get the local-ibm and tnqvm accelerators
# and allocate some qubits for execution on each
qpu = xacc.getAccelerator('aer', {
    'shots': 1024,
    'backend': 'ibmq_johannesburg',
    'readout_error': True
})
tnqvm = xacc.getAccelerator('tnqvm')
buffer = xacc.qalloc(2)
tnqvmBuffer = xacc.qalloc(2)

# Turn on readout error correction by decorating
# the local-ibm accelerator
qpu = xacc.getAcceleratorDecorator('ro-error', qpu)

# Construct the Hamiltonian
ham = xacc.getObservable(
    'pauli', '5.907 - 2.1433 X0X1 - 2.1433 Y0Y1 + .21829 Z0 - 6.125 Z1')


# Define the ansatz and decorate it to indicate
# you'd like to run VQE
@xacc.qpu(algo='energy', accelerator=qpu, observable=ham)
def ansatz(buffer, t0):
    X(buffer[0])
    Ry(buffer[1], t0)
    CNOT(buffer[1], buffer[0])
Exemplo n.º 24
0
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))


Exemplo n.º 25
0
    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)