Exemplo n.º 1
0
    def __call__(self, *args, **kwargs):
        super().__call__(*args, **kwargs)
        import numpy as np

        execParams = {
            'accelerator': self.qpu,
            'ansatz': self.compiledKernel,
            'observable': self.kwargs["observable"]
        }

        if not isinstance(args[0], xacc.AcceleratorBuffer):
            raise RuntimeError(
                'First argument of an xacc kernel must be the Accelerator Buffer to operate on.'
            )

        buffer = args[0]
        ars = args[1:]
        if len(ars) > 0:
            execParams['parameters'] = list(ars)
        else:
            execParams['parameters'] = random.randrange(-np.pi, np.pi)

        vqe_energy = xacc.getAlgorithm('vqe-energy', execParams)
        vqe_energy.execute(buffer)
        return
Exemplo n.º 2
0
    def __call__(self, *args, **kwargs):
        super().__call__(*args, **kwargs)

        execParams = {'accelerator': self.qpu, 'ansatz': self.compiledKernel, 'observable': self.kwargs["observable"]}
        optParams = {}

        if not isinstance(args[0], xacc.AcceleratorBuffer):
            raise RuntimeError(
                'First argument of an xacc kernel must be the Accelerator Buffer to operate on.')

        buffer = args[0]
        ars = args[1:]
        if len(ars) > 0:
            if isinstance(ars,list) or isinstance(ars,tuple):
                # print('ars is a list')
                optParams['initial-parameters'] = ars[0]
            else:
                optParams['initial-parameters'] = list(ars)

        # print(type(ars), optParams['initial-parameters'])
        if 'options' in self.kwargs:
            optParams = self.kwargs['options']

        if 'optimizer' not in self.kwargs:
            self.kwargs['optimizer'] = 'nlopt'

        execParams['optimizer'] = xacc.getOptimizer(self.kwargs['optimizer'], optParams)

        vqe = xacc.getAlgorithm('vqe', execParams)
        vqe.execute(buffer)

        return
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, inputParams):
        """
            Inherited method with algorithm-specific implementation

            Parameters:
                inputParams - a dictionary of input parameters obtained from .ini file

            - sets XACC VQE task to 'compute-energy'
            - executes a parameter-sweep
        """
        super().execute(inputParams)
        pi = 3.141592653589793
        self.vqe_options_dict['task'] = 'compute-energy'

        if inputParams['upper-bound'] == 'pi':
            up_bound = pi
        else:
            up_bound = ast.literal_eval(inputParams['upper-bound'])

        if inputParams['lower-bound'] == '-pi':
            low_bound = -pi
        else:
            low_bound = ast.literal_eval(inputParams['lower-bound'])

        num_params = ast.literal_eval(inputParams['num-params'])

        self.energies = []
        self.angles = []
        for param in self.linspace(low_bound, up_bound, num_params):
            print(param)
            self.vqe_options_dict['parameters'] = [param]
            vqe_energy = xacc.getAlgorithm('vqe-energy', self.vqe_options_dict)

            self.angles.append(param)
            # self.vqe_options_dict['vqe-params'] = str(param)
            vqe_energy.execute(self.buffer)

            energy = self.buffer.getInformation('opt-val')
            #xaccvqe.execute(self.op, self.buffer, **self.vqe_options_dict).energy
            # if 'rdm-purification' in self.qpu.name():
            #     p = self.buffer.getAllUnique('parameters')
            #     ind = len(p) - 1
            #     children = self.buffer.getChildren('parameters', [param])
            #     print(children[0])
            #     energy = children[1].getInformation('purified-energy')

            self.energies.append(energy)

        self.buffer.addExtraInfo('vqe-energies', self.energies)
        self.buffer.addExtraInfo('vqe-angles', self.angles)
        self.buffer.addExtraInfo('vqe-energy', min(self.energies))
        return self.buffer
Exemplo n.º 5
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.º 6
0
    def execute(self, inputParams):
        """
            Inherited method with algorithm-specific implementation

            Parameters:
                inputParams - a dictionary of input parameters obtained from .ini file

        """
        super().execute(inputParams)

        if not isinstance(self.optimizer, xacc.Optimizer):
            self.optimizer.optimize(self.buffer, self.optimizer_options,
                                    self.vqe_options_dict)
        else:
            vqe = xacc.getAlgorithm('vqe', self.vqe_options_dict)
            vqe.execute(self.buffer)

        return self.buffer
