Exemple #1
0
def _parse_common_args(backend, qobj_id, qobj_header, shots, memory,
                       max_credits, seed_simulator, **run_config):
    """Resolve the various types of args allowed to the assemble() function through
    duck typing, overriding args, etc. Refer to the assemble() docstring for details on
    what types of inputs are allowed.

    Here the args are resolved by converting them to standard instances, and prioritizing
    them in case a run option is passed through multiple args (explicitly setting an arg
    has more priority than the arg set by backend)

    Returns:
        RunConfig: a run config, which is a standardized object that configures the qobj
            and determines the runtime environment.

    Raises:
        QiskitError: if the memory arg is True and the backend does not support
        memory.
    """
    # grab relevant info from backend if it exists
    backend_config = None
    if backend:
        backend_config = backend.configuration()
        # check for memory flag applied to backend that does not support memory
        if memory and not backend_config.memory:
            raise QiskitError("memory not supported by backend {}".format(
                backend_config.backend_name))

    # an identifier for the Qobj
    qobj_id = qobj_id or str(uuid.uuid4())

    # The header that goes at the top of the Qobj (and later Result)
    # we process it as dict, then write entries that are not None to a QobjHeader object
    qobj_header = qobj_header or {}
    if isinstance(qobj_header, QobjHeader):
        qobj_header = qobj_header.to_dict()
    backend_name = getattr(backend_config, 'backend_name', None)
    backend_version = getattr(backend_config, 'backend_version', None)
    qobj_header = {
        **dict(backend_name=backend_name, backend_version=backend_version),
        **qobj_header
    }
    qobj_header = QobjHeader(
        **{k: v
           for k, v in qobj_header.items() if v is not None})

    # create run configuration and populate
    run_config_dict = dict(shots=shots,
                           memory=memory,
                           max_credits=max_credits,
                           seed_simulator=seed_simulator,
                           **run_config)

    return qobj_id, qobj_header, run_config_dict
