Exemple #1
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
Exemple #2
0
# assembling pulse programs (schedules) and running simulation.

import xacc, sys, numpy as np

# Helper to create a centered Gaussian pulse:
def gaussianCalc(in_time, in_amp, in_center, in_sigma):
    return in_amp*np.exp(-(in_time - in_center)**2/ 2.0 / (in_sigma**2.0))

# Construct a sample pulse
nbSamples = 160
my_pulse = np.zeros(nbSamples)
amp = 0.1
for i in range(nbSamples):
    my_pulse[i] = gaussianCalc(i, amp, nbSamples/2, nbSamples/4)

provider = xacc.getIRProvider("quantum")
program = provider.createComposite("gaussian")
# Create the pulse instructions
gaussian = provider.createInstruction("gaussian", [0], [], { "channel" : "d0", "samples": my_pulse})
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)
Exemple #3
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
Exemple #4
0
(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)

pool = xacc.quantum.getOperatorPool("singlet-adapted-uccsd")
pool.optionalParameters({"n-electrons": 2})
pool.generate(buffer.size())
provider = xacc.getIRProvider('quantum')
ansatz = provider.createComposite('initial-state')
ansatz.addInstruction(provider.createInstruction('X', [0]))
ansatz.addInstruction(provider.createInstruction('X', [2]))
ansatz.addVariable("x0")
for inst in pool.getOperatorInstructions(2, 0).getInstructions():
    ansatz.addInstruction(inst)
kernel = ansatz.eval([0.0808])

qeom = xacc.getAlgorithm(
    'qeom', {
        'accelerator': accelerator,
        'observable': H,
        'ansatz': kernel,
        'n-electrons': 2
    })
Exemple #5
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