Exemplo n.º 7
0
    def execute(self, inputParams):
        """
            Inherited method with algorithm-specific implementation

            Parameters:
                inputParams - a dictionary of input parameters obtained from .ini file

            - sets XACC VQE task to 'compute-energy'
        """
        super().execute(inputParams)

        algo = xacc.getAlgorithm("vqe-energy", self.vqe_options_dict)
        algo.execute(self.buffer)

        # if 'rdm-purification' in self.qpu.name():
        #     p = self.buffer.getAllUnique('parameters')
        #     child = self.buffer.getChildren('parameters', p[0])
        #     energy = child[1].getInformation('purified-energy')
        #     self.buffer.addExtraInfo('vqe-energy', energy)

        return self.buffer
Exemplo n.º 8
0
    def __call__(self, *args, **kwargs):
        super().__call__(*args, **kwargs)

        execParams = {
            'accelerator': self.qpu,
            'ansatz': self.compiledKernel,
            'target_dist': self.kwargs['target_dist'],
            'loss': self.kwargs['loss']
        }
        if 'gradient' in self.kwargs:
            execParams['gradient'] = self.kwargs['gradient']
        optParams = {}

        if not isinstance(args[0], xacc.AcceleratorBuffer):
            raise RuntimeError(
                'First argument of an xacc kernel must be the Accelerator Buffer to operate on.'
            )

        buffer = args[0]
        ars = args[1:]
        if len(ars) > 0:
            optParams['initial-parameters'] = list(ars)

        if 'options' in self.kwargs:
            optParams = self.kwargs['options']

        if 'optimizer' not in self.kwargs:
            self.kwargs['optimizer'] = 'nlopt'

        if self.kwargs['optimizer'] in self.vqe_optimizers:
            optimizer = self.vqe_optimizers[self.kwargs['optimizer']]
            optimizer.optimize(buffer, optParams, execParams)
        else:
            execParams['optimizer'] = xacc.getOptimizer(
                self.kwargs['optimizer'], optParams)

        ddcl = xacc.getAlgorithm('ddcl', execParams)
        ddcl.execute(buffer)

        return
Exemplo n.º 9
0
(-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
    })

qeom.execute(buffer)
spectrum = buffer.getInformation("excitation-energies")
print(spectrum)
Exemplo n.º 10
0
xacc.set_verbose(True)
# Choose the QPU on which to
# characterize the process matrix for a Hadamard
qpu = xacc.getAccelerator('aer')

# 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.]
Exemplo n.º 11
0
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")
# Manual construction:
# Triangular graph
graph.addVertex({'name': 'v1'})
graph.addVertex({'name': 'v2'})
graph.addVertex({'name': 'v3'})

graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addEdge(1, 2)

print(graph)

nbSteps = 1
buffer = xacc.qalloc(3)
opt = xacc.getOptimizer('nlopt')
# Create QAOA
qaoa = xacc.getAlgorithm(
    'maxcut-qaoa', {
        'accelerator': qpu,
        'graph': graph,
        'optimizer': opt,
        'steps': nbSteps,
        'shuffle-terms': True
    })
result = qaoa.execute(buffer)
print("Max-cut val:", buffer["opt-val"])
Exemplo n.º 12
0
# 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)

# Create the QPE algorithm
qpe = xacc.getAlgorithm('QPE', {
    'accelerator': qpu,
    'oracle': oracle,
    'state-preparation': statePrep
})

qpe.execute(buffer)
# We should only get the bit string of |100> = 1
# i.e. phase value of 1/2^3 = 1/8.
print(buffer)
Exemplo n.º 13
0
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,
        'observable': obs,
        'optimizer': opt
    })

# Execute
vqe.execute(qbits)

# qbits buffer has all results, print(qbits)
# to see it all
print(qbits.getInformation('opt-val'))
Exemplo n.º 14
0
import xacc

accelerator = xacc.getAccelerator("qpp")

H = xacc.getObservable(
    'pauli',
    '0.2976 + 0.3593 Z0 - 0.4826 Z1 + 0.5818 Z0 Z1 + 0.0896 X0 X1 + 0.0896 Y0 Y1'
)

expansion = 'Cioslowski'

order = 2

provider = xacc.getIRProvider('quantum')
ansatz = provider.createComposite('initial-state')
ansatz.addInstruction(provider.createInstruction('X', [0]))