Exemple #2
0
 def test_snapshot_instruction_from_dict(self):
     """Test snapshot instruction from dict."""
     expected_qobj = QasmQobj(
         qobj_id='12345',
         header=QobjHeader(),
         config=QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10),
         experiments=[
             QasmQobjExperiment(instructions=[
                 QasmQobjInstruction(name='u1', qubits=[1], params=[0.4]),
                 QasmQobjInstruction(name='u2', qubits=[1], params=[0.4, 0.2]),
                 QasmQobjInstruction(name='snapshot', qubits=[1],
                                     snapshot_type='statevector',
                                     label='my_snap')
             ])
         ]
     )
     qobj_dict = {
         'qobj_id': '12345',
         'type': 'QASM',
         'schema_version': '1.1.0',
         'header': {},
         'config': {'max_credits': 10, 'memory_slots': 2, 'shots': 1024},
         'experiments': [
             {'instructions': [
                 {'name': 'u1', 'params': [0.4], 'qubits': [1]},
                 {'name': 'u2', 'params': [0.4, 0.2], 'qubits': [1]},
                 {'name': 'snapshot', 'qubits': [1],
                  'snapshot_type': 'statevector', 'label': 'my_snap'}
             ]}
         ],
     }
     self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict))
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qasm_circ = QuantumCircuit.from_qasm_file(self.qasm_filename)
        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(2, 'c')
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.measure(qr[0], cr[0])
        self.qc = qc

        # create qobj
        dag = DAGCircuit.fromQuantumCircuit(self.qc)
        json_circuit = DagUnroller(dag, JsonBackend(dag.basis)).execute()
        compiled_circuit1 = QobjExperiment.from_dict(json_circuit)

        dag = DAGCircuit.fromQuantumCircuit(self.qasm_circ)
        json_circuit = DagUnroller(dag, JsonBackend(dag.basis)).execute()
        compiled_circuit2 = QobjExperiment.from_dict(json_circuit)

        self.qobj = Qobj(qobj_id='test_qobj',
                         config=QobjConfig(shots=2000,
                                           memory_slots=1,
                                           max_credits=3,
                                           seed=1111),
                         experiments=[compiled_circuit1, compiled_circuit2],
                         header=QobjHeader(backend_name='qasm_simulator'))
        self.qobj.experiments[0].header.name = 'test_circuit1'
        self.qobj.experiments[0].config = QobjItem(
            basis_gates='u1,u2,u3,cx,id')
        self.qobj.experiments[1].header.name = 'test_circuit2'
        self.qobj.experiments[1].config = QobjItem(
            basis_gates='u1,u2,u3,cx,id')
        self.backend = QasmSimulator()
 def test_qobj_to_circuits_with_nothing(self):
     """Verify that qobj_to_circuits returns None without any data."""
     qobj = QasmQobj(qobj_id='abc123',
                     config=QasmQobjConfig(),
                     header=QobjHeader(),
                     experiments=[])
     self.assertIsNone(qobj_to_circuits(qobj))
    def setUp(self):
        qasm_filename = self._get_resource_path('qasm/example.qasm')
        qasm_ast = Qasm(filename=qasm_filename).parse()
        qasm_dag = Unroller(qasm_ast, DAGBackend()).execute()
        qasm_json = DagUnroller(qasm_dag,
                                JsonBackend(qasm_dag.basis)).execute()

        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(2, 'c')
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.measure(qr[0], cr[0])
        qc_dag = DAGCircuit.fromQuantumCircuit(qc)
        qc_json = DagUnroller(qc_dag, JsonBackend(qc_dag.basis)).execute()

        # create qobj
        compiled_circuit1 = QobjExperiment.from_dict(qc_json)
        compiled_circuit2 = QobjExperiment.from_dict(qasm_json)

        self.qobj = Qobj(qobj_id='test_qobj',
                         config=QobjConfig(shots=2000,
                                           memory_slots=1,
                                           max_credits=3,
                                           seed=1111),
                         experiments=[compiled_circuit1, compiled_circuit2],
                         header=QobjHeader(backend_name='qasm_simulator'))
        self.qobj.experiments[0].header.name = 'test_circuit1'
        self.qobj.experiments[1].header.name = 'test_circuit2'
        self.backend = QasmSimulator()
Exemple #6
0
def update_qobj_config(qobj, backend_options=None, noise_model=None):
    """Update a Qobj configuration from options and noise model.

    Args:
        qobj (Qobj): description of job
        backend_options (dict): backend options
        noise_model (NoiseModel): noise model

    Returns:
        Qobj: qobj.
    """
    config = qobj.config.as_dict()

    # Append backend options to configuration.
    if backend_options:
        for key, val in backend_options.items():
            config[key] = val

    # Append noise model to configuration.
    if noise_model:
        config['noise_model'] = noise_model.as_dict(serializable=True)

    # Update the Qobj configuration.
    qobj.config = QobjHeader.from_dict(config)

    return qobj
    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        unroller = unroll.Unroller(
            qasm.Qasm(filename=self.qasm_filename).parse(),
            unroll.JsonBackend([]))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['instructions'] = [
            op for op in circuit['instructions'] if op['name'] != 'measure'
        ]
        circuit = QobjExperiment.from_dict(circuit)
        circuit.config = QobjItem(coupling_map=None,
                                  basis_gates=None,
                                  layout=None,
                                  seed=self.seed)
        circuit.header.name = 'test'

        qobj = Qobj(
            id='unitary',
            config=QobjConfig(shots=1, register_slots=6, max_credits=None),
            experiments=[circuit],
            header=QobjHeader(backend_name='local_unitary_simulator_py'))
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
        # delimiter=',')
        expected = np.loadtxt(
            self._get_resource_path('example_unitary_matrix.dat'),
            dtype='complex',
            delimiter=',')

        result = UnitarySimulatorPy().run(qobj).result()
        self.assertTrue(
            np.allclose(result.get_unitary('test'), expected, rtol=1e-3))
