How to use the qiskit.test.QiskitTestCase function in qiskit

To help you get started, we’ve selected a few qiskit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Qiskit / qiskit-terra / test / python / quantum_info / test_analyzation.py View on Github external
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Tests for qiskit.quantum_info.analysis"""

import unittest

import qiskit
from qiskit import BasicAer
from qiskit.quantum_info.analysis.average import average_data
from qiskit.quantum_info.analysis.make_observable import make_dict_observable
from qiskit.quantum_info.analysis import hellinger_fidelity
from qiskit.test import QiskitTestCase


class TestAnalyzation(QiskitTestCase):
    """Test qiskit.Result API"""

    def test_average_data_dict_observable(self):
        """Test average_data for dictionary observable input"""
        qr = qiskit.QuantumRegister(2)
        cr = qiskit.ClassicalRegister(2)
        qc = qiskit.QuantumCircuit(qr, cr, name="qc")
        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        shots = 10000
        backend = BasicAer.get_backend('qasm_simulator')
        result = qiskit.execute(qc, backend, shots=shots).result()
        counts = result.get_counts(qc)
        observable = {"00": 1, "11": 1, "01": -1, "10": -1}
github Qiskit / qiskit-terra / test / python / circuit / test_instruction_repeat.py View on Github external
def test_standard_1Q_one(self):
        """Test standard gate.repeat(1) method.
        """
        qr = QuantumRegister(1, 'qr')
        expected_circ = QuantumCircuit(qr)
        expected_circ.append(SGate(), [qr[0]])
        expected = expected_circ.to_instruction()

        result = SGate().repeat(1)

        self.assertEqual(result.name, 's*1')
        self.assertEqual(result.definition, expected.definition)
        self.assertIsInstance(result, Gate)


class TestRepeatInt2Q(QiskitTestCase):
    """Test gate_q2.repeat() with integer"""

    def test_standard_2Q_two(self):
        """Test standard 2Q gate.repeat(2) method.
        """
        qr = QuantumRegister(2, 'qr')
        expected_circ = QuantumCircuit(qr)
        expected_circ.append(CnotGate(), [qr[0], qr[1]])
        expected_circ.append(CnotGate(), [qr[0], qr[1]])
        expected = expected_circ.to_instruction()

        result = CnotGate().repeat(2)

        self.assertEqual(result.name, 'cx*2')
        self.assertEqual(result.definition, expected.definition)
        self.assertIsInstance(result, Gate)
github Qiskit / qiskit-terra / test / python / circuit / test_registerless_circuit.py View on Github external
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Test registerless QuantumCircuit and Gates on wires"""

import numpy

from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase


class TestRegisterlessCircuit(QiskitTestCase):
    """Test registerless QuantumCircuit."""

    def test_circuit_constructor_qwires(self):
        """Create a QuantumCircuit directly with quantum wires
        """
        circuit = QuantumCircuit(2)

        expected = QuantumCircuit(QuantumRegister(2, 'q'))

        self.assertEqual(circuit, expected)

    def test_circuit_constructor_wires_wrong(self):
        """Create a registerless QuantumCircuit wrongly
        """
        self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3)  # QuantumCircuit(1, 2, 3)
github Qiskit / qiskit-terra / test / python / circuit / test_extensions_standard.py View on Github external
self.assertEqual(instruction_set.instructions[0].name, 'z')
        self.assertEqual(instruction_set.qargs[1], [self.qr[1]])
        self.assertEqual(instruction_set.instructions[2].params, [])

    def test_broadcast_does_not_duplicate_instructions(self):
        self.circuit.rz(0, range(6))
        instructions = [inst for inst, qargs, cargs in self.circuit.data]
        self.assertEqual(len(set(id(inst) for inst in instructions)), 6)

        self.circuit.data = []
        self.circuit.rz(0, self.qr)
        instructions = [inst for inst, qargs, cargs in self.circuit.data]
        self.assertEqual(len(set(id(inst) for inst in instructions)), 3)


class TestStandard2Q(QiskitTestCase):
    """Standard Extension Test. Gates with two Qubits"""

    def setUp(self):
        self.qr = QuantumRegister(3, "q")
        self.qr2 = QuantumRegister(3, "r")
        self.cr = ClassicalRegister(3, "c")
        self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr)

    def test_barrier_reg_bit(self):
        self.circuit.barrier(self.qr, self.qr2[0])
        self.assertEqual(len(self.circuit), 1)
        op, qargs, _ = self.circuit[0]
        self.assertEqual(op.name, 'barrier')
        self.assertEqual(qargs, [self.qr[0], self.qr[1], self.qr[2], self.qr2[0]])

    def test_ch_reg_reg(self):