buffer = xacc.qalloc(2)

qcmx = xacc.getAlgorithm(
    'qcmx', {
        'accelerator': accelerator,
        'observable': H,
        'ansatz': ansatz,
        'cmx-order': order,
        'expansion-type': expansion
    })

qcmx.execute(buffer)
print('Energy = ', buffer.getInformation('opt-val'))
Exemplo n.º 15
0
import xacc

qpu = xacc.getAccelerator('tnqvm')
optimizer = xacc.getOptimizer('nlopt', {'nlopt-optimizer': 'l-bfgs'})
buffer = xacc.qalloc(4)

geom = '''
H  0.000000   0.0      0.0
H   0.0        0.0  .7474
'''
H = xacc.getObservable('pyscf', {'basis': 'sto-3g', 'geometry': geom})
print(H.toString())

adapt = xacc.getAlgorithm(
    'adapt-vqe', {
        'accelerator': qpu,
        'optimizer': optimizer,
        'observable': H,
        'nElectrons': 2,
        'gradient-strategy': 'parameter-shift-gradient',
        'print-operators': True,
        'threshold': 1.0e-2,
        'print-threshold': 1.0e-10,
        'maxiter': 2,
        'pool': "singlet-adapted-uccsd"
    })
# execute
adapt.execute(buffer)
Exemplo n.º 16
0
qpu = xacc.getAccelerator('tnqvm:exatn', {
    "exp-val-by-conjugate": True,
    "max-qubit": 2
})
print("QPU:", qpu.name())
buffer = xacc.qalloc(4)
geom = '''
Na  0.000000   0.0      0.0
H   0.0        0.0  1.914388
'''
fo = [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
ao = [5, 9, 15, 19]
H = xacc.getObservable(
    'pyscf', {
        'basis': 'sto-3g',
        'geometry': geom,
        'frozen-spin-orbitals': fo,
        'active-spin-orbitals': ao
    })
# print(H.toString())
opt = xacc.getOptimizer('nlopt')
vqe = xacc.getAlgorithm('vqe', {
    'ansatz': ansatz,
    'accelerator': qpu,
    'observable': H,
    'optimizer': opt
})
# # xacc.set_verbose(True)
energy = vqe.execute(buffer, [])
print('Energy = ', energy)
Exemplo n.º 17
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.º 18
0
# 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')
cnot = provider.createInstruction('CX', [0, 1])
circuit.addInstruction(cnot)

# Create the Algorithm, give it the circuit
# to characterize and the backend to target
qpt = xacc.getAlgorithm('qpt', {
    'circuit': circuit,
    'accelerator': qpu,
    'qubit-map': [1, 2]
})

# Allocate a qubit, this will
# store our tomography results
buffer = xacc.qalloc(2)

# Execute
qpt.execute(buffer)

theory_cx = [
    1., 0., 0., 1., 1., 0., 0., -1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
    0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
    0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 1., 0., 0.,
    -1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 1., 0., 0., -1., 0.,
Exemplo n.º 19
0
# There are 7 gamma terms (non-identity) in the cost Hamiltonian
# and 4 beta terms for mixer Hamiltonian
nbParamsPerStep = 7 + 4

# The number of steps (often referred to as 'p' parameter):
# alternating layers of mixer and cost Hamiltonian exponential.
nbSteps = 4

# Total number of params
nbTotalParams = nbParamsPerStep * nbSteps

# Init params randomly:
initParams = np.random.rand(nbTotalParams)

# The optimizer: nlopt
opt = xacc.getOptimizer('nlopt', {'initial-parameters': initParams})

# Create the QAOA algorithm
qaoa = xacc.getAlgorithm('QAOA', {
    'accelerator': qpu,
    'observable': ham,
    'optimizer': opt,
    'steps': nbSteps
})

result = qaoa.execute(buffer)

# Expected result: ~ -11
# Ref: https://docs.entropicalabs.io/qaoa/notebooks/6_solvingqubowithqaoa
print('Min QUBO value = ', buffer.getInformation('opt-val'))
Exemplo n.º 20
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.º 21
0
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,
        'accelerator': qpu,
        'target_dist': [0., 0., 0., 1.],
        'persist-buffer': True,
        'optimizer': optimizer,
        'loss': 'js',
        'gradient': 'js-parameter-shift'
    })