def update_qobj_config(qobj: Union[QasmQobj, PulseQobj],
                       backend_options: Optional[Dict] = None,
                       noise_model: Any = None) -> Union[QasmQobj, PulseQobj]:
    """Update a ``Qobj`` configuration from backend options and a noise model.

    Args:
        qobj: Description of the job.
        backend_options: Backend options.
        noise_model: Noise model.

    Returns:
        The updated ``Qobj``.
    """
    config = qobj.config.to_dict()

    # Append backend options to configuration.
    if backend_options:
        for key, val in backend_options.items():
            config[key] = val

    # Append noise model to configuration. Overwrites backend option
    if noise_model:
        config['noise_model'] = noise_model

    # Look for noise_models in the config, and try to transform them
    config = _serialize_noise_model(config)

    # Update the Qobj configuration.
    qobj.config = QobjHeader.from_dict(config)

    return qobj
def update_qobj_config(
        qobj: Qobj,
        backend_options: Optional[Dict] = None,
        noise_model: Any = None
) -> Qobj:
    """Update a Qobj configuration from options and noise model.

    Args:
        qobj (Qobj): description of job
        backend_options (dict): backend options
        noise_model (NoiseModel): noise model

    Returns:
        Qobj: qobj.
    """
    config = qobj.config.to_dict()

    # Append backend options to configuration.
    if backend_options:
        for key, val in backend_options.items():
            config[key] = val

    # Append noise model to configuration. Overwrites backend option
    if noise_model:
        config['noise_model'] = noise_model

    # Look for noise_models in the config, and try to transform them
    config = _serialize_noise_model(config)

    # Update the Qobj configuration.
    qobj.config = QobjHeader.from_dict(config)

    return qobj
Exemple #10
0
    def setUp(self):
        self.valid_qobj = QasmQobj(
            qobj_id='12345',
            header=QobjHeader(),
            config=QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10),
            experiments=[
                QasmQobjExperiment(instructions=[
                    QasmQobjInstruction(name='u1', qubits=[1], params=[0.4]),
                    QasmQobjInstruction(name='u2', qubits=[1], params=[0.4, 0.2])
                ])
            ]
        )

        self.valid_dict = {
            'qobj_id': '12345',
            'type': 'QASM',
            'schema_version': '1.1.0',
            'header': {},
            'config': {'max_credits': 10, 'memory_slots': 2, 'shots': 1024},
            'experiments': [
                {'instructions': [
                    {'name': 'u1', 'params': [0.4], 'qubits': [1]},
                    {'name': 'u2', 'params': [0.4, 0.2], 'qubits': [1]}
                ]}
            ],
        }

        self.bad_qobj = copy.deepcopy(self.valid_qobj)
        self.bad_qobj.experiments = []
 def setUp(self):
     experiment_result_data = ExperimentResultData.from_dict(
         {'counts': {
             '0x0': 42
         }})
     experiment_result_data_2 = ExperimentResultData.from_dict(
         {'counts': {
             '0x1': 42
         }})
     experiment_result_data_3 = ExperimentResultData.from_dict({})
     header_1 = QobjHeader.from_dict({'name': 'Test1'})
     header_2 = QobjHeader.from_dict({'name': 'Test2'})
     header_3 = QobjHeader.from_dict({'name': 'Test3'})
     self.experiment_result_dictionary_1 = {
         'name': 'Test1',
         'shots': 42,
         'data': experiment_result_data,
         'status': 'DONE',
         'success': True,
         'time_taken': 0.42,
         'header': header_1
     }
     self.experiment_result_dictionary_2 = {
         'name': 'Test2',
         'shots': 23,
         'data': experiment_result_data_2,
         'status': 'DONE',
         'success': True,
         'time_taken': 0.12,
         'header': header_2
     }
     self.experiment_result_dictionary_3 = {
         'name': 'Test3',
         'shots': 23,
         'data': experiment_result_data_3,
         'status': 'CANCELLED',
         'success': False,
         'time_taken': 0.12,
         'header': header_3
     }
     self.experiment_result_1 = ExperimentResult(
         **self.experiment_result_dictionary_1)
     self.experiment_result_2 = ExperimentResult(
         **self.experiment_result_dictionary_2)
     self.experiment_result_3 = ExperimentResult(
         **self.experiment_result_dictionary_3)