github Qiskit / qiskit-terra / test / python / transpiler / test_depth_pass.py View on Github external
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Depth pass testing"""

import unittest

from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Depth
from qiskit.test import QiskitTestCase


class TestDepthPass(QiskitTestCase):
    """ Tests for Depth analysis methods. """

    def test_empty_dag(self):
        """ Empty DAG has 0 depth """
        circuit = QuantumCircuit()
        dag = circuit_to_dag(circuit)

        pass_ = Depth()
        _ = pass_.run(dag)

        self.assertEqual(pass_.property_set['depth'], 0)

    def test_just_qubits(self):
        """ A dag with 8 operations and no classic bits"""
        qr = QuantumRegister(2)
        circuit = QuantumCircuit(qr)
github Qiskit / qiskit-terra / test / python / transpiler / test_noise_adaptive_layout.py View on Github external
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.models import BackendProperties
from qiskit.providers.models.backendproperties import Nduv, Gate


def make_qubit_with_error(readout_error):
    """Create a qubit for BackendProperties"""
    calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
    return [Nduv(name="T1", date=calib_time, unit="µs", value=100.0),
            Nduv(name="T2", date=calib_time, unit="µs", value=100.0),
            Nduv(name="frequency", date=calib_time, unit="GHz", value=5.0),
            Nduv(name="readout_error", date=calib_time, unit="", value=readout_error)]


class TestNoiseAdaptiveLayout(QiskitTestCase):
    """Tests the NoiseAdaptiveLayout pass."""

    def test_on_linear_topology(self):
        """
        Test that the mapper identifies the correct gate in a linear topology
        """
        calib_time = datetime(year=2019, month=2, day=1, hour=0, minute=0, second=0)
        qr = QuantumRegister(2, name='q')
        circuit = QuantumCircuit(qr)
        circuit.cx(qr[0], qr[1])
        dag = circuit_to_dag(circuit)
        qubit_list = []
        ro_errors = [0.01, 0.01, 0.01]
        for ro_error in ro_errors:
            qubit_list.append(make_qubit_with_error(ro_error))
        p01 = [Nduv(date=calib_time, name='gate_error', unit='', value=0.9)]
github Qiskit / qiskit-terra / test / python / tools / jupyter / test_notebooks.py View on Github external
import sys
import unittest

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from qiskit.tools.visualization import HAS_MATPLOTLIB
from qiskit.test import (Path, QiskitTestCase, online_test, slow_test)


# Timeout (in seconds) for a single notebook.
TIMEOUT = 1000
# Jupyter kernel to execute the notebook in.
JUPYTER_KERNEL = 'python3'


class TestJupyter(QiskitTestCase):
    """Notebooks test case."""
    def setUp(self):
        self.execution_path = os.path.join(Path.SDK.value, '..')

    def _execute_notebook(self, filename, qe_token=None, qe_url=None):
        # Create the preprocessor.
        execute_preprocessor = ExecutePreprocessor(timeout=TIMEOUT,
                                                   kernel_name=JUPYTER_KERNEL)

        # Read the notebook.
        with open(filename) as file_:
            notebook = nbformat.read(file_, as_version=4)

        if qe_token and qe_url:
            top_str = "from qiskit import IBMQ\n"
            top_str += "IBMQ.enable_account('{token}', '{url}')".format(token=qe_token,
github Qiskit / qiskit-terra / test / python / test_schemas.py View on Github external
# that they have been altered from the originals.

"""Schemas test."""

import json
import os

from qiskit.validation.jsonschema.schema_validation import (
    validate_json_against_schema, _get_validator)
from qiskit.providers.models import (QasmBackendConfiguration, PulseBackendConfiguration,
                                     BackendProperties, BackendStatus, JobStatus, PulseDefaults)
from qiskit.result import Result
from qiskit.test import QiskitTestCase, Path


class TestSchemaExamples(QiskitTestCase):
    """
    Tests schema validation
    """
    _json_examples_per_schema = {
        "qasm_backend_configuration": (
            'backend_configuration',
            ["backend_configuration_openqasm_example.json",
             "backend_configuration_openqasm_simulator_example.json"]),
        "pulse_backend_configuration": (
            'backend_configuration',
            ["backend_configuration_openpulse_example.json"]),
        "backend_properties": [
            "backend_properties_example.json"],
        "backend_status": [
            "backend_status_example.json"],
        "default_pulse_configuration": [
github Qiskit / qiskit-terra / test / python / test_qcvv_fitters.py View on Github external
# -*- coding: utf-8 -*-

# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.

"""Test qiskit.tools.qcvv.fitters."""

import numpy as np

from qiskit.tools.qcvv import fitters
from qiskit.test import QiskitTestCase


class TestQCVVFitters(QiskitTestCase):
    """Tests for functions in qiskit.tools.qcvv.fitters."""

    def test_exp_fit_fun(self):
        """Test exponential decay fit function."""
        a_in = 2
        x_in = 3
        tau_in = 4
        c_in = 1
        result = fitters.exp_fit_fun(x_in, a_in, tau_in, c_in)
        self.assertAlmostEqual(1.9447331054820294, result)

    def test_osc_fit_fun(self):
        """Test decay cosine fit function."""
        a_in = 2
        x_in = 3
        tau_in = 4
github Qiskit / qiskit-terra / test / python / pulse / test_continuous_pulses.py View on Github external
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=invalid-name

"""Tests continuous pulse functions."""

import numpy as np

from qiskit.test import QiskitTestCase
import qiskit.pulse.pulse_lib.continuous as continuous


class TestContinuousPulses(QiskitTestCase):
    """Test continuous pulses."""

    def test_constant(self):
        """Test constant pulse."""
        amp = 0.5j
        samples = 50
        times = np.linspace(0, 10, samples)

        constant_arr = continuous.constant(times, amp=amp)

        self.assertEqual(constant_arr.dtype, np.complex_)
        np.testing.assert_equal(constant_arr, amp)
        self.assertEqual(len(constant_arr), samples)

    def test_zero(self):
        """Test constant pulse."""