# execute
ddcl.execute(qbits)

# Note that the buffer file was persisted to
# the hidden file with name
# .ddcl_KERNELNAME_TIMESTAMP.ab, which in this case looks like
# .ddcl_qubit2_depth1_2019-10-.....ab -> depends on time you ran this :)
Exemplo n.º 22
0
.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,
        'target_dist': [.5, .5],
        'optimizer': optimizer,
        'loss': 'js',
        'gradient': 'js-parameter-shift'
    })
# execute
ddcl.execute(qbits)

print(qbits.keys())
print(qbits['opt-val'])
print(qbits['opt-params'])
Exemplo n.º 23
0
# Construct the Hamiltonian as an XACC PauliOperator
ham = xacc.getObservable('pauli', '0.70710678118 X0 + 0.70710678118 Z0')

# See Fig. 2 (e) of https://www.nature.com/articles/s41567-019-0704-4
# 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)
Exemplo n.º 24
0
import xacc

xacc.set_verbose(True)
accelerator = xacc.getAccelerator("qpp")
buffer = xacc.qalloc(4)
optimizer = xacc.getOptimizer('nlopt', {'nlopt-optimizer': 'l-bfgs'})
pool = "multi-qubit-qaoa"
nLayers = 2
subAlgo_qaoa = "QAOA"
H = xacc.getObservable(
    'pauli',
    '-5.0 - 0.5 Z0 - 1.0 Z2 + 0.5 Z3 + 1.0 Z0 Z1 + 2.0 Z0 Z2 + 0.5 Z1 Z2 + 2.5 Z2 Z3'
)
adapt = xacc.getAlgorithm(
    'adapt', {
        'accelerator': accelerator,
        'observable': H,
        'optimizer': optimizer,
        'pool': pool,
        'maxiter': nLayers,
        'sub-algorithm': subAlgo_qaoa
    })

adapt.execute(buffer)
Exemplo n.º 25
0
(-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)

adapt = xacc.getAlgorithm(
    'adapt', {
        'accelerator': qpu,
        'optimizer': optimizer,
        'observable': H,
        'n-electrons': 2,
        'maxiter': 2,
        'sub-algorithm': 'vqe',
        'pool': 'qubit-pool'
    })
# execute
adapt.execute(buffer)
Exemplo n.º 26
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.º 27
0
# alternating layers of mixer and cost Hamiltonian exponential.
nbSteps = 4

# Total number of params
nbTotalParams = nbParamsPerStep * nbSteps

# Init params randomly:
initParams = np.random.rand(nbTotalParams)

# The optimizer: nlopt
opt = xacc.getOptimizer('nlopt', {
    'initial-parameters': initParams,
    'nlopt-optimizer': 'l-bfgs'
})

# Create the QAOA algorithm
qaoa = xacc.getAlgorithm(
    'QAOA', {
        'accelerator': qpu,
        'observable': ham,
        'optimizer': opt,
        'steps': nbSteps,
        'gradient_strategy': 'parameter-shift-gradient'
    })

result = qaoa.execute(buffer)

# Expected result: ~ -11
# Ref: https://docs.entropicalabs.io/qaoa/notebooks/6_solvingqubowithqaoa
print('Min QUBO value = ', buffer.getInformation('opt-val'))
Exemplo n.º 28
0
# We need 2 qubits for this case (H2)
buffer = xacc.qalloc(2)

# Horizontal axis: 0 -> 0.3 (step = 0.05)
# The number of Trotter steps
nbSteps = 6

# The Trotter step size
stepSize = 0.05

# Create the QITE algorithm
qite = xacc.getAlgorithm(
    'qite', {
        'accelerator': qpu,
        'observable': ham,
        'step-size': stepSize,
        'steps': nbSteps,
        'ansatz': prep_circuit
    })

result = qite.execute(buffer)

# Expected result: ~ -1.74886
print('Min energy value = ', buffer.getInformation('opt-val'))
E = buffer.getInformation('exp-vals')
# Reproduce Fig. 3(a) of https://arxiv.org/pdf/1912.06226.pdf
plt.plot(np.arange(0, nbSteps + 1) * stepSize, E, 'ro-', label='XACC QITE')
plt.ylim((-2.0, -0.25))
plt.yticks(np.arange(-2.0, -0.25, step=0.25))
plt.grid()
plt.show()