Exemple #12
0
 def test_snapshot_instruction_to_dict(self):
     """Test snapshot instruction to dict."""
     valid_qobj = QasmQobj(
         qobj_id="12345",
         header=QobjHeader(),
         config=QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10),
         experiments=[
             QasmQobjExperiment(instructions=[
                 QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
                 QasmQobjInstruction(
                     name="u2", qubits=[1], params=[0.4, 0.2]),
                 QasmQobjInstruction(
                     name="snapshot",
                     qubits=[1],
                     snapshot_type="statevector",
                     label="my_snap",
                 ),
             ])
         ],
     )
     res = valid_qobj.to_dict()
     expected_dict = {
         "qobj_id":
         "12345",
         "type":
         "QASM",
         "schema_version":
         "1.3.0",
         "header": {},
         "config": {
             "max_credits": 10,
             "memory_slots": 2,
             "shots": 1024
         },
         "experiments": [{
             "instructions": [
                 {
                     "name": "u1",
                     "params": [0.4],
                     "qubits": [1]
                 },
                 {
                     "name": "u2",
                     "params": [0.4, 0.2],
                     "qubits": [1]
                 },
                 {
                     "name": "snapshot",
                     "qubits": [1],
                     "snapshot_type": "statevector",
                     "label": "my_snap",
                 },
             ],
             "config": {},
             "header": {},
         }],
     }
     self.assertEqual(expected_dict, res)
Exemple #13
0
def _dags_2_qobj(dags, backend_name, config=None, shots=None,
                 max_credits=None, qobj_id=None, basis_gates=None, coupling_map=None,
                 seed=None):
    """Convert a list of dags into a qobj.

    Args:
        dags (list[DAGCircuit]): dags to compile
        backend_name (str): name of runner backend
        config (dict): dictionary of parameters (e.g. noise) used by runner
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        qobj_id (int): identifier for the generated qobj
        basis_gates (list[str])): basis gates for the experiment
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        seed (int): random seed for simulators

    Returns:
        Qobj: the Qobj to be run on the backends
    """
    # TODO: the following will be removed from qobj and thus removed here:
    # `basis_gates`, `coupling_map`

    # Step 1: create the Qobj, with empty experiments.
    # Copy the configuration: the values in `config` have preference
    qobj_config = deepcopy(config or {})
    # TODO: "memory_slots" is required by the qobj schema in the top-level
    # qobj.config, and is user-defined. At the moment is set to the maximum
    # number of *register* slots for the circuits, in order to have `measure`
    # behave properly until the transition is over; and each circuit stores
    # its memory_slots in its configuration.
    qobj_config.update({'shots': shots,
                        'max_credits': max_credits,
                        'memory_slots': 0})

    qobj = Qobj(qobj_id=qobj_id or str(uuid.uuid4()),
                config=QobjConfig(**qobj_config),
                experiments=[],
                header=QobjHeader(backend_name=backend_name))
    if seed:
        qobj.config.seed = seed

    qobj.experiments = parallel_map(_dags_2_qobj_parallel, dags,
                                    task_kwargs={'basis_gates': basis_gates,
                                                 'config': config,
                                                 'coupling_map': coupling_map})

    # Update the `memory_slots` value.
    # TODO: remove when `memory_slots` can be provided by the user.
    qobj.config.memory_slots = max(experiment.config.memory_slots for
                                   experiment in qobj.experiments)

    # Update the `n_qubits` global value.
    # TODO: num_qubits is not part of the qobj specification, but needed
    # for the simulator.
    qobj.config.n_qubits = max(experiment.config.n_qubits for
                               experiment in qobj.experiments)

    return qobj
