def test_aer_placed_expectation() -> None: # bug TKET-695 n_qbs = 3 c = Circuit(n_qbs, n_qbs) c.X(0) c.CX(0, 2) c.CX(1, 2) c.H(1) # c.measure_all() b = AerBackend() operator = QubitPauliOperator({ QubitPauliString(Qubit(0), Pauli.Z): 1.0, QubitPauliString(Qubit(1), Pauli.X): 0.5, }) assert b.get_operator_expectation_value(c, operator) == (-0.5 + 0j) with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"), "rb") as f: properties = pickle.load(f) noise_model = NoiseModel.from_backend(properties) noise_b = AerBackend(noise_model) with pytest.raises(RuntimeError) as errorinfo: noise_b.get_operator_expectation_value(c, operator) assert "not supported with noise model" in str(errorinfo.value) c.rename_units({Qubit(1): Qubit("node", 1)}) with pytest.raises(ValueError) as errorinfoCirc: b.get_operator_expectation_value(c, operator) assert "default register Qubits" in str(errorinfoCirc.value)
def test_process_characterisation_no_noise_model() -> None: my_noise_model = NoiseModel() back = AerBackend(my_noise_model) assert back.characterisation is None c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0) back.compile_circuit(c) assert back.valid_circuit(c)
def test_process_characterisation_incomplete_noise_model() -> None: my_noise_model = NoiseModel() my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 1]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [1]) my_noise_model.add_quantum_error(depolarizing_error(0.1, 1), ["u3"], [3]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Z", 0.65)]), ["u2"], [0]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Y", 0.65)]), ["u1"], [2]) back = AerBackend(my_noise_model) char = cast(Dict[str, Any], back.characterisation) c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0).measure_all() back.compile_circuit(c) assert back.valid_circuit(c) dev = Device( char.get("NodeErrors", {}), char.get("EdgeErrors", {}), char.get("Architecture", Architecture([])), ) nodes = dev.nodes assert set(dev.architecture.coupling) == set([ (nodes[0], nodes[1]), (nodes[0], nodes[2]), (nodes[0], nodes[3]), (nodes[1], nodes[2]), (nodes[1], nodes[3]), (nodes[2], nodes[0]), (nodes[2], nodes[1]), (nodes[2], nodes[3]), (nodes[3], nodes[0]), (nodes[3], nodes[1]), (nodes[3], nodes[2]), ])
def __init__( self, backend_name: str, hub: Optional[str] = None, group: Optional[str] = None, project: Optional[str] = None, ): """Construct an IBMQEmulatorBackend. Identical to :py:class:`IBMQBackend` constructor, except there is no `monitor` parameter. See :py:class:`IBMQBackend` docs for more details. """ self._ibmq = IBMQBackend(backend_name, hub, group, project) qasm_sim = QasmSimulator.from_backend(self._ibmq._backend) super().__init__(noise_model=NoiseModel.from_backend(qasm_sim)) self._backend = qasm_sim
def test_aer_default_pass() -> None: with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"), "rb") as f: properties = pickle.load(f) noise_model = NoiseModel.from_backend(properties) for nm in [None, noise_model]: b = AerBackend(nm) for ol in range(3): comp_pass = b.default_compilation_pass(ol) c = Circuit(3, 3) c.H(0) c.CX(0, 1) c.CSWAP(1, 0, 2) c.ZZPhase(0.84, 2, 0) c.add_gate(OpType.TK1, [0.2, 0.3, 0.4], [0]) comp_pass.apply(c) c.measure_all() for pred in b.required_predicates: assert pred.verify(c)
def test_noise() -> None: with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"), "rb") as f: properties = pickle.load(f) noise_model = NoiseModel.from_backend(properties) n_qbs = 5 c = Circuit(n_qbs, n_qbs) x_qbs = [2, 0, 4] for i in x_qbs: c.X(i) c.measure_all() b = AerBackend(noise_model) n_shots = 50 b.compile_circuit(c) shots = b.get_shots(c, n_shots, seed=4) zer_exp = [] one_exp = [] for i in range(n_qbs): expectation = np.sum(shots[:, i]) / n_shots if i in x_qbs: one_exp.append(expectation) else: zer_exp.append(expectation) assert min(one_exp) > max(zer_exp) c2 = (Circuit(4, 4).H(0).CX(0, 2).CX(3, 1).T(2).CX(0, 1).CX(0, 3).CX(2, 1).measure_all()) b.compile_circuit(c2) shots = b.get_shots(c2, 10, seed=5) assert shots.shape == (10, 4)
from functions import QuantumNeuralNetwork, EffectiveDimension from qiskit.aqua import QuantumInstance from qiskit import IBMQ, Aer from qiskit.providers.aer.noise.noise_model import NoiseModel import numpy as np from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes TOKEN = 'insert token here' IBMQ.save_account(TOKEN, overwrite=True) provider = IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-internal', group='deployed', project='default') backend_name = 'ibmq_montreal' backend_ibmq = provider.get_backend(backend_name) properties = backend_ibmq.properties() coupling_map = backend_ibmq.configuration().coupling_map noise_model = NoiseModel.from_backend(properties) layout = [3, 5, 8, 11, 14, 13, 12, 10] # might need to change qi_ibmq_noise_model = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), noise_model=noise_model, optimization_level=0, shots=8000, seed_transpiler=2, initial_layout=layout) qi = qi_ibmq_noise_model compile_config = {'initial_layout': layout, 'seed_transpiler': 2, 'optimization_level': 3 } n = [1000, 2000, 8000, 10000, 40000, 60000, 100000, 150000, 200000, 500000, 1000000, 10000000, 10000000000, 10000000000000] qubits = 8 fm = ZZFeatureMap(qubits, reps=2, entanglement='full') varform = RealAmplitudes(qubits, reps=9, entanglement='full') qnet = QuantumNeuralNetwork(fm, varform) ed = EffectiveDimension(qnet, 100, 100)
def test_process_characterisation_complete_noise_model() -> None: my_noise_model = NoiseModel() readout_error_0 = 0.2 readout_error_1 = 0.3 my_noise_model.add_readout_error( [ [1 - readout_error_0, readout_error_0], [readout_error_0, 1 - readout_error_0], ], [0], ) my_noise_model.add_readout_error( [ [1 - readout_error_1, readout_error_1], [readout_error_1, 1 - readout_error_1], ], [1], ) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 1]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [0]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Z", 0.65)]), ["u2"], [0]) my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Y", 0.65)]), ["u1"], [0]) back = AerBackend(my_noise_model) char = cast(Dict[str, Any], back.characterisation) dev = Device( char.get("NodeErrors", {}), char.get("EdgeErrors", {}), char.get("Architecture", Architecture([])), ) assert char["GenericTwoQubitQErrors"][(0, 1)][0][1][0] == 0.0375 assert char["GenericTwoQubitQErrors"][(0, 1)][0][1][15] == 0.4375 assert char["GenericOneQubitQErrors"][0][0][1][0] == 0.125 assert char["GenericOneQubitQErrors"][0][0][1][3] == 0.625 assert char["GenericOneQubitQErrors"][0][1][1][0] == 0.35 assert char["GenericOneQubitQErrors"][0][1][1][1] == 0.65 assert char["GenericOneQubitQErrors"][0][2][1][0] == 0.35 assert char["GenericOneQubitQErrors"][0][2][1][1] == 0.65 assert dev.get_error(OpType.U3, dev.nodes[0]) == 0.375 assert dev.get_error(OpType.CX, (dev.nodes[0], dev.nodes[1])) == 0.5625 assert dev.get_error(OpType.CX, (dev.nodes[1], dev.nodes[0])) == 0.80859375 assert char["ReadoutErrors"][0] == [[0.8, 0.2], [0.2, 0.8]] assert char["ReadoutErrors"][1] == [[0.7, 0.3], [0.3, 0.7]]
def test_circuit_compilation_complete_noise_model() -> None: my_noise_model = NoiseModel() my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 1]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 2]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [0, 3]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [1, 2]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [1, 3]) my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"], [2, 3]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [0]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [1]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [2]) my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [3]) back = AerBackend(my_noise_model) c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0).measure_all() back.compile_circuit(c) assert back.valid_circuit(c)
def basic_device_noise_model(properties, gate_error=True, readout_error=True, thermal_relaxation=True, temperature=0, gate_lengths=None, gate_length_units='ns', standard_gates=True): """ Return a noise model derived from a devices backend properties. This function generates a noise model based on: * 1 and 2 qubit gate errors consisting of a :func:`depolarizing_error` followed by a :func:`thermal_relaxation_error`. * Single qubit :class:`ReadoutError` on all measurements. The Error error parameters are tuned for each individual qubit based on the :math:`T_1`, :math:`T_2`, frequency and readout error parameters for each qubit, and the gate error and gate time parameters for each gate obtained from the device backend properties. **Additional Information** The noise model includes the following errors: * If ``readout_error=True`` include single qubit readout errors on measurements. * If ``gate_error=True`` and ``thermal_relaxation=True`` include: * Single-qubit gate errors consisting of a :func:`depolarizing_error` followed by a :func:`thermal_relaxation_error` for the qubit the gate acts on. * Two-qubit gate errors consisting of a 2-qubit :func:`depolarizing_error` followed by single qubit :func:`thermal_relaxation_error` on each qubit participating in the gate. * If ``gate_error=True`` is ``True`` and ``thermal_relaxation=False``: * An N-qubit :func:`depolarizing_error` on each N-qubit gate. * If ``gate_error=False`` and ``thermal_relaxation=True`` include single-qubit :func:`thermal_relaxation_errors` on each qubits participating in a multi-qubit gate. For best practice in simulating a backend make sure that the circuit is compiled using the set of basis gates in the noise module by setting ``basis_gates=noise_model.basis_gates`` and using the device coupling map with ``coupling_map=backend.configuration().coupling_map`` **Specifying custom gate times** The ``gate_lengths`` kwarg can be used to specify custom gate times to add gate errors using the :math:`T_1` and :math:`T_2` values from the backend properties. This should be passed as a list of tuples ``gate_lengths=[(name, value), ...]`` where ``name`` is the gate name string, and ``value`` is the gate time in nanoseconds. If a custom gate is specified that already exists in the backend properties, the ``gate_lengths`` value will override the gate time value from the backend properties. If non-default values are used gate_lengths should be a list Args: properties (BackendProperties): backend properties. gate_error (bool): Include depolarizing gate errors (Default: True). readout_error (Bool): Include readout errors in model (Default: True). thermal_relaxation (Bool): Include thermal relaxation errors (Default: True). temperature (double): qubit temperature in milli-Kelvin (mK) for thermal relaxation errors (Default: 0). gate_lengths (list): Custom gate times for thermal relaxation errors. Used to extend or override the gate times in the backend properties (Default: None)) gate_length_units (str): Time units for gate length values in gate_lengths. Can be 'ns', 'ms', 'us', or 's' (Default: 'ns'). standard_gates (bool): If true return errors as standard qobj gates. If false return as unitary qobj instructions (Default: True) Returns: NoiseModel: An approximate noise model for the device backend. """ warnings.warn( 'This function is been deprecated and moved to a method of the' '`NoiseModel` class. For equivalent functionality use' ' `NoiseModel.from_backend(properties, **kwargs).', DeprecationWarning) # This wrapper is for the deprecated function # We need to import noise model here to avoid cyclic import errors # pylint: disable=import-outside-toplevel from qiskit.providers.aer.noise.noise_model import NoiseModel return NoiseModel.from_backend(properties, gate_error=gate_error, readout_error=readout_error, thermal_relaxation=thermal_relaxation, temperature=temperature, gate_lengths=gate_lengths, gate_length_units=gate_length_units, standard_gates=standard_gates)