Example #1
0
 def from_qasm(self, qasm_str):
     xacc_ir = xacc.getCompiler('staq').compile(qasm_str).getComposites()[0]
     pyxasm = xacc.getCompiler('pyxasm').translate(xacc_ir)
     pyxasm = pyxasm.replace('__translate_qrg__', self.qreg_name)
     pyxasm = '\n'.join(self.TAB+line for line in pyxasm.split('\n'))
     processed_str = pyxasm        
     self.qjit_str += processed_str
Example #2
0
    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)
Example #3
0
    def apply(self, program, accelerator, options):
        # Import qiskit modules here so that users
        # who don't have qiskit can still use rest of xacc
        from qiskit import QuantumCircuit, transpile
        from qiskit.transpiler import PassManager
        from qiskit.transpiler.passes import CXCancellation

        # Map CompositeInstruction program to OpenQasm string
        openqasm_compiler = xacc.getCompiler('openqasm')
        src = openqasm_compiler.translate(program).replace('\\', '')

        # Create a QuantumCircuit
        circuit = QuantumCircuit.from_qasm_str(src)

        # Create the PassManager and run the pass
        pass_manager = PassManager()
        pass_manager.append(CXCancellation())
        out_circuit = transpile(circuit, pass_manager=pass_manager)

        # Map the output to OpenQasm and map to XACC IR
        out_src = out_circuit.qasm()
        out_src = '__qpu__ void ' + program.name(
        ) + '(qbit q) {\n' + out_src + "\n}"
        out_prog = openqasm_compiler.compile(out_src,
                                             accelerator).getComposites()[0]

        # update the given program CompositeInstruction reference
        program.clear()
        for inst in out_prog.getInstructions():
            program.addInstruction(inst)

        return
Example #4
0
 def openqasm(self, *args):
     """
     Return an OpenQasm string representation of this 
     quantum kernel.
     """
     kernel = self.extract_composite(*args)
     staq = xacc.getCompiler('staq')
     return staq.translate(kernel)
Example #5
0
    def apply(self, program, accelerator, options):
        # Import qiskit modules here so that users
        # who don't have qiskit can still use rest of xacc
        from pyzx.circuit import Circuit
        from pyzx import simplify, extract, optimize

        # Map CompositeInstruction program to OpenQasm string
        openqasm_compiler = xacc.getCompiler('staq')
        src = openqasm_compiler.translate(program).replace('\\','')
      
        measures = []
        lines = src.split('\n')
        for l in lines:
            if 'measure' in l or 'creg' in l:
                measures.append(l)
        
        c = Circuit.from_qasm(src)
        g = c.to_graph()
        
        simplify.full_reduce(g,quiet=True)
        c2 = extract.extract_circuit(g)
        c3 = optimize.basic_optimization(c2.to_basic_gates())
        c3 = c3.to_basic_gates()
        c3 = c3.split_phase_gates()
        output = c3.to_qasm()
        for measure in measures:
            output += '\n' + measure

        # Map the output to OpenQasm and map to XACC IR
        out_prog = openqasm_compiler.compile(output, accelerator).getComposites()[0]

        # update the given program CompositeInstruction reference
        program.clear()
        for inst in out_prog.getInstructions():
            program.addInstruction(inst)

        return
Example #6
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"
Example #7
0
    def execute_one_qasm(self, buffer, program):
        import cirq

        staq = xacc.getCompiler('staq')
        cirq_code = staq.translate(program, {'lang-type':'cirq'})
        cirq_code = cirq_code[0:len(cirq_code)-15]
        exec(cirq_code, globals(), globals())
        # Now we have a circuit variable for execution with Cirq
        simulator = cirq.Simulator()
        result = simulator.run(circuit, repetitions=self.shots)
        import re
        qbit2keys = {}
        for qq in q:
            m = re.search(r"\[([0-9_]+)\]", str(qq))
            qbit2keys[int(m.group(1))] = str(qq).replace('[', '_c[')

        bs = []
        for i in range(self.shots):
            b = [0 for i in range(buffer.size())]
            for k,v in qbit2keys.items():
                b[k] = result._measurements[v][i][0]
            bs.append(''.join([str(bb) for bb in b]))

        [buffer.appendMeasurement(bb) for bb in bs]
Example #8
0
 def initialize(self, options):
     self.openqasm_compiler = xacc.getCompiler('staq')
     self.openqasm_compiler.setExtraOptions({'no-optimize': True})
     return
Example #9
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)
Example #10
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

        """
        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)
if loadResult is True:
    qpu = xacc.getAccelerator('QuaC', {
        'system-model': model.name(),
        'logging-period': 0.1
    })
    channelConfigs = xacc.BackendChannelConfigs()
    T = 5.0
    channelConfigs.dt = 0.01
    # Krotov will be able to compute things even without resonance
    # i.e. it will figure out how to modulate things into resonance (if needed)
    channelConfigs.loFregs_dChannels = [0.0]
    model.setChannelConfigs(channelConfigs)

    # Get the XASM compiler
    xasmCompiler = xacc.getCompiler('xasm')
    # Composite to be transform to pulse: X gate = H-Z-H
    ir = xasmCompiler.compile(
        '''__qpu__ void f(qbit q) {
        Ry(q[0], pi/2);
        X(q[0]); 
    }''', qpu)
    program = ir.getComposites()[0]

    # Run the pulse IRTransformation
    optimizer = xacc.getIRTransformation('quantum-control')
    optimizer.apply(
        program,
        qpu,
        {
            # Using the Python-contributed pulse optimizer