Exemple #14
0
    def test_aerjob_raises_error_when_sending_bad_qobj(self):
        """Test aerjob is denied resource request access when given an invalid Qobj instance."""
        job_id = str(uuid.uuid4())
        backend = FakeBackend()
        self.bad_qobj.header = QobjHeader(backend_name=backend.name())

        with self.assertRaises(SchemaValidationError):
            job = aerjob.AerJob(backend, job_id, _nop, self.bad_qobj)
            job.submit()
    def test_localjob_raises_error_when_sending_bad_qobj(self):
        """Test localjob is denied resource request access when given an invalid Qobj instance."""

        backend = FakeBackend()
        self.bad_qobj.header = QobjHeader(backend_name=backend.name())

        with self.assertRaises(QobjValidationError):
            job = localjob.LocalJob(_nop, self.bad_qobj)
            job.submit()
    def test_ibmqobj_raises_error_when_sending_bad_qobj(self):
        """Test IBMQobj is denied resource request access when given an invalid Qobj instance."""

        backend = FakeBackend()
        self.bad_qobj.header = QobjHeader(backend_name=backend.name())

        api_stub = {}
        with self.assertRaises(QobjValidationError):
            job = ibmqjob.IBMQJob(api_stub, 'True', self.bad_qobj)
            job.submit()
Exemple #17
0
def _compile_wrapper(circuits, backend, backend_config, compile_config,
                     run_config):
    transpiled_circuits = transpiler.transpile(circuits, backend,
                                               **backend_config,
                                               **compile_config)
    qobj = circuits_to_qobj(transpiled_circuits,
                            user_qobj_header=QobjHeader(),
                            run_config=run_config,
                            qobj_id=None)
    return qobj, transpiled_circuits
Exemple #18
0
def new_fake_qobj():
    """Create fake `Qobj` and backend instances."""
    backend = FakeBackend()
    return Qobj(id='test-id',
                config=QobjConfig(shots=1024, memory_slots=1, max_credits=100),
                header=QobjHeader(backend_name=backend.name),
                experiments=[
                    QobjExperiment(instructions=[],
                                   header=QobjExperimentHeader(
                                       compiled_circuit_qasm='fake-code'),
                                   config=QobjItem(seed=123456))
                ])
Exemple #19
0
 def __init__(self):
     qobj_id = "test_id"
     config = QasmQobjConfig(shots=1024, memory_slots=1)
     header = QobjHeader(backend_name=FakeQasmSimulator().name())
     experiments = [
         QasmQobjExperiment(
             instructions=[QasmQobjInstruction(name="barrier", qubits=[1])],
             header=QobjExperimentHeader(),
             config=QasmQobjExperimentConfig(seed=123456),
         )
     ]
     super().__init__(qobj_id=qobj_id, config=config, experiments=experiments, header=header)
Exemple #20
0
def _compile_wrapper(circuits, backend, backend_config, compile_config,
                     run_config):
    transpiled_circuits = compiler.transpile(circuits, backend,
                                             **backend_config,
                                             **compile_config)
    if not isinstance(transpiled_circuits, list):
        transpiled_circuits = [transpiled_circuits]

    qobj = assemble_circuits(transpiled_circuits,
                             qobj_id=str(uuid.uuid4()),
                             qobj_header=QobjHeader(),
                             run_config=run_config)
    return qobj, transpiled_circuits
    def test_submit(self):
        backend = Mock()
        backend.run.return_value = '25'
        api = Mock()
        job_id = '42'
        qobj = QasmQobj(qobj_id='id',
                        config=QasmQobjConfig(),
                        experiments=[],
                        header=QobjHeader())
        job = QIJob(backend, job_id, api, qobj)

        job.submit()
        self.assertEqual('25', job.job_id())
Exemple #22
0
def new_fake_qobj():
    """Create fake `Qobj` and backend instances."""
    backend = FakeQasmSimulator()
    return QasmQobj(
        qobj_id='test-id',
        config=QasmQobjConfig(shots=1024, memory_slots=1, max_credits=100),
        header=QobjHeader(backend_name=backend.name()),
        experiments=[
            QasmQobjExperiment(
                instructions=[QasmQobjInstruction(name='barrier', qubits=[1])],
                header=QobjExperimentHeader(),
                config=QasmQobjExperimentConfig(seed_simulator=123456))
        ])
    def test_constructor_with_qobj(self):
        api = Mock()
        job_id = '42'
        backend = 'test_backend'
        qobj = QasmQobj(qobj_id='id',
                        config=QasmQobjConfig(),
                        experiments=[],
                        header=QobjHeader())
        job = QIJob(backend, job_id, api, qobj)

        self.assertIs(qobj, job._qobj)
        self.assertEqual(job.job_id(), '')
        self.assertEqual(api, job._api)
        self.assertIsNone(job.experiments)
        self.assertEqual(JobStatus.INITIALIZING, job._status)
Exemple #24
0
    def test_qobj_headers_in_result(self):
        """Test that the qobj headers are passed onto the results."""
        custom_qobj_header = {'x': 1, 'y': [1, 2, 3], 'z': {'a': 4}}
        for backend in qiskit.providers.aer.Aer.backends():
            with self.subTest(backend=backend):
                qobj = compile(self.qc1, backend)

                # Update the Qobj header.
                qobj.header = QobjHeader.from_dict(custom_qobj_header)
                # Update the Qobj.experiment header.
                qobj.experiments[0].header.some_field = 'extra info'

                result = backend.run(qobj).result()
                self.assertEqual(result.header.to_dict(), custom_qobj_header)
                self.assertEqual(result.results[0].header.some_field,
                                 'extra info')
Exemple #25
0
def execute_circuits(circuits,
                     backend,
                     qobj_header=None,
                     transpile_config=None,
                     run_config=None,
                     **kwargs):
    """Executes a list of circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
        backend (BaseBackend): a backend to execute the circuits on
        qobj_header (QobjHeader): User input to go in the header
        transpile_config (TranspileConfig): Configurations for the transpiler
        run_config (RunConfig): Run Configuration
        kwargs: extra arguments used by AER for running configurable backends.
                Refer to the backend documentation for details on these arguments

    Returns:
        BaseJob: returns job instance derived from BaseJob
    """

    # TODO: a hack, remove when backend is not needed in transpile
    # ------
    transpile_config = transpile_config or TranspileConfig()
    transpile_config.backend = backend
    # ------

    # filling in the header with the backend name the qobj was run on
    qobj_header = qobj_header or QobjHeader()
    qobj_header.backend_name = backend.name()

    # default values
    if not run_config:
        # TODO remove max_credits from the default when it is not
        # required by by the backend.
        run_config = RunConfig(shots=1024, max_credits=10, memory=False)

    # transpiling the circuits using the transpiler_config
    new_circuits = transpile(circuits, transpile_config=transpile_config)

    # assembling the circuits into a qobj to be run on the backend
    qobj = assemble_circuits(new_circuits,
                             qobj_header=qobj_header,
                             run_config=run_config)

    # executing the circuits on the backend and returning the job
    return backend.run(qobj, **kwargs)
Exemple #26
0
def circuits_to_qobj(circuits, qobj_header=None,
                     qobj_id=None, backend_name=None,
                     config=None, shots=None, max_credits=None,
                     basis_gates=None,
                     coupling_map=None, seed=None, memory=None):
    """Convert a list of circuits into a qobj.

    Args:
        circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
        qobj_header (QobjHeader): header to pass to the results
        qobj_id (int): TODO: delete after qiskit-terra 0.8
        backend_name (str): TODO: delete after qiskit-terra 0.8
        config (dict): TODO: delete after qiskit-terra 0.8
        shots (int): TODO: delete after qiskit-terra 0.8
        max_credits (int): TODO: delete after qiskit-terra 0.8
        basis_gates (str): TODO: delete after qiskit-terra 0.8
        coupling_map (list): TODO: delete after qiskit-terra 0.8
        seed (int): TODO: delete after qiskit-terra 0.8
        memory (bool): TODO: delete after qiskit-terra 0.8

    Returns:
        Qobj: the Qobj to be run on the backends
    """
    warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. '
                  'Use qiskit.compiler.assemble() to serialize circuits into a qobj.',
                  DeprecationWarning)

    qobj_header = qobj_header or QobjHeader()

    if backend_name:
        qobj_header.backend_name = backend_name
    if basis_gates:
        warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning)
    if coupling_map:
        warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning)

    qobj = assemble(experiments=circuits,
                    qobj_id=qobj_id,
                    qobj_header=qobj_header,
                    shots=shots,
                    memory=memory,
                    max_credits=max_credits,
                    seed_simulator=seed,
                    config=config)

    return qobj
Exemple #27
0
    def test_qobj_headers_in_result_devices(self, backend):
        """Test that the qobj headers are passed onto the results for devices."""
        # pylint: disable=unused-argument
        custom_qobj_header = {'x': 1, 'y': [1, 2, 3], 'z': {'a': 4}}

        qobj = assemble(transpile(self.qc1, backend=backend), backend=backend)
        # Update the Qobj header.
        qobj.header = QobjHeader.from_dict(custom_qobj_header)
        # Update the Qobj.experiment header.
        qobj.experiments[0].header.some_field = 'extra info'

        job = backend.run(qobj, validate_qobj=True)
        job.wait_for_final_state(wait=300, callback=self.simple_job_callback)
        result = job.result()
        self.assertEqual(result.header.to_dict(), custom_qobj_header)
        self.assertEqual(result.results[0].header.some_field,
                         'extra info')
Exemple #28
0
    def setUp(self):
        super().setUp()
        self.valid_qobj = QasmQobj(
            qobj_id="12345",
            header=QobjHeader(),
            config=QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10),
            experiments=[
                QasmQobjExperiment(instructions=[
                    QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
                    QasmQobjInstruction(
                        name="u2", qubits=[1], params=[0.4, 0.2]),
                ])
            ],
        )

        self.valid_dict = {
            "qobj_id":
            "12345",
            "type":
            "QASM",
            "schema_version":
            "1.2.0",
            "header": {},
            "config": {
                "max_credits": 10,
                "memory_slots": 2,
                "shots": 1024
            },
            "experiments": [{
                "instructions": [
                    {
                        "name": "u1",
                        "params": [0.4],
                        "qubits": [1]
                    },
                    {
                        "name": "u2",
                        "params": [0.4, 0.2],
                        "qubits": [1]
                    },
                ]
            }],
        }

        self.bad_qobj = copy.deepcopy(self.valid_qobj)
        self.bad_qobj.experiments = []
Exemple #29
0
    def test_qobj_headers_in_result(self):
        """Test that the qobj headers are passed onto the results."""
        custom_qobj_header = {'x': 1, 'y': [1, 2, 3], 'z': {'a': 4}}

        for backend in BasicAer.backends():
            with self.subTest(backend=backend):
                new_circ = transpile(self.qc1, backend=backend)
                qobj = assemble(new_circ, shots=1024)

                # Update the Qobj header.
                qobj.header = QobjHeader.from_dict(custom_qobj_header)
                # Update the Qobj.experiment header.
                qobj.experiments[0].header.some_field = 'extra info'

                result = backend.run(qobj).result()
                self.assertEqual(result.header.to_dict(), custom_qobj_header)
                self.assertEqual(result.results[0].header.some_field, 'extra info')
Exemple #30
0
    def from_dict(cls, data):
        """Create a new ExperimentResultData object from a dictionary.

        Args:
            data (dict): A dictionary representing the Result to create. It
                         will be in the same format as output by
                         :meth:`to_dict`.
        Returns:
            Result: The ``Result`` object from the input dictionary.

        """

        in_data = copy.copy(data)
        in_data["results"] = [ExperimentResult.from_dict(x) for x in in_data.pop("results")]
        if "header" in in_data:
            in_data["header"] = QobjHeader.from_dict(in_data.pop("header"))
        return cls(**in_data)