def _compare_tensor_to_operator(self, chans, mats):

unitaries = [Operator(np.kron(j, i)) for i in mats for j in mats]<EOL>channels = [j.tensor(i) for i in chans for j in chans]<EOL>for chan, uni in zip(channels, unitaries):<EOL><INDENT>self.assertEqual(chan, chan.__class__(uni))<EOL><DEDENT>


def _compare_expand_to_operator(self, chans, mats):

unitaries = [Operator(np.kron(i, j)) for i in mats for j in mats]<EOL>channels = [j.expand(i) for i in chans for j in chans]<EOL>for chan, uni in zip(channels, unitaries):<EOL><INDENT>self.assertEqual(chan, chan.__class__(uni))<EOL><DEDENT>


def _compare_compose_to_operator(self, chans, mats):

unitaries = [Operator(np.dot(i, j)) for i in mats for j in mats]<EOL>channels = [j.compose(i) for i in chans for j in chans]<EOL>for chan, uni in zip(channels, unitaries):<EOL><INDENT>self.assertEqual(chan, chan.__class__(uni))<EOL><DEDENT>


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.tensor(rep(chan)).__class__)<EOL><DEDENT>

Check tensor works for other representations


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.expand(rep(chan)).__class__)<EOL><DEDENT>

Check expand works for other representations


current_rep = chan.__class__<EOL>other_reps = [Operator, Choi, SuperOp, Kraus, Stinespring, Chi, PTM]<EOL>for rep in other_reps:<EOL><INDENT>self.assertEqual(current_rep, chan.compose(rep(chan)).__class__)<EOL><DEDENT>

Check compose works for other representations


<EOL>gate_h = np.array([[<NUM_LIT:1>, <NUM_LIT:1>], [<NUM_LIT:1>, -<NUM_LIT:1>]]) / np.sqrt(<NUM_LIT:2>)<EOL>gate_x = np.array([[<NUM_LIT:0>, <NUM_LIT:1>], [<NUM_LIT:1>, <NUM_LIT:0>]])<EOL>gate_y = np.array([[<NUM_LIT:0>, -<NUM_LIT>], [<NUM_LIT>, <NUM_LIT:0>]])<EOL>gate_z = np.array([[<NUM_LIT:1>, <NUM_LIT:0>], [<NUM_LIT:0>, -<NUM_LIT:1>]])<EOL>gate_cx = np.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0.>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]])<EOL>target_unitary1 = np.kron(np.kron(gate_h, gate_h), gate_h)<EOL>target_unitary2 = np.kron(np.eye(<NUM_LIT:2>), gate_cx)<EOL>target_unitary3 = np.kron(gate_cx, gate_y)<EOL>target_unitary4 = np.dot(np.kron(gate_cx, np.eye(<NUM_LIT:2>)),<EOL>np.dot(np.kron(np.eye(<NUM_LIT:2>), gate_cx),<EOL>np.kron(np.eye(<NUM_LIT:4>), gate_h)))<EOL>target_unitary5 = np.kron(np.kron(np.dot(gate_x, gate_z),<EOL>np.dot(gate_z, gate_y)),<EOL>np.dot(gate_y, gate_x))<EOL>return [target_unitary1, target_unitary2, target_unitary3,<EOL>target_unitary4, target_unitary5]<EOL>

Return reference unitaries for test circuits


qr = QuantumRegister(<NUM_LIT:3>, '<STR_LIT:q>')<EOL>cr = ClassicalRegister(<NUM_LIT:3>, '<STR_LIT:c>')<EOL>circuit = QuantumCircuit(qr, cr)<EOL>circuit.x(qr[<NUM_LIT:0>])<EOL>circuit.y(qr[<NUM_LIT:0>])<EOL>circuit.z(qr[<NUM_LIT:0>])<EOL>circuit.barrier(qr[<NUM_LIT:0>])<EOL>circuit.barrier(qr[<NUM_LIT:1>])<EOL>circuit.barrier(qr[<NUM_LIT:2>])<EOL>circuit.h(qr[<NUM_LIT:0>])<EOL>circuit.s(qr[<NUM_LIT:0>])<EOL>circuit.sdg(qr[<NUM_LIT:0>])<EOL>circuit.t(qr[<NUM_LIT:0>])<EOL>circuit.tdg(qr[<NUM_LIT:0>])<EOL>circuit.iden(qr[<NUM_LIT:0>])<EOL>circuit.reset(qr[<NUM_LIT:0>])<EOL>circuit.rx(pi, qr[<NUM_LIT:0>])<EOL>circuit.ry(pi, qr[<NUM_LIT:0>])<EOL>circuit.rz(pi, qr[<NUM_LIT:0>])<EOL>circuit.u0(pi, qr[<NUM_LIT:0>])<EOL>circuit.u1(pi, qr[<NUM_LIT:0>])<EOL>circuit.u2(pi, pi, qr[<NUM_LIT:0>])<EOL>circuit.u3(pi, pi, pi, qr[<NUM_LIT:0>])<EOL>circuit.swap(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.cx(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.cy(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.cz(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.ch(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.cu1(pi, qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.cu3(pi, pi, pi, qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.crz(pi, qr[<NUM_LIT:0>], qr[<NUM_LIT:1>])<EOL>circuit.ccx(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>], qr[<NUM_LIT:2>])<EOL>circuit.cswap(qr[<NUM_LIT:0>], qr[<NUM_LIT:1>], qr[<NUM_LIT:2>])<EOL>circuit.measure(qr, cr)<EOL>return circuit<EOL>

Generate a sample circuit that includes the most common elements of
        quantum circuits.


def assertFilesAreEqual(self, current, expected):

self.assertTrue(os.path.exists(current))<EOL>self.assertTrue(os.path.exists(expected))<EOL>with open(current, "<STR_LIT:r>", encoding='<STR_LIT>') as cur,open(expected, "<STR_LIT:r>", encoding='<STR_LIT>') as exp:<EOL><INDENT>self.assertEqual(cur.read(), exp.read())<EOL><DEDENT>


def assertImagesAreEqual(self, current, expected, diff_tolerance=<NUM_LIT>):

from PIL import Image, ImageChops<EOL>if isinstance(current, str):<EOL><INDENT>current = Image.open(current)<EOL><DEDENT>if isinstance(expected, str):<EOL><INDENT>expected = Image.open(expected)<EOL><DEDENT>diff = ImageChops.difference(expected, current)<EOL>black_pixels = _get_black_pixels(diff)<EOL>total_pixels = diff.size[<NUM_LIT:0>] * diff.size[<NUM_LIT:1>]<EOL>similarity_ratio = black_pixels / total_pixels<EOL>self.assertTrue(<EOL><NUM_LIT:1> - similarity_ratio < diff_tolerance,<EOL>'<STR_LIT>'<EOL>.format(diff_tolerance * <NUM_LIT:100>))<EOL>

Checks if both images are similar enough to be considered equal.
        Similarity is controlled by the ```diff_tolerance``` argument.


def assertEqualElement(self, expected, element):

Asserts the top,mid,bot trio
Args:
    expected (list[top,mid,bot]): What is expected.
    element (DrawElement): The element to check.


def random_circuit(self, width=<NUM_LIT:3>, depth=<NUM_LIT:3>, max_operands=<NUM_LIT:3>):

qr = QuantumRegister(width, "<STR_LIT:q>")<EOL>qc = QuantumCircuit(qr)<EOL>one_q_ops = "<STR_LIT>"<EOL>two_q_ops = "<STR_LIT>"<EOL>three_q_ops = "<STR_LIT>"<EOL>seed = np.random.randint(<NUM_LIT:0>, np.iinfo(np.int32).max)<EOL>logger.debug("<STR_LIT>", seed)<EOL>rng = np.random.RandomState(seed)<EOL>for _ in range(depth):<EOL><INDENT>remaining_qubits = list(range(width))<EOL>while remaining_qubits:<EOL><INDENT>max_possible_operands = min(len(remaining_qubits), max_operands)<EOL>num_operands = rng.choice(range(max_possible_operands)) + <NUM_LIT:1><EOL>rng.shuffle(remaining_qubits)<EOL>operands = remaining_qubits[:num_operands]<EOL>remaining_qubits = [q for q in remaining_qubits if q not in operands]<EOL>if num_operands == <NUM_LIT:1>:<EOL><INDENT>operation = rng.choice(one_q_ops.split('<STR_LIT:U+002C>'))<EOL><DEDENT>elif num_operands == <NUM_LIT:2>:<EOL><INDENT>operation = rng.choice(two_q_ops.split('<STR_LIT:U+002C>'))<EOL><DEDENT>elif num_operands == <NUM_LIT:3>:<EOL><INDENT>operation = rng.choice(three_q_ops.split('<STR_LIT:U+002C>'))<EOL><DEDENT>gate = getattr(QuantumCircuit, operation)<EOL>op_args = list(signature(gate).parameters.keys())<EOL>num_angles = len(op_args) - num_operands - <NUM_LIT:1>  <EOL>angles = [rng.uniform(<NUM_LIT:0>, <NUM_LIT>) for x in range(num_angles)]<EOL>register_operands = [qr[i] for i in operands]<EOL>gate(qc, *angles, *register_operands)<EOL><DEDENT><DEDENT>return qc<EOL>

Generate random circuit of arbitrary size.
        Note: the depth is the layers of independent operation. true depth
        in the image may be more for visualization purposes, if gates overlap.

        Args:
            width (int): number of quantum wires
            depth (int): layers of operations
            max_operands (int): maximum operands of each gate

        Returns:
            QuantumCircuit: constructed circuit


calib_time = datetime(year=<NUM_LIT>, month=<NUM_LIT:2>, day=<NUM_LIT:1>, hour=<NUM_LIT:0>, minute=<NUM_LIT:0>, second=<NUM_LIT:0>)<EOL>return [Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=<NUM_LIT>),<EOL>Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=<NUM_LIT>),<EOL>Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=<NUM_LIT>),<EOL>Nduv(name="<STR_LIT>", date=calib_time, unit="<STR_LIT>", value=readout_error)]<EOL>


def assertScheduler(self, circuit, passmanager, expected):

with self.assertLogs(logger, level='<STR_LIT>') as cm:<EOL><INDENT>out = transpile(circuit, pass_manager=passmanager)<EOL><DEDENT>self.assertIsInstance(out, QuantumCircuit)<EOL>self.assertEqual([record.message for record in cm.records], expected)<EOL>

Runs transpiler(circuit, passmanager) and checks if the passes run as expected.
Args:
    circuit (QuantumCircuit): Circuit to transform via transpilation.
    passmanager (PassManager): pass manager instance for the transpilation process
    expected (list): List of things the passes are logging


def assertSchedulerRaises(self, circuit, passmanager, expected, exception_type):

with self.assertLogs(logger, level='<STR_LIT>') as cm:<EOL><INDENT>self.assertRaises(exception_type, transpile, circuit, pass_manager=passmanager)<EOL><DEDENT>self.assertEqual([record.message for record in cm.records], expected)<EOL>

Runs transpiler(circuit, passmanager) and checks if the passes run as expected until
exception_type is raised.
Args:
    circuit (QuantumCircuit): Circuit to transform via transpilation
    passmanager (PassManager): pass manager instance for the transpilation process
    expected (list): List of things the passes are logging
    exception_type (Exception): Exception that is expected to be raised.


def create_passmanager(self, coupling_map, initial_layout=None):

passmanager = PassManager(<EOL>self.pass_class(CouplingMap(coupling_map),  <EOL>**self.additional_args))<EOL>if initial_layout:<EOL><INDENT>passmanager.property_set['<STR_LIT>'] = Layout(initial_layout)<EOL><DEDENT>return passmanager<EOL>

Returns a PassManager using self.pass_class(coupling_map, initial_layout)


return BasicAer.get_backend('<STR_LIT>')<EOL>


def generate_ground_truth(self, transpiled_result, filename):

sim_backend = self.create_backend()<EOL>job = execute(transpiled_result, sim_backend, seed=self.seed, shots=self.shots,<EOL>seed_mapper=self.seed_mapper)<EOL>self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta)<EOL>with open(filename, "<STR_LIT:wb>") as output_file:<EOL><INDENT>pickle.dump(transpiled_result, output_file)<EOL><DEDENT>

Generates the expected result into a file.

        Checks if transpiled_result matches self.counts by running in a backend
        (self.create_backend()). That's saved in a pickle in filename.

        Args:
            transpiled_result (DAGCircuit): The DAGCircuit to execute.
            filename (string): Where the pickle is saved.


def assertResult(self, result, circuit):

picklename = '<STR_LIT>' % (type(self).__name__, circuit.name)<EOL>filename = os.path.join(DIRNAME, picklename)<EOL>if self.regenerate_expected:<EOL><INDENT>self.generate_ground_truth(result, filename)<EOL><DEDENT>with open(filename, "<STR_LIT:rb>") as input_file:<EOL><INDENT>expected = pickle.load(input_file)<EOL><DEDENT>self.assertEqual(result, expected)<EOL>

Fetches the pickle in circuit.name file and compares it with result.


def assertCommutationSet(self, result, expected):

result_to_compare = {}<EOL>for qbit_str, sets in result.items():<EOL><INDENT>if not isinstance(qbit_str, str):<EOL><INDENT>continue<EOL><DEDENT>result_to_compare[qbit_str] = []<EOL>for commutation_set in sets:<EOL><INDENT>result_to_compare[qbit_str].append(<EOL>sorted([node._node_id for node in commutation_set]))<EOL><DEDENT><DEDENT>for qbit_str, sets in expected.items():<EOL><INDENT>for commutation_set in sets:<EOL><INDENT>commutation_set.sort()<EOL><DEDENT><DEDENT>self.assertDictEqual(result_to_compare, expected)<EOL>

Compares the result of propertyset["commutation_set"] with a dictionary of the form
        {'q[0]': [ [node_id, ...], [node_id, ...] ]}


import importlib<EOL>import concurrent.futures as futures<EOL>import qiskit.providers.basicaer.basicaerjob as basicaerjob<EOL>executor = unittest.mock.MagicMock(spec=futures.Executor)<EOL>executor.submit.return_value = unittest.mock.MagicMock(spec=futures.Future)<EOL>mock_options = {'<STR_LIT>': executor, '<STR_LIT>': True}<EOL>with patch.object(futures, '<STR_LIT>', **mock_options),patch.object(futures, '<STR_LIT>', **mock_options):<EOL><INDENT>importlib.reload(basicaerjob)<EOL>yield basicaerjob.BasicAerJob, executor<EOL><DEDENT>

Context that patches the derived executor classes to return the same
    executor object. Also patches the future object returned by executor's
    submit().


with patch.object(path, '<STR_LIT>', return_value=True, autospec=True),patch.object(path, '<STR_LIT>', return_value=<NUM_LIT:1000>, autospec=True):<EOL><INDENT>yield<EOL><DEDENT>

Context to force binary-based simulators to think the simulators exist.


call_count = mocked_callable.call_count<EOL>self.assertEqual(<EOL>call_count, <NUM_LIT:1>,<EOL>'<STR_LIT>'.format(<EOL>call_count))<EOL>

Assert a mocked callable has been called once.


if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:5>):<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>


deprecation_filter = ('<STR_LIT>', None, DeprecationWarning,<EOL>re.compile(r'<STR_LIT>', re.UNICODE), <NUM_LIT:0>)<EOL>try:<EOL><INDENT>warnings._add_filter(*deprecation_filter, append=False)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>warnings.simplefilter('<STR_LIT:ignore>', category=ChangedInMarshmallow3Warning)<EOL>

Apply filters to deprecation warnings.

    Force the `DeprecationWarning` warnings to be displayed for the qiskit
    module, overriding the system configuration as they are ignored by default
    [1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
    messages.

    TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].

    [1] https://docs.python.org/3/library/warnings.html#default-warning-filters
    [2] https://www.python.org/dev/peps/pep-0565/


results = {<EOL>'<STR_LIT>': platform.system(),<EOL>'<STR_LIT>': psutil.virtual_memory().total / (<NUM_LIT> ** <NUM_LIT:3>),<EOL>'<STR_LIT>': psutil.cpu_count(logical=False) or <NUM_LIT:1><EOL>}<EOL>return results<EOL>

Basic hardware information about the local machine.

    Gives actual number of CPU's in the machine, even when hyperthreading is
    turned on. CPU count defaults to 1 when true count can't be determined.

    Returns:
        dict: The hardware information.


try:<EOL><INDENT>host = socket.gethostbyname(hostname)<EOL>socket.create_connection((host, port), <NUM_LIT:2>)<EOL>return True<EOL><DEDENT>except Exception:  <EOL><INDENT>return False<EOL><DEDENT>

Checks if internet connection exists to host via specified port.

    If any exception is raised while trying to open a socket this will return
    false.

    Args:
        hostname (str): Hostname to connect to.
        port (int): Port to connect to

    Returns:
        bool: Has connection or not


def compile(circuits, backend,<EOL>config=None, basis_gates=None, coupling_map=None, initial_layout=None,<EOL>shots=<NUM_LIT>, max_credits=<NUM_LIT:10>, seed=None, qobj_id=None, seed_mapper=None,<EOL>pass_manager=None, memory=False):

Compile a list of circuits into a qobj.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (list[str]): list of basis gates names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        seed_mapper (int): random seed for swapper mapper
        qobj_id (int): identifier for the generated qobj
        pass_manager (PassManager): a pass manger for the transpiler pipeline
        memory (bool): if True, per-shot measurement bitstrings are returned as well

    Returns:
        Qobj: the qobj to be run on the backends

    Raises:
        QiskitError: if the desired options are not supported by backend


Update 'qiskit' logger configuration using a SDK default one.

    Update the configuration of the 'qiskit' logger using the default SDK
    configuration provided by `QISKIT_LOGGING_CONFIG`:

    * console logging using a custom format for levels != INFO.
    * console logging with simple format for level INFO.
    * set logger level to INFO.

    Warning:
        This function modifies the configuration of the standard logging system
        for the 'qiskit.*' loggers, and might interfere with custom logger
        configurations.


qiskit_logger = logging.getLogger('<STR_LIT>')<EOL>for handler in qiskit_logger.handlers:<EOL><INDENT>qiskit_logger.removeHandler(handler)<EOL><DEDENT>

Remove the handlers for the 'qiskit' logger.


for j in range(n):<EOL><INDENT>for k in range(j):<EOL><INDENT>circ.cu1(math.pi / float(<NUM_LIT:2>**(j - k)), q[j], q[k])<EOL><DEDENT>circ.h(q[j])<EOL><DEDENT>


def partial_trace(state, trace_systems, dimensions=None, reverse=True):

state = np.array(state)  <EOL>if dimensions is None:  <EOL><INDENT>num_qubits = int(np.log2(len(state)))<EOL>dimensions = [<NUM_LIT:2> for _ in range(num_qubits)]<EOL>if len(state) != <NUM_LIT:2> ** num_qubits:<EOL><INDENT>raise Exception("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>dimensions = list(dimensions)<EOL><DEDENT>if isinstance(trace_systems, int):<EOL><INDENT>trace_systems = [trace_systems]<EOL><DEDENT>else:  <EOL><INDENT>trace_systems = sorted(trace_systems, reverse=True)<EOL><DEDENT>if state.ndim == <NUM_LIT:1>:<EOL><INDENT>return __partial_trace_vec(state, trace_systems, dimensions, reverse)<EOL><DEDENT>return __partial_trace_mat(state, trace_systems, dimensions, reverse)<EOL>

Partial trace over subsystems of multi-partite matrix.

Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.

Args:
    state (matrix_like): a matrix NxN
    trace_systems (list(int)): a list of subsystems (starting from 0) to
                              trace over.
    dimensions (list(int)): a list of the dimensions of the subsystems.
                            If this is not set it will assume all
                            subsystems are qubits.
    reverse (bool): ordering of systems in operator.
        If True system-0 is the right most system in tensor product.
        If False system-0 is the left most system in tensor product.

Returns:
    matrix_like: A density matrix with the appropriate subsystems traced
        over.
Raises:
    Exception: if input is not a multi-qubit state.


def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):

<EOL>if reverse:<EOL><INDENT>dimensions = dimensions[::-<NUM_LIT:1>]<EOL>trace_systems = len(dimensions) - <NUM_LIT:1> - np.array(trace_systems)<EOL><DEDENT>rho = vec.reshape(dimensions)<EOL>rho = np.tensordot(rho, rho.conj(), axes=(trace_systems, trace_systems))<EOL>d = int(np.sqrt(np.product(rho.shape)))<EOL>return rho.reshape(d, d)<EOL>

Partial trace over subsystems of multi-partite vector.

Args:
    vec (vector_like): complex vector N
    trace_systems (list(int)): a list of subsystems (starting from 0) to
                              trace over.
    dimensions (list(int)): a list of the dimensions of the subsystems.
                            If this is not set it will assume all
                            subsystems are qubits.
    reverse (bool): ordering of systems in operator.
        If True system-0 is the right most system in tensor product.
        If False system-0 is the left most system in tensor product.

Returns:
    ndarray: A density matrix with the appropriate subsystems traced over.


def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True):

trace_systems = sorted(trace_systems, reverse=True)<EOL>for j in trace_systems:<EOL><INDENT>dimension_trace = int(dimensions[j])  <EOL>if reverse:<EOL><INDENT>left_dimensions = dimensions[j + <NUM_LIT:1>:]<EOL>right_dimensions = dimensions[:j]<EOL>dimensions = right_dimensions + left_dimensions<EOL><DEDENT>else:<EOL><INDENT>left_dimensions = dimensions[:j]<EOL>right_dimensions = dimensions[j + <NUM_LIT:1>:]<EOL>dimensions = left_dimensions + right_dimensions<EOL><DEDENT>dimension_left = int(np.prod(left_dimensions))<EOL>dimension_right = int(np.prod(right_dimensions))<EOL>mat = mat.reshape([dimension_left, dimension_trace, dimension_right,<EOL>dimension_left, dimension_trace, dimension_right])<EOL>mat = mat.trace(axis1=<NUM_LIT:1>, axis2=<NUM_LIT:4>).reshape(<EOL>dimension_left * dimension_right,<EOL>dimension_left * dimension_right)<EOL><DEDENT>return mat<EOL>

Partial trace over subsystems of multi-partite matrix.

Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.

Args:
    mat (matrix_like): a matrix NxN.
    trace_systems (list(int)): a list of subsystems (starting from 0) to
                              trace over.
    dimensions (list(int)): a list of the dimensions of the subsystems.
                            If this is not set it will assume all
                            subsystems are qubits.
    reverse (bool): ordering of systems in operator.
        If True system-0 is the right most system in tensor product.
        If False system-0 is the left most system in tensor product.

Returns:
    ndarray: A density matrix with the appropriate subsystems traced over.


density_matrix = np.array(density_matrix)<EOL>if method == '<STR_LIT>':<EOL><INDENT>return density_matrix.flatten(order='<STR_LIT:F>')<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return density_matrix.flatten(order='<STR_LIT:C>')<EOL><DEDENT>elif method in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>num = int(np.log2(len(density_matrix)))  <EOL>if len(density_matrix) != <NUM_LIT:2>**num:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>pgroup = pauli_group(num, case='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>pgroup = pauli_group(num, case='<STR_LIT>')<EOL><DEDENT>vals = [np.trace(np.dot(p.to_matrix(), density_matrix))<EOL>for p in pgroup]<EOL>return np.array(vals)<EOL><DEDENT>return None<EOL>

Flatten an operator to a vector in a specified basis.

    Args:
        density_matrix (ndarray): a density matrix.
        method (str): the method of vectorization. Allowed values are
            - 'col' (default) flattens to column-major vector.
            - 'row' flattens to row-major vector.
            - 'pauli'flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting vector.
    Raises:
        Exception: if input state is not a n-qubit state


vectorized_mat = np.array(vectorized_mat)<EOL>dimension = int(np.sqrt(vectorized_mat.size))<EOL>if len(vectorized_mat) != dimension * dimension:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>return vectorized_mat.reshape(dimension, dimension, order='<STR_LIT:F>')<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return vectorized_mat.reshape(dimension, dimension, order='<STR_LIT:C>')<EOL><DEDENT>elif method in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>num_qubits = int(np.log2(dimension))  <EOL>if dimension != <NUM_LIT:2> ** num_qubits:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>pgroup = pauli_group(num_qubits, case='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>pgroup = pauli_group(num_qubits, case='<STR_LIT>')<EOL><DEDENT>pbasis = np.array([p.to_matrix() for p in pgroup]) / <NUM_LIT:2> ** num_qubits<EOL>return np.tensordot(vectorized_mat, pbasis, axes=<NUM_LIT:1>)<EOL><DEDENT>return None<EOL>

Devectorize a vectorized square matrix.

    Args:
        vectorized_mat (ndarray): a vectorized density matrix.
        method (str): the method of devectorization. Allowed values are
            - 'col' (default): flattens to column-major vector.
            - 'row': flattens to row-major vector.
            - 'pauli': flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting matrix.
    Raises:
        Exception: if input state is not a n-qubit state


if order == <NUM_LIT:0>:<EOL><INDENT>order = '<STR_LIT>'<EOL><DEDENT>elif order == <NUM_LIT:1>:<EOL><INDENT>order = '<STR_LIT>'<EOL><DEDENT>num_qubits = int(np.log2(np.sqrt(len(choi))))<EOL>pgp = pauli_group(num_qubits, case=order)<EOL>rauli = []<EOL>for i in pgp:<EOL><INDENT>for j in pgp:<EOL><INDENT>pauliop = np.kron(j.to_matrix().T, i.to_matrix())<EOL>rauli += [np.trace(np.dot(choi, pauliop))]<EOL><DEDENT><DEDENT>return np.array(rauli).reshape(<NUM_LIT:4> ** num_qubits, <NUM_LIT:4> ** num_qubits)<EOL>

Convert a Choi-matrix to a Pauli-basis superoperator.

Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bell_state).

The resulting 'rauli' R acts on input states as
|rho_out>_p = R.|rho_in>_p
where |rho> = vectorize(rho, method='pauli') for order=1
and |rho> = vectorize(rho, method='pauli_weights') for order=0.

Args:
    choi (matrix): the input Choi-matrix.
    order (int): ordering of the Pauli group vector.
        order=1 (default) is standard lexicographic ordering.
            Eg: [II, IX, IY, IZ, XI, XX, XY,...]
        order=0 is ordered by weights.
            Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...]

Returns:
    np.array: A superoperator in the Pauli basis.


ret = np.array(array)<EOL>if np.isrealobj(ret):<EOL><INDENT>ret[abs(ret) < epsilon] = <NUM_LIT:0.0><EOL><DEDENT>else:<EOL><INDENT>ret.real[abs(ret.real) < epsilon] = <NUM_LIT:0.0><EOL>ret.imag[abs(ret.imag) < epsilon] = <NUM_LIT:0.0><EOL><DEDENT>return ret<EOL>

Truncate small values of a complex array.

Args:
    array (array_like): array to truncte small values.
    epsilon (float): threshold.

Returns:
    np.array: A new operator with small values set to zero.


if vector2 is None:<EOL><INDENT>vector2 = np.array(vector1).conj()<EOL><DEDENT>else:<EOL><INDENT>vector2 = np.array(vector2).conj()<EOL><DEDENT>return np.outer(vector1, vector2)<EOL>

Construct the outer product of two vectors.

The second vector argument is optional, if absent the projector
of the first vector will be returned.

Args:
    vector1 (ndarray): the first vector.
    vector2 (ndarray): the (optional) second vector.

Returns:
    np.array: The matrix |v1><v2|.


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>return random.random_unitary(dim, seed).data<EOL>


def random_density_matrix(length, rank=None, method='<STR_LIT>', seed=None):

warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>return random.random_density_matrix(length, rank, method, seed)<EOL>


warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>DeprecationWarning)<EOL>return new_purity(state)<EOL>

Calculate the purity of a quantum state.

    Args:
        state (np.array): a quantum state
    Returns:
        float: purity.


rho = np.array(state)<EOL>if rho.ndim == <NUM_LIT:1>:<EOL><INDENT>rho = outer(state)<EOL><DEDENT>if len(state) != <NUM_LIT:4>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>YY = np.fliplr(np.diag([-<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, -<NUM_LIT:1>]))<EOL>A = rho.dot(YY).dot(rho.conj()).dot(YY)<EOL>w = la.eigh(A, eigvals_only=True)<EOL>w = np.sqrt(np.maximum(w, <NUM_LIT:0>))<EOL>return max(<NUM_LIT:0.0>, w[-<NUM_LIT:1>] - np.sum(w[<NUM_LIT:0>:-<NUM_LIT:1>]))<EOL>

Calculate the concurrence.

    Args:
        state (np.array): a quantum state (1x4 array) or a density matrix (4x4
                          array)
    Returns:
        float: concurrence.
    Raises:
        Exception: if attempted on more than two qubits.


<EOL>if base == <NUM_LIT:2>:<EOL><INDENT>def logfn(x):<EOL><INDENT>return - x * np.log2(x)<EOL><DEDENT><DEDENT>elif base == np.e:<EOL><INDENT>def logfn(x):<EOL><INDENT>return - x * np.log(x)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def logfn(x):<EOL><INDENT>return -x * np.log(x) / np.log(base)<EOL><DEDENT><DEDENT>h = <NUM_LIT:0.><EOL>for x in pvec:<EOL><INDENT>if <NUM_LIT:0> < x < <NUM_LIT:1>:<EOL><INDENT>h += logfn(x)<EOL><DEDENT><DEDENT>return h<EOL>

Compute the Shannon entropy of a probability vector.

The shannon entropy of a probability vector pv is defined as
$H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.

Args:
    pvec (array_like): a probability vector.
    base (int): the base of the logarith

Returns:
    float: The Shannon entropy H(pvec).


rho = np.array(state)<EOL>if rho.ndim == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>evals = np.maximum(np.linalg.eigvalsh(state), <NUM_LIT:0.>)<EOL>return shannon_entropy(evals, base=np.e)<EOL>

Compute the von-Neumann entropy of a quantum state.

Args:
    state (array_like): a density matrix or state vector.

Returns:
    float: The von-Neumann entropy S(rho).


def mutual_information(state, d0, d1=None):

if d1 is None:<EOL><INDENT>d1 = int(len(state) / d0)<EOL><DEDENT>mi = entropy(partial_trace(state, [<NUM_LIT:0>], dimensions=[d0, d1]))<EOL>mi += entropy(partial_trace(state, [<NUM_LIT:1>], dimensions=[d0, d1]))<EOL>mi -= entropy(state)<EOL>return mi<EOL>

Compute the mutual information of a bipartite state.

Args:
    state (array_like): a bipartite state-vector or density-matrix.
    d0 (int): dimension of the first subsystem.
    d1 (int or None): dimension of the second subsystem.

Returns:
    float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).


def entanglement_of_formation(state, d0, d1=None):

state = np.array(state)<EOL>if d1 is None:<EOL><INDENT>d1 = int(len(state) / d0)<EOL><DEDENT>if state.ndim == <NUM_LIT:2> and len(state) == <NUM_LIT:4> and d0 == <NUM_LIT:2> and d1 == <NUM_LIT:2>:<EOL><INDENT>return __eof_qubit(state)<EOL><DEDENT>elif state.ndim == <NUM_LIT:1>:<EOL><INDENT>if d0 < d1:<EOL><INDENT>tr = [<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>tr = [<NUM_LIT:0>]<EOL><DEDENT>state = partial_trace(state, tr, dimensions=[d0, d1])<EOL>return entropy(state)<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>return None<EOL>

Compute the entanglement of formation of quantum state.

The input quantum state must be either a bipartite state vector, or a
2-qubit density matrix.

Args:
    state (array_like): (N) array_like or (4,4) array_like, a
        bipartite quantum state.
    d0 (int): the dimension of the first subsystem.
    d1 (int or None): the dimension of the second subsystem.

Returns:
    float: The entanglement of formation.


c = concurrence(rho)<EOL>c = <NUM_LIT:0.5> + <NUM_LIT:0.5> * np.sqrt(<NUM_LIT:1> - c * c)<EOL>return shannon_entropy([c, <NUM_LIT:1> - c])<EOL>

Compute the Entanglement of Formation of a 2-qubit density matrix.

Args:
    rho ((array_like): (4,4) array_like, input density matrix.

Returns:
    float: The entanglement of formation.


return np.all(np.linalg.eigvals(x) > <NUM_LIT:0>)<EOL>


def _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):

status = job.status()<EOL>msg = status.value<EOL>prev_msg = msg<EOL>msg_len = len(msg)<EOL>if not quiet:<EOL><INDENT>print('<STR_LIT>' % ('<STR_LIT>', msg), end='<STR_LIT>', file=output)<EOL><DEDENT>while status.name not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>time.sleep(interval)<EOL>status = job.status()<EOL>msg = status.value<EOL>if status.name == '<STR_LIT>':<EOL><INDENT>msg += '<STR_LIT>' % job.queue_position()<EOL>if not _interval_set:<EOL><INDENT>interval = max(job.queue_position(), <NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not _interval_set:<EOL><INDENT>interval = <NUM_LIT:2><EOL><DEDENT><DEDENT>if len(msg) < msg_len:<EOL><INDENT>msg += '<STR_LIT:U+0020>' * (msg_len - len(msg))<EOL><DEDENT>elif len(msg) > msg_len:<EOL><INDENT>msg_len = len(msg)<EOL><DEDENT>if msg != prev_msg and not quiet:<EOL><INDENT>print('<STR_LIT>' % ('<STR_LIT>', msg), end='<STR_LIT>', file=output)<EOL>prev_msg = msg<EOL><DEDENT><DEDENT>if not quiet:<EOL><INDENT>print('<STR_LIT>', file=output)<EOL><DEDENT>

A text-based job status checker

    Args:
        job (BaseJob): The job to check.
        interval (int): The interval at which to check.
        _interval_set (bool): Was interval time set by user?
        quiet (bool): If True, do not print status messages.
        output (file): The file like object to write status messages to.
        By default this is sys.stdout.


def job_monitor(job, interval=None, monitor_async=False, quiet=False, output=sys.stdout):

if interval is None:<EOL><INDENT>_interval_set = False<EOL>interval = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>_interval_set = True<EOL><DEDENT>if _NOTEBOOK_ENV:<EOL><INDENT>if monitor_async:<EOL><INDENT>try:<EOL><INDENT>import ipywidgets as widgets  <EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>from qiskit.tools.jupyter.jupyter_magics import _html_checker  <EOL>style = "<STR_LIT>"<EOL>header = "<STR_LIT>".format(<EOL>style=style)<EOL>status = widgets.HTML(value=header % job.status().value)<EOL>display(status)<EOL>thread = threading.Thread(target=_html_checker, args=(job, interval,<EOL>status, header))<EOL>thread.start()<EOL><DEDENT>else:<EOL><INDENT>_text_checker(job, interval, _interval_set,<EOL>quiet=quiet, output=output)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if monitor_async:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>')<EOL><DEDENT>_text_checker(job, interval, _interval_set, quiet=quiet, output=output)<EOL><DEDENT>

Monitor the status of a IBMQJob instance.

    Args:
        job (BaseJob): Job to monitor.
        interval (int): Time interval between status queries.
        monitor_async (bool): Monitor asyncronously (in Jupyter only).
        quiet (bool): If True, do not print status messages.
        output (file): The file like object to write status messages to.
        By default this is sys.stdout.

    Raises:
        QiskitError: When trying to run async outside of Jupyter
        ImportError: ipywidgets not available for notebook.


backends = IBMQ.backends()<EOL>unique_hardware_backends = []<EOL>unique_names = []<EOL>for back in backends:<EOL><INDENT>if back.name() not in unique_names and not back.configuration().simulator:<EOL><INDENT>unique_hardware_backends.append(back)<EOL>unique_names.append(back.name())<EOL><DEDENT><DEDENT>if not unique_hardware_backends:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>return unique_hardware_backends<EOL>

Gets the unique backends that are available.

    Returns:
        list: Unique available backends.

    Raises:
        QiskitError: No backends available.


if not isinstance(backend, IBMQBackend):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>config = backend.configuration().to_dict()<EOL>status = backend.status().to_dict()<EOL>config_dict = {**status, **config}<EOL>if not config['<STR_LIT>']:<EOL><INDENT>props = backend.properties().to_dict()<EOL><DEDENT>print(backend.name())<EOL>print('<STR_LIT:=>'*len(backend.name()))<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT:->'*<NUM_LIT>)<EOL>offset = '<STR_LIT:U+0020>'<EOL>upper_list = ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>lower_list = list(set(config_dict.keys()).difference(upper_list))<EOL>lower_list.remove('<STR_LIT>')<EOL>for item in upper_list+lower_list:<EOL><INDENT>print(offset+item+'<STR_LIT::>', config_dict[item])<EOL><DEDENT>if config['<STR_LIT>']:<EOL><INDENT>return<EOL><DEDENT>print()<EOL>qubit_header = '<STR_LIT>'<EOL>print(qubit_header)<EOL>print('<STR_LIT:->'*len(qubit_header))<EOL>sep = '<STR_LIT>'<EOL>for qub in range(len(props['<STR_LIT>'])):<EOL><INDENT>name = '<STR_LIT>' % qub<EOL>qubit_data = props['<STR_LIT>'][qub]<EOL>gate_data = props['<STR_LIT>'][<NUM_LIT:3>*qub:<NUM_LIT:3>*qub+<NUM_LIT:3>]<EOL>t1_info = qubit_data[<NUM_LIT:0>]<EOL>t2_info = qubit_data[<NUM_LIT:1>]<EOL>freq_info = qubit_data[<NUM_LIT:2>]<EOL>readout_info = qubit_data[<NUM_LIT:3>]<EOL>freq = str(round(freq_info['<STR_LIT:value>'], <NUM_LIT:5>))+'<STR_LIT:U+0020>'+freq_info['<STR_LIT>']<EOL>T1 = str(round(t1_info['<STR_LIT:value>'],  <EOL><NUM_LIT:5>))+'<STR_LIT:U+0020>' + t1_info['<STR_LIT>']<EOL>T2 = str(round(t2_info['<STR_LIT:value>'],  <EOL><NUM_LIT:5>))+'<STR_LIT:U+0020>' + t2_info['<STR_LIT>']<EOL>U1 = str(round(gate_data[<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>U2 = str(round(gate_data[<NUM_LIT:1>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>U3 = str(round(gate_data[<NUM_LIT:2>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>readout_error = str(round(readout_info['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>qstr = sep.join([name, freq, T1, T2, U1, U2, U3, readout_error])<EOL>print(offset+qstr)<EOL><DEDENT>print()<EOL>multi_qubit_gates = props['<STR_LIT>'][<NUM_LIT:3>*config['<STR_LIT>']:]<EOL>multi_header = '<STR_LIT>'<EOL>print(multi_header)<EOL>print('<STR_LIT:->'*len(multi_header))<EOL>for gate in multi_qubit_gates:<EOL><INDENT>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = str(round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>mstr = sep.join([name, ttype, error])<EOL>print(offset+mstr)<EOL><DEDENT>

Monitor a single IBMQ backend.

    Args:
        backend (IBMQBackend): Backend to monitor.
    Raises:
        QiskitError: Input is not a IBMQ backend.


unique_hardware_backends = get_unique_backends()<EOL>_backends = []<EOL>for idx, back in enumerate(unique_hardware_backends):<EOL><INDENT>if back.status().operational:<EOL><INDENT>_backends = [back] + _backends<EOL><DEDENT>else:<EOL><INDENT>_backends = _backends + [back]<EOL><DEDENT><DEDENT>stati = [back.status() for back in _backends]<EOL>idx = list(range(len(_backends)))<EOL>pending = [s.pending_jobs for s in stati]<EOL>_, least_idx = zip(*sorted(zip(pending, idx)))<EOL>for ind in least_idx:<EOL><INDENT>if stati[ind].operational:<EOL><INDENT>least_pending_idx = ind<EOL>break<EOL><DEDENT><DEDENT>num_rows = math.ceil(len(_backends)/<NUM_LIT:3>)<EOL>count = <NUM_LIT:0><EOL>num_backends = len(_backends)<EOL>for _ in range(num_rows):<EOL><INDENT>max_len = <NUM_LIT:0><EOL>str_list = ['<STR_LIT>']*<NUM_LIT:8><EOL>for idx in range(<NUM_LIT:3>):<EOL><INDENT>offset = '<STR_LIT:U+0020>' * <NUM_LIT:10> if idx else '<STR_LIT>'<EOL>config = _backends[count].configuration().to_dict()<EOL>props = _backends[count].properties().to_dict()<EOL>n_qubits = config['<STR_LIT>']<EOL>str_list[<NUM_LIT:0>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:0>]))+offset)<EOL>str_list[<NUM_LIT:0>] += _backends[count].name()<EOL>str_list[<NUM_LIT:1>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:1>]))+offset)<EOL>str_list[<NUM_LIT:1>] += '<STR_LIT:->'*len(_backends[count].name())<EOL>str_list[<NUM_LIT:2>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:2>]))+offset)<EOL>str_list[<NUM_LIT:2>] += '<STR_LIT>' % config['<STR_LIT>']<EOL>str_list[<NUM_LIT:3>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:3>]))+offset)<EOL>str_list[<NUM_LIT:3>] += '<STR_LIT>' % stati[count].pending_jobs<EOL>str_list[<NUM_LIT:4>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:4>]))+offset)<EOL>str_list[<NUM_LIT:4>] += '<STR_LIT>' % (count == least_pending_idx)<EOL>str_list[<NUM_LIT:5>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:5>]))+offset)<EOL>str_list[<NUM_LIT:5>] += '<STR_LIT>' % stati[count].operational<EOL>str_list[<NUM_LIT:6>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:6>]))+offset)<EOL>str_list[<NUM_LIT:6>] += '<STR_LIT>' % round(sum([q[<NUM_LIT:0>]['<STR_LIT:value>']<EOL>for q in props['<STR_LIT>']])/n_qubits, <NUM_LIT:1>)<EOL>str_list[<NUM_LIT:7>] += ('<STR_LIT:U+0020>'*(max_len-len(str_list[<NUM_LIT:7>]))+offset)<EOL>str_list[<NUM_LIT:7>] += '<STR_LIT>' % round(sum([q[<NUM_LIT:1>]['<STR_LIT:value>']<EOL>for q in props['<STR_LIT>']])/n_qubits, <NUM_LIT:1>)<EOL>count += <NUM_LIT:1><EOL>if count == num_backends:<EOL><INDENT>break<EOL><DEDENT>max_len = max([len(s) for s in str_list])<EOL><DEDENT>print("<STR_LIT:\n>".join(str_list))<EOL>print('<STR_LIT:\n>'*<NUM_LIT:2>)<EOL><DEDENT>

Gives overview information on all the IBMQ
    backends that are available.


def parallel_map(task, values, task_args=tuple(), task_kwargs={},  <EOL>num_processes=CPU_COUNT):

if len(values) == <NUM_LIT:1>:<EOL><INDENT>return [task(values[<NUM_LIT:0>], *task_args, **task_kwargs)]<EOL><DEDENT>Publisher().publish("<STR_LIT>", len(values))<EOL>nfinished = [<NUM_LIT:0>]<EOL>def _callback(_):<EOL><INDENT>nfinished[<NUM_LIT:0>] += <NUM_LIT:1><EOL>Publisher().publish("<STR_LIT>", nfinished[<NUM_LIT:0>])<EOL><DEDENT>if platform.system() != '<STR_LIT>' and num_processes > <NUM_LIT:1>and os.getenv('<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>try:<EOL><INDENT>pool = Pool(processes=num_processes)<EOL>async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,<EOL>_callback) for value in values]<EOL>while not all([item.ready() for item in async_res]):<EOL><INDENT>for item in async_res:<EOL><INDENT>item.wait(timeout=<NUM_LIT:0.1>)<EOL><DEDENT><DEDENT>pool.terminate()<EOL>pool.join()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pool.terminate()<EOL>pool.join()<EOL>Publisher().publish("<STR_LIT>")<EOL>raise QiskitError('<STR_LIT>')<EOL><DEDENT>Publisher().publish("<STR_LIT>")<EOL>os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>return [ar.get() for ar in async_res]<EOL><DEDENT>results = []<EOL>for _, value in enumerate(values):<EOL><INDENT>result = task(value, *task_args, **task_kwargs)<EOL>results.append(result)<EOL>_callback(<NUM_LIT:0>)<EOL><DEDENT>Publisher().publish("<STR_LIT>")<EOL>return results<EOL>

Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::

    result = [task(value, *task_args, **task_kwargs) for value in values]

On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.

Args:
    task (func): Function that is to be called for each value in ``values``.
    values (array_like): List or array of values for which the ``task``
                        function is to be evaluated.
    task_args (list): Optional additional arguments to the ``task`` function.
    task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
    num_processes (int): Number of processes to spawn.

Returns:
    result: The result list contains the value of
            ``task(value, *task_args, **task_kwargs)`` for
                each value in ``values``.

Raises:
    QiskitError: If user interrupts via keyboard.

Events:
    terra.parallel.start: The collection of parallel tasks are about to start.
    terra.parallel.update: One of the parallel task has finished.
    terra.parallel.finish: All the parallel tasks have finished.


if not callable(callback):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if event not in self._subscribers:<EOL><INDENT>self._subscribers[event] = []<EOL><DEDENT>new_subscription = self._Subscription(event, callback)<EOL>if new_subscription in self._subscribers[event]:<EOL><INDENT>return False<EOL><DEDENT>self._subscribers[event].append(new_subscription)<EOL>return True<EOL>

Subscribes to an event, so when it's emitted all the callbacks subscribed,
        will be executed. We are not allowing double registration.

        Args
            event (string): The event to subscribed in the form of:
                            "terra.<component>.<method>.<action>"
            callback (callable): The callback that will be executed when an event is
                                  emitted.


def dispatch(self, event, *args, **kwargs):

<EOL>if event not in self._subscribers:<EOL><INDENT>return<EOL><DEDENT>for subscriber in self._subscribers[event]:<EOL><INDENT>subscriber.callback(*args, **kwargs)<EOL><DEDENT>

Emits an event if there are any subscribers.

        Args
            event (String): The event to be emitted
            args: Arguments linked with the event
            kwargs: Named arguments linked with the event


try:<EOL><INDENT>self._subscribers[event].remove(self._Subscription(event, callback))<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Unsubscribe the specific callback to the event.

        Args
            event (String): The event to unsubscribe
            callback (callable): The callback that won't be executed anymore

        Returns
            True: if we have successfully unsubscribed to the event
            False: if there's no callback previously registered


Unsubscribe everything, leaving the Broker without subscribers/events.


def publish(self, event, *args, **kwargs):

return self._broker.dispatch(event, *args, **kwargs)<EOL>

Triggers an event, and associates some data to it, so if there are any
        subscribers, their callback will be called synchronously.


return self._broker.subscribe(event, callback)<EOL>

Subscribes to an event, associating a callback function to that event, so
        when the event occurs, the callback will be called.
        This is a blocking call, so try to keep callbacks as lighweight as possible.


return self._broker.unsubscribe(event, callback)<EOL>

Unsubscribe a pair event-callback, so the callback will not be called anymore
        when the event occurs.


self.touched = True<EOL>self.iter = int(iterations)<EOL>self.t_start = time.time()<EOL>

Start the progress bar.

        Parameters:
            iterations (int): Number of iterations.


pass<EOL>


return "<STR_LIT>" % (time.time() - self.t_start)<EOL>

Return the time elapsed since start.

        Returns:
            elapsed_time: Time since progress bar started.


if completed_iter:<EOL><INDENT>t_r_est = (time.time() - self.t_start) /completed_iter*(self.iter-completed_iter)<EOL><DEDENT>else:<EOL><INDENT>t_r_est = <NUM_LIT:0><EOL><DEDENT>date_time = datetime.datetime(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>) + datetime.timedelta(seconds=t_r_est)<EOL>time_string = "<STR_LIT>" %(date_time.day - <NUM_LIT:1>, date_time.hour, date_time.minute, date_time.second)<EOL>return time_string<EOL>

Estimate the remaining time left.

        Parameters:
            completed_iter (int): Number of iterations completed.

        Returns:
            est_time: Estimated time remaining.


def tomography_basis(basis, prep_fun=None, meas_fun=None):

ret = TomographyBasis(basis)<EOL>ret.prep_fun = prep_fun<EOL>ret.meas_fun = meas_fun<EOL>return ret<EOL>

Generate a TomographyBasis object.

See TomographyBasis for further details.abs

Args:
    prep_fun (callable) optional: the function which adds preparation
        gates to a circuit.
    meas_fun (callable) optional: the function which adds measurement
        gates to a circuit.

Returns:
    TomographyBasis: A tomography basis.


def __pauli_prep_gates(circuit, qreg, op):

bas, proj = op<EOL>if bas not in ['<STR_LIT:X>', '<STR_LIT:Y>', '<STR_LIT>']:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if bas == "<STR_LIT:X>":<EOL><INDENT>if proj == <NUM_LIT:1>:<EOL><INDENT>circuit.u2(np.pi, np.pi, qreg)  <EOL><DEDENT>else:<EOL><INDENT>circuit.u2(<NUM_LIT:0.>, np.pi, qreg)  <EOL><DEDENT><DEDENT>elif bas == "<STR_LIT:Y>":<EOL><INDENT>if proj == <NUM_LIT:1>:<EOL><INDENT>circuit.u2(-<NUM_LIT:0.5> * np.pi, np.pi, qreg)  <EOL><DEDENT>else:<EOL><INDENT>circuit.u2(<NUM_LIT:0.5> * np.pi, np.pi, qreg)  <EOL><DEDENT><DEDENT>elif bas == "<STR_LIT>" and proj == <NUM_LIT:1>:<EOL><INDENT>circuit.u3(np.pi, <NUM_LIT:0.>, np.pi, qreg)<EOL><DEDENT>

Add state preparation gates to a circuit.


def __pauli_meas_gates(circuit, qreg, op):

if op not in ['<STR_LIT:X>', '<STR_LIT:Y>', '<STR_LIT>']:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if op == "<STR_LIT:X>":<EOL><INDENT>circuit.u2(<NUM_LIT:0.>, np.pi, qreg)  <EOL><DEDENT>elif op == "<STR_LIT:Y>":<EOL><INDENT>circuit.u2(<NUM_LIT:0.>, <NUM_LIT:0.5> * np.pi, qreg)<EOL><DEDENT>

Add state measurement gates to a circuit.


def __sic_prep_gates(circuit, qreg, op):

bas, proj = op<EOL>if bas != '<STR_LIT:S>':<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>theta = -<NUM_LIT:2> * np.arctan(np.sqrt(<NUM_LIT:2>))<EOL>if proj == <NUM_LIT:1>:<EOL><INDENT>circuit.u3(theta, np.pi, <NUM_LIT:0.0>, qreg)<EOL><DEDENT>elif proj == <NUM_LIT:2>:<EOL><INDENT>circuit.u3(theta, np.pi / <NUM_LIT:3>, <NUM_LIT:0.0>, qreg)<EOL><DEDENT>elif proj == <NUM_LIT:3>:<EOL><INDENT>circuit.u3(theta, -np.pi / <NUM_LIT:3>, <NUM_LIT:0.0>, qreg)<EOL><DEDENT>


if not isinstance(meas_qubits, list):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>num_of_qubits = len(meas_qubits)<EOL>if prep_qubits is None:<EOL><INDENT>prep_qubits = meas_qubits<EOL><DEDENT>if not isinstance(prep_qubits, list):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>if len(prep_qubits) != len(meas_qubits):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>if isinstance(meas_basis, str):<EOL><INDENT>if meas_basis.lower() == '<STR_LIT>':<EOL><INDENT>meas_basis = PAULI_BASIS<EOL><DEDENT><DEDENT>if isinstance(prep_basis, str):<EOL><INDENT>if prep_basis.lower() == '<STR_LIT>':<EOL><INDENT>prep_basis = PAULI_BASIS<EOL><DEDENT>elif prep_basis.lower() == '<STR_LIT>':<EOL><INDENT>prep_basis = SIC_BASIS<EOL><DEDENT><DEDENT>circuits = []<EOL>circuit_labels = []<EOL>if prep_basis is None:<EOL><INDENT>for meas_product in product(meas_basis.keys(), repeat=num_of_qubits):<EOL><INDENT>meas = dict(zip(meas_qubits, meas_product))<EOL>circuits.append({'<STR_LIT>': meas})<EOL>label = '<STR_LIT>'<EOL>for qubit, op in meas.items():<EOL><INDENT>label += '<STR_LIT>' % (op[<NUM_LIT:0>], qubit)<EOL><DEDENT>circuit_labels.append(label)<EOL><DEDENT>return {'<STR_LIT>': meas_qubits,<EOL>'<STR_LIT>': circuits,<EOL>'<STR_LIT>': circuit_labels,<EOL>'<STR_LIT>': meas_basis}<EOL><DEDENT>num_of_s = len(list(prep_basis.values())[<NUM_LIT:0>])<EOL>plst_single = [(b, s)<EOL>for b in prep_basis.keys()<EOL>for s in range(num_of_s)]<EOL>for plst_product in product(plst_single, repeat=num_of_qubits):<EOL><INDENT>for meas_product in product(meas_basis.keys(),<EOL>repeat=num_of_qubits):<EOL><INDENT>prep = dict(zip(prep_qubits, plst_product))<EOL>meas = dict(zip(meas_qubits, meas_product))<EOL>circuits.append({'<STR_LIT>': prep, '<STR_LIT>': meas})<EOL>label = '<STR_LIT>'<EOL>for qubit, op in prep.items():<EOL><INDENT>label += '<STR_LIT>' % (op[<NUM_LIT:0>], op[<NUM_LIT:1>], qubit)<EOL><DEDENT>label += '<STR_LIT>'<EOL>for qubit, op in meas.items():<EOL><INDENT>label += '<STR_LIT>' % (op[<NUM_LIT:0>], qubit)<EOL><DEDENT>circuit_labels.append(label)<EOL><DEDENT><DEDENT>return {'<STR_LIT>': meas_qubits,<EOL>'<STR_LIT>': circuits,<EOL>'<STR_LIT>': circuit_labels,<EOL>'<STR_LIT>': prep_basis,<EOL>'<STR_LIT>': meas_basis}<EOL>

Generate a dictionary of tomography experiment configurations.

This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.

Quantum State Tomography:
    Be default it will return a set for performing Quantum State
    Tomography where individual qubits are measured in the Pauli basis.
    A custom measurement basis may also be used by defining a user
    `tomography_basis` and passing this in for the `meas_basis` argument.

Quantum Process Tomography:
    A quantum process tomography set is created by specifying a preparation
    basis along with a measurement basis. The preparation basis may be a
    user defined `tomography_basis`, or one of the two built in basis 'SIC'
    or 'Pauli'.
    - SIC: Is a minimal symmetric informationally complete preparation
           basis for 4 states for each qubit (4 ^ number of qubits total
           preparation states). These correspond to the |0> state and the 3
           other vertices of a tetrahedron on the Bloch-sphere.
    - Pauli: Is a tomographically overcomplete preparation basis of the six
             eigenstates of the 3 Pauli operators (6 ^ number of qubits
             total preparation states).

Args:
    meas_qubits (list): The qubits being measured.
    meas_basis (tomography_basis or str): The qubit measurement basis.
        The default value is 'Pauli'.
    prep_qubits (list or None): The qubits being prepared. If None then
        meas_qubits will be used for process tomography experiments.
    prep_basis (tomography_basis or None): The optional qubit preparation
        basis. If no basis is specified state tomography will be performed
        instead of process tomography. A built in basis may be specified by
        'SIC' or 'Pauli'  (SIC basis recommended for > 2 qubits).

Returns:
    dict: A dict of tomography configurations that can be parsed by
    `create_tomography_circuits` and `tomography_data` functions
    for implementing quantum tomography experiments. This output contains
    fields "qubits", "meas_basis", "circuits". It may also optionally
    contain a field "prep_basis" for process tomography experiments.
    ```
    {
        'qubits': qubits (list[ints]),
        'meas_basis': meas_basis (tomography_basis),
        'circuit_labels': (list[string]),
        'circuits': (list[dict])  # prep and meas configurations
        # optionally for process tomography experiments:
        'prep_basis': prep_basis (tomography_basis)
    }
    ```
Raises:
    QiskitError: if the Qubits argument is not a list.


return tomography_set(qubits, meas_basis=meas_basis)<EOL>

Generate a dictionary of state tomography experiment configurations.

This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.

Quantum State Tomography:
    Be default it will return a set for performing Quantum State
    Tomography where individual qubits are measured in the Pauli basis.
    A custom measurement basis may also be used by defining a user
    `tomography_basis` and passing this in for the `meas_basis` argument.

Quantum Process Tomography:
    A quantum process tomography set is created by specifying a preparation
    basis along with a measurement basis. The preparation basis may be a
    user defined `tomography_basis`, or one of the two built in basis 'SIC'
    or 'Pauli'.
    - SIC: Is a minimal symmetric informationally complete preparation
           basis for 4 states for each qubit (4 ^ number of qubits total
           preparation states). These correspond to the |0> state and the 3
           other vertices of a tetrahedron on the Bloch-sphere.
    - Pauli: Is a tomographically overcomplete preparation basis of the six
             eigenstates of the 3 Pauli operators (6 ^ number of qubits
             total preparation states).

Args:
    qubits (list): The qubits being measured.
    meas_basis (tomography_basis or str): The qubit measurement basis.
        The default value is 'Pauli'.

Returns:
    dict: A dict of tomography configurations that can be parsed by
    `create_tomography_circuits` and `tomography_data` functions
    for implementing quantum tomography experiments. This output contains
    fields "qubits", "meas_basis", "circuits".
    ```
    {
        'qubits': qubits (list[ints]),
        'meas_basis': meas_basis (tomography_basis),
        'circuit_labels': (list[string]),
        'circuits': (list[dict])  # prep and meas configurations
    }
    ```


def process_tomography_set(meas_qubits, meas_basis='<STR_LIT>',<EOL>prep_qubits=None, prep_basis='<STR_LIT>'):

return tomography_set(meas_qubits, meas_basis=meas_basis,<EOL>prep_qubits=prep_qubits, prep_basis=prep_basis)<EOL>

Generate a dictionary of process tomography experiment configurations.

 This returns a data structure that is used by other tomography functions
 to generate state and process tomography circuits, and extract tomography
 data from results after execution on a backend.

A quantum process tomography set is created by specifying a preparation
 basis along with a measurement basis. The preparation basis may be a
 user defined `tomography_basis`, or one of the two built in basis 'SIC'
 or 'Pauli'.
 - SIC: Is a minimal symmetric informationally complete preparation
        basis for 4 states for each qubit (4 ^ number of qubits total
        preparation states). These correspond to the |0> state and the 3
        other vertices of a tetrahedron on the Bloch-sphere.
 - Pauli: Is a tomographically overcomplete preparation basis of the six
          eigenstates of the 3 Pauli operators (6 ^ number of qubits
          total preparation states).

 Args:
     meas_qubits (list): The qubits being measured.
     meas_basis (tomography_basis or str): The qubit measurement basis.
         The default value is 'Pauli'.
     prep_qubits (list or None): The qubits being prepared. If None then
         meas_qubits will be used for process tomography experiments.
     prep_basis (tomography_basis or str): The qubit preparation basis.
         The default value is 'SIC'.

 Returns:
     dict: A dict of tomography configurations that can be parsed by
     `create_tomography_circuits` and `tomography_data` functions
     for implementing quantum tomography experiments. This output contains
     fields "qubits", "meas_basis", "prep_basus", circuits".
     ```
     {
         'qubits': qubits (list[ints]),
         'meas_basis': meas_basis (tomography_basis),
         'prep_basis': prep_basis (tomography_basis),
         'circuit_labels': (list[string]),
         'circuits': (list[dict])  # prep and meas configurations
     }
     ```


return [name + l for l in tomo_set['<STR_LIT>']]<EOL>

Return a list of tomography circuit names.

The returned list is the same as the one returned by
`create_tomography_circuits` and can be used by a QuantumProgram
to execute tomography circuits and extract measurement results.

Args:
    tomo_set (tomography_set): a tomography set generated by
        `tomography_set`.
    name (str): the name of the base QuantumCircuit used by the
    tomography experiment.

Returns:
    list: A list of circuit names.


def create_tomography_circuits(circuit, qreg, creg, tomoset):

if not isinstance(circuit, QuantumCircuit):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>dics = tomoset['<STR_LIT>']<EOL>labels = tomography_circuit_names(tomoset, circuit.name)<EOL>tomography_circuits = []<EOL>for label, conf in zip(labels, dics):<EOL><INDENT>tmp = circuit<EOL>if '<STR_LIT>' in conf:<EOL><INDENT>prep = QuantumCircuit(qreg, creg, name='<STR_LIT>')<EOL>for qubit, op in conf['<STR_LIT>'].items():<EOL><INDENT>tomoset['<STR_LIT>'].prep_gate(prep, qreg[qubit], op)<EOL>prep.barrier(qreg[qubit])<EOL><DEDENT>tmp = prep + tmp<EOL><DEDENT>meas = QuantumCircuit(qreg, creg, name='<STR_LIT>')<EOL>for qubit, op in conf['<STR_LIT>'].items():<EOL><INDENT>meas.barrier(qreg[qubit])<EOL>tomoset['<STR_LIT>'].meas_gate(meas, qreg[qubit], op)<EOL>meas.measure(qreg[qubit], creg[qubit])<EOL><DEDENT>tmp = tmp + meas<EOL>tmp.name = label<EOL>tomography_circuits.append(tmp)<EOL><DEDENT>logger.info('<STR_LIT>', circuit.name)<EOL>return tomography_circuits<EOL>

Add tomography measurement circuits to a QuantumProgram.

The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.

For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.

Args:
    circuit (QuantumCircuit): The circuit to be appended with tomography
                              state preparation and/or measurements.
    qreg (QuantumRegister): the quantum register containing qubits to be
                            measured.
    creg (ClassicalRegister): the classical register containing bits to
                              store measurement outcomes.
    tomoset (tomography_set): the dict of tomography configurations.

Returns:
    list: A list of quantum tomography circuits for the input circuit.

Raises:
    QiskitError: if circuit is not a valid QuantumCircuit

Example:
    For a tomography set specifying state tomography of qubit-0 prepared
    by a circuit 'circ' this would return:
    ```
    ['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
    ```
    For process tomography of the same circuit with preparation in the
    SIC-POVM basis it would return:
    ```
    [
        'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
        'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
        'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
        'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
        'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
        'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
    ]
    ```


def tomography_data(results, name, tomoset):

labels = tomography_circuit_names(tomoset, name)<EOL>circuits = tomoset['<STR_LIT>']<EOL>data = []<EOL>prep = None<EOL>for j, _ in enumerate(labels):<EOL><INDENT>counts = marginal_counts(results.get_counts(labels[j]),<EOL>tomoset['<STR_LIT>'])<EOL>shots = sum(counts.values())<EOL>meas = circuits[j]['<STR_LIT>']<EOL>prep = circuits[j].get('<STR_LIT>', None)<EOL>meas_qubits = sorted(meas.keys())<EOL>if prep:<EOL><INDENT>prep_qubits = sorted(prep.keys())<EOL><DEDENT>circuit = {}<EOL>for c in counts.keys():<EOL><INDENT>circuit[c] = {}<EOL>circuit[c]['<STR_LIT>'] = [(meas[meas_qubits[k]], int(c[-<NUM_LIT:1> - k]))<EOL>for k in range(len(meas_qubits))]<EOL>if prep:<EOL><INDENT>circuit[c]['<STR_LIT>'] = [prep[prep_qubits[k]]<EOL>for k in range(len(prep_qubits))]<EOL><DEDENT><DEDENT>data.append({'<STR_LIT>': counts, '<STR_LIT>': shots, '<STR_LIT>': circuit})<EOL><DEDENT>ret = {'<STR_LIT:data>': data, '<STR_LIT>': tomoset['<STR_LIT>']}<EOL>if prep:<EOL><INDENT>ret['<STR_LIT>'] = tomoset['<STR_LIT>']<EOL><DEDENT>return ret<EOL>

Return a results dict for a state or process tomography experiment.

Args:
    results (Result): Results from execution of a process tomography
        circuits on a backend.
    name (string): The name of the circuit being reconstructed.
    tomoset (tomography_set): the dict of tomography configurations.

Returns:
    list: A list of dicts for the outcome of each process tomography
    measurement circuit.


<EOL>num_of_qubits = len(list(counts.keys())[<NUM_LIT:0>])<EOL>qs = sorted(meas_qubits, reverse=True)<EOL>meas_keys = count_keys(len(qs))<EOL>rgx = [<EOL>reduce(lambda x, y: (key[qs.index(y)] if y in qs else '<STR_LIT>') + x,<EOL>range(num_of_qubits), '<STR_LIT>') for key in meas_keys<EOL>]<EOL>meas_counts = []<EOL>for m in rgx:<EOL><INDENT>c = <NUM_LIT:0><EOL>for key, val in counts.items():<EOL><INDENT>if match(m, key):<EOL><INDENT>c += val<EOL><DEDENT><DEDENT>meas_counts.append(c)<EOL><DEDENT>return dict(zip(meas_keys, meas_counts))<EOL>

Compute the marginal counts for a subset of measured qubits.

Args:
    counts (dict): the counts returned from a backend ({str: int}).
    meas_qubits (list[int]): the qubits to return the marginal
                             counts distribution for.

Returns:
    dict: A counts dict for the meas_qubits.abs
    Example: if `counts = {'00': 10, '01': 5}`
        `marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.
        `marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.


return [bin(j)[<NUM_LIT:2>:].zfill(n) for j in range(<NUM_LIT:2>**n)]<EOL>

Generate outcome bitstrings for n-qubits.

    Args:
        n (int): the number of qubits.

    Returns:
        list: A list of bitstrings ordered as follows:
        Example: n=2 returns ['00', '01', '10', '11'].


def fit_tomography_data(tomo_data, method='<STR_LIT>', options=None):

if isinstance(method, str) and method.lower() in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>trace = __get_option('<STR_LIT>', options)<EOL>beta = __get_option('<STR_LIT>', options)<EOL>rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)<EOL>if method == '<STR_LIT>':<EOL><INDENT>epsilon = __get_option('<STR_LIT>', options)<EOL>rho = __wizard(rho, epsilon=epsilon)<EOL><DEDENT>return rho<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>' % method)<EOL><DEDENT>

Reconstruct a density matrix or process-matrix from tomography data.

If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.

Args:
    tomo_data (dict): process tomography measurement data.
    method (str): the fitting method to use.
        Available methods:
            - 'wizard' (default)
            - 'leastsq'
    options (dict or None): additional options for fitting method.

Returns:
    numpy.array: The fitted operator.

Available methods:
    - 'wizard' (Default): The returned operator will be constrained to be
                          positive-semidefinite.
        Options:
        - 'trace': the trace of the returned operator.
                   The default value is 1.
        - 'beta': hedging parameter for computing frequencies from
                  zero-count data. The default value is 0.50922.
        - 'epsilon: threshold for truncating small eigenvalues to zero.
                    The default value is 0
    - 'leastsq': Fitting without positive-semidefinite constraint.
        Options:
        - 'trace': Same as for 'wizard' method.
        - 'beta': Same as for 'wizard' method.
Raises:
    Exception: if the `method` parameter is not valid.


if options is not None:<EOL><INDENT>if opt in options:<EOL><INDENT>return options[opt]<EOL><DEDENT><DEDENT>return None<EOL>

Return an optional value or None if not found.


def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):

if trace is None:<EOL><INDENT>trace = <NUM_LIT:1.>  <EOL><DEDENT>data = tomo_data['<STR_LIT:data>']<EOL>keys = data[<NUM_LIT:0>]['<STR_LIT>'].keys()<EOL>counts = []<EOL>shots = []<EOL>ops = []<EOL>for dat in data:<EOL><INDENT>for key in keys:<EOL><INDENT>counts.append(dat['<STR_LIT>'][key])<EOL>shots.append(dat['<STR_LIT>'])<EOL>projectors = dat['<STR_LIT>'][key]<EOL>op = __projector(projectors['<STR_LIT>'], tomo_data['<STR_LIT>'])<EOL>if '<STR_LIT>' in projectors:<EOL><INDENT>op_prep = __projector(projectors['<STR_LIT>'],<EOL>tomo_data['<STR_LIT>'])<EOL>op = np.kron(op_prep.conj(), op)<EOL><DEDENT>ops.append(op)<EOL><DEDENT><DEDENT>counts = np.array(counts)<EOL>shots = np.array(shots)<EOL>freqs = counts / shots<EOL>if weights is None:<EOL><INDENT>if beta is None:<EOL><INDENT>beta = <NUM_LIT><EOL><DEDENT>K = len(keys)<EOL>freqs_hedged = (counts + beta) / (shots + K * beta)<EOL>weights = np.sqrt(shots / (freqs_hedged * (<NUM_LIT:1> - freqs_hedged)))<EOL><DEDENT>return __tomo_linear_inv(freqs, ops, weights, trace=trace)<EOL>

Reconstruct a state from unconstrained least-squares fitting.

Args:
    tomo_data (list[dict]): state or process tomography data.
    weights (list or array or None): weights to use for least squares
        fitting. The default is standard deviation from a binomial
        distribution.
    trace (float or None): trace of returned operator. The default is 1.
    beta (float or None): hedge parameter (>=0) for computing frequencies
        from zero-count data. The default value is 0.50922.

Returns:
    numpy.array: A numpy array of the reconstructed operator.


ret = <NUM_LIT:1><EOL>for op in op_list:<EOL><INDENT>label, eigenstate = op<EOL>ret = np.kron(basis[label][eigenstate], ret)<EOL><DEDENT>return ret<EOL>


def __tomo_linear_inv(freqs, ops, weights=None, trace=None):

<EOL>if weights is not None:<EOL><INDENT>W = np.array(weights)<EOL>if W.ndim == <NUM_LIT:1>:<EOL><INDENT>W = np.diag(W)<EOL><DEDENT><DEDENT>S = np.array([vectorize(m).conj()<EOL>for m in ops]).reshape(len(ops), ops[<NUM_LIT:0>].size)<EOL>if weights is not None:<EOL><INDENT>S = np.dot(W, S)  <EOL><DEDENT>v = np.array(freqs)  <EOL>if weights is not None:<EOL><INDENT>v = np.dot(W, freqs)  <EOL><DEDENT>Sdg = S.T.conj()  <EOL>inv = np.linalg.pinv(np.dot(Sdg, S))  <EOL>ret = devectorize(np.dot(inv, np.dot(Sdg, v)))<EOL>if trace is not None:<EOL><INDENT>ret = trace * ret / np.trace(ret)<EOL><DEDENT>return ret<EOL>

Reconstruct a matrix through linear inversion.

Args:
    freqs (list[float]): list of observed frequences.
    ops (list[np.array]): list of corresponding projectors.
    weights (list[float] or array_like):
        weights to be used for weighted fitting.
    trace (float or None): trace of returned operator.

Returns:
    numpy.array: A numpy array of the reconstructed operator.


if epsilon is None:<EOL><INDENT>epsilon = <NUM_LIT:0.>  <EOL><DEDENT>dim = len(rho)<EOL>rho_wizard = np.zeros([dim, dim])<EOL>v, w = np.linalg.eigh(rho)  <EOL>for j in range(dim):<EOL><INDENT>if v[j] < epsilon:<EOL><INDENT>tmp = v[j]<EOL>v[j] = <NUM_LIT:0.><EOL>x = <NUM_LIT:0.><EOL>for k in range(j + <NUM_LIT:1>, dim):<EOL><INDENT>x += tmp / (dim - (j + <NUM_LIT:1>))<EOL>v[k] = v[k] + tmp / (dim - (j + <NUM_LIT:1>))<EOL><DEDENT><DEDENT><DEDENT>for j in range(dim):<EOL><INDENT>rho_wizard = rho_wizard + v[j] * outer(w[:, j])<EOL><DEDENT>return rho_wizard<EOL>

Returns the nearest positive semidefinite operator to an operator.

This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.

Args:
    rho (array_like): the input operator.
    epsilon(float or None): threshold (>=0) for truncating small
        eigenvalues values to zero.

Returns:
    numpy.array: A positive semidefinite numpy array.


def build_wigner_circuits(circuit, phis, thetas, qubits,<EOL>qreg, creg):

if not isinstance(circuit, QuantumCircuit):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>tomography_circuits = []<EOL>points = len(phis[<NUM_LIT:0>])<EOL>for point in range(points):<EOL><INDENT>label = '<STR_LIT>'<EOL>label += str(point)<EOL>tmp_circ = QuantumCircuit(qreg, creg, name=label)<EOL>for qubit, _ in enumerate(qubits):<EOL><INDENT>tmp_circ.u3(thetas[qubit][point], <NUM_LIT:0>,<EOL>phis[qubit][point], qreg[qubits[qubit]])<EOL>tmp_circ.measure(qreg[qubits[qubit]], creg[qubits[qubit]])<EOL><DEDENT>tmp_circ = circuit + tmp_circ<EOL>tmp_circ.name = circuit.name + label<EOL>tomography_circuits.append(tmp_circ)<EOL><DEDENT>logger.info('<STR_LIT>', circuit.name)<EOL>return tomography_circuits<EOL>

Create the circuits to rotate to points in phase space
    Args:
        circuit (QuantumCircuit): The circuit to be appended with tomography
                                  state preparation and/or measurements.
        phis (np.matrix[[complex]]): phis
        thetas (np.matrix[[complex]]): thetas
        qubits (list[int]): a list of the qubit indexes of qreg to be measured.
        qreg (QuantumRegister): the quantum register containing qubits to be
                                measured.
        creg (ClassicalRegister): the classical register containing bits to
                                    store measurement outcomes.

    Returns:
        list: A list of names of the added wigner function circuits.

    Raises:
        QiskitError: if circuit is not a valid QuantumCircuit.


def wigner_data(q_result, meas_qubits, labels, shots=None):

num = len(meas_qubits)<EOL>dim = <NUM_LIT:2>**num<EOL>p = [<NUM_LIT:0.5> + <NUM_LIT:0.5> * np.sqrt(<NUM_LIT:3>), <NUM_LIT:0.5> - <NUM_LIT:0.5> * np.sqrt(<NUM_LIT:3>)]<EOL>parity = <NUM_LIT:1><EOL>for i in range(num):<EOL><INDENT>parity = np.kron(parity, p)<EOL><DEDENT>w = [<NUM_LIT:0>] * len(labels)<EOL>wpt = <NUM_LIT:0><EOL>counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)<EOL>for circ in labels]<EOL>for entry in counts:<EOL><INDENT>x = [<NUM_LIT:0>] * dim<EOL>for i in range(dim):<EOL><INDENT>if bin(i)[<NUM_LIT:2>:].zfill(num) in entry:<EOL><INDENT>x[i] = float(entry[bin(i)[<NUM_LIT:2>:].zfill(num)])<EOL><DEDENT><DEDENT>if shots is None:<EOL><INDENT>shots = np.sum(x)<EOL><DEDENT>for i in range(dim):<EOL><INDENT>w[wpt] = w[wpt] + (x[i] / shots) * parity[i]<EOL><DEDENT>wpt += <NUM_LIT:1><EOL><DEDENT>return w<EOL>

Get the value of the Wigner function from measurement results.

    Args:
        q_result (Result): Results from execution of a state tomography
                            circuits on a backend.
        meas_qubits (list[int]): a list of the qubit indexes measured.
        labels (list[str]): a list of names of the circuits
        shots (int): number of shots

    Returns:
        list: The values of the Wigner function at measured points in
            phase space


if self.prep_fun is None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.prep_fun(circuit, qreg, op)<EOL><DEDENT>

Add state preparation gates to a circuit.

Args:
    circuit (QuantumCircuit): circuit to add a preparation to.
    qreg (tuple(QuantumRegister,int)): quantum register to apply
    preparation to.
    op (tuple(str, int)): the basis label and index for the
    preparation op.


if self.meas_fun is None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.meas_fun(circuit, qreg, op)<EOL><DEDENT>

Add measurement gates to a circuit.

Args:
    circuit (QuantumCircuit): circuit to add measurement to.
    qreg (tuple(QuantumRegister,int)): quantum register being measured.
    op (str): the basis label for the measurement.


<EOL>return a * np.exp(-x / tau) + c<EOL>

Function used to fit the exponential decay.


<EOL>return a * np.exp(-x / tau) * np.cos(<NUM_LIT:2> * np.pi * f * x + phi) + c<EOL>


<EOL>return a * alpha ** x + b<EOL>


def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str,<EOL>qubit_label):

if not HAS_MATPLOTLIB:<EOL><INDENT>raise ImportError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>plt.errorbar(xdata, ydata, std_error, marker='<STR_LIT:.>',<EOL>markersize=<NUM_LIT:9>, c='<STR_LIT:b>', linestyle='<STR_LIT>')<EOL>plt.plot(xdata, fit_function(xdata, *fit), c='<STR_LIT:r>', linestyle='<STR_LIT>',<EOL>label=(exp_str + '<STR_LIT>' % (str(round(fit[<NUM_LIT:1>])), xunit)))<EOL>plt.xticks(fontsize=<NUM_LIT>, rotation=<NUM_LIT>)<EOL>plt.yticks(fontsize=<NUM_LIT>)<EOL>plt.xlabel('<STR_LIT>' % (xunit), fontsize=<NUM_LIT:16>)<EOL>plt.ylabel('<STR_LIT>', fontsize=<NUM_LIT:16>)<EOL>plt.title(exp_str + '<STR_LIT>' % (str(qubit_label)), fontsize=<NUM_LIT>)<EOL>plt.legend(fontsize=<NUM_LIT:12>)<EOL>plt.grid(True)<EOL>plt.show()<EOL>

Plot coherence data.

    Args:
        xdata
        ydata
        std_error
        fit
        fit_function
        xunit
        exp_str
        qubit_label
    Raises:
        ImportError: If matplotlib is not installed.


rb_data = []<EOL>rb_data.append(np.mean(raw_rb, <NUM_LIT:0>))<EOL>rb_data.append(np.std(raw_rb, <NUM_LIT:0>))<EOL>return rb_data<EOL>

Take the raw rb data and convert it into averages and std dev

    Args:
        raw_rb (numpy.array): m x n x l list where m is the number of seeds, n
            is the number of Clifford sequences and l is the number of qubits

    Return:
        numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 is
            the std dev overseeds


for patterns in rb_pattern:<EOL><INDENT>for qubit in patterns:<EOL><INDENT>fitalpha = fit['<STR_LIT>' % qubit]['<STR_LIT>'][<NUM_LIT:1>]<EOL>fitalphaerr = fit['<STR_LIT>' % qubit]['<STR_LIT>'][<NUM_LIT:1>]<EOL>nrb = <NUM_LIT:2> ** len(patterns)<EOL>fit['<STR_LIT>' % qubit]['<STR_LIT>'] = {}<EOL>fit['<STR_LIT>' % qubit]['<STR_LIT>']['<STR_LIT>'] = [(nrb - <NUM_LIT:1>) / nrb * (<NUM_LIT:1> - fitalpha),<EOL>fitalphaerr / fitalpha]<EOL>fit['<STR_LIT>' % qubit]['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:1>] *= fit['<STR_LIT>' % qubit]['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT><DEDENT>return fit<EOL>

Take the rb fit data and convert it into EPC (error per Clifford)

    Args:
        fit (dict): dictionary of the fit quantities (A, alpha, B) with the
            keys 'qn' where n is  the qubit and subkeys 'fit', e.g.
            {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}}
        rb_pattern (list): (see randomized benchmarking functions). Pattern
            which specifies which qubits performing RB with which qubits. E.g.
            [[1],[0,2]] is Q1  doing 1Q RB simultaneously with Q0/Q2 doing
            2Q RB

    Return:
        dict: updates the passed in fit dictionary with the epc


def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None,<EOL>show_plt=True):

<EOL>if not HAS_MATPLOTLIB:<EOL><INDENT>raise ImportError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if ax is None:<EOL><INDENT>plt.figure()<EOL>ax = plt.gca()<EOL><DEDENT>for ydata in ydatas:<EOL><INDENT>ax.plot(xdata, ydata, color='<STR_LIT>', linestyle='<STR_LIT:none>', marker='<STR_LIT:x>')<EOL><DEDENT>ax.errorbar(xdata, yavg, yerr=yerr, color='<STR_LIT:r>', linestyle='<STR_LIT>', linewidth=<NUM_LIT:3>)<EOL>ax.plot(xdata, survival_prob(xdata, *fit), color='<STR_LIT>', linestyle='<STR_LIT:->', linewidth=<NUM_LIT:2>)<EOL>ax.tick_params(labelsize=<NUM_LIT>)<EOL>ax.set_xlabel('<STR_LIT>', fontsize=<NUM_LIT:16>)<EOL>ax.set_ylabel('<STR_LIT>', fontsize=<NUM_LIT:16>)<EOL>ax.grid(True)<EOL>if show_plt:<EOL><INDENT>plt.show()<EOL><DEDENT>

Plot randomized benchmarking data.

    Args:
        xdata (list): list of subsequence lengths
        ydatas (list): list of lists of survival probabilities for each
            sequence
        yavg (list): mean of the survival probabilities at each sequence
            length
        yerr (list): error of the survival
        fit (list): fit parameters
        survival_prob (callable): function that computes survival probability
        ax (Axes or None): plot axis (if passed in)
        show_plt (bool): display the plot.

    Raises:
        ImportError: If matplotlib is not installed.


def _html_checker(job_var, interval, status, header,<EOL>_interval_set=False):

job_status = job_var.status()<EOL>job_status_name = job_status.name<EOL>job_status_msg = job_status.value<EOL>status.value = header % (job_status_msg)<EOL>while job_status_name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>time.sleep(interval)<EOL>job_status = job_var.status()<EOL>job_status_name = job_status.name<EOL>job_status_msg = job_status.value<EOL>if job_status_name == '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>if job_status_name == '<STR_LIT>':<EOL><INDENT>job_status_msg += '<STR_LIT>' % job_var.queue_position()<EOL>if not _interval_set:<EOL><INDENT>interval = max(job_var.queue_position(), <NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not _interval_set:<EOL><INDENT>interval = <NUM_LIT:2><EOL><DEDENT><DEDENT>status.value = header % (job_status_msg)<EOL><DEDENT><DEDENT>status.value = header % (job_status_msg)<EOL>

Internal function that updates the status
    of a HTML job monitor.

    Args:
        job_var (BaseJob): The job to keep track of.
        interval (int): The status check interval
        status (widget): HTML ipywidget for output ot screen
        header (str): String representing HTML code for status.
        _interval_set (bool): Was interval set by user?


args = magic_arguments.parse_argstring(self.qiskit_job_status, line)<EOL>if args.interval is None:<EOL><INDENT>args.interval = <NUM_LIT:2><EOL>_interval_set = False<EOL><DEDENT>else:<EOL><INDENT>_interval_set = True<EOL><DEDENT>cell_lines = cell.split('<STR_LIT:\n>')<EOL>line_vars = []<EOL>for cline in cell_lines:<EOL><INDENT>if '<STR_LIT:=>' in cline and '<STR_LIT>' not in cline:<EOL><INDENT>line_vars.append(cline.replace('<STR_LIT:U+0020>', '<STR_LIT>').split('<STR_LIT:=>')[<NUM_LIT:0>])<EOL><DEDENT>elif '<STR_LIT>' in cline:<EOL><INDENT>line_vars.append(cline.replace('<STR_LIT:U+0020>', '<STR_LIT>').split('<STR_LIT:(>')[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>self.shell.ex(cell)<EOL>jobs = []<EOL>for var in line_vars:<EOL><INDENT>iter_var = False<EOL>if '<STR_LIT:#>' not in var:<EOL><INDENT>if '<STR_LIT:[>' in var:<EOL><INDENT>var = var.split('<STR_LIT:[>')[<NUM_LIT:0>]<EOL>iter_var = True<EOL><DEDENT>elif '<STR_LIT>' in var:<EOL><INDENT>var = var.split('<STR_LIT>')[<NUM_LIT:0>]<EOL>iter_var = True<EOL><DEDENT>if iter_var:<EOL><INDENT>for item in self.shell.user_ns[var]:<EOL><INDENT>if isinstance(item, qiskit.providers.basejob.BaseJob):<EOL><INDENT>jobs.append(item)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(self.shell.user_ns[var],<EOL>qiskit.providers.basejob.BaseJob):<EOL><INDENT>jobs.append(self.shell.user_ns[var])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not any(jobs):<EOL><INDENT>raise Exception(<EOL>"<STR_LIT>")<EOL><DEDENT>multi_job = False<EOL>if len(jobs) > <NUM_LIT:1>:<EOL><INDENT>multi_job = True<EOL><DEDENT>job_checkers = []<EOL>for idx, job_var in enumerate(jobs):<EOL><INDENT>style = "<STR_LIT>"<EOL>if multi_job:<EOL><INDENT>idx_str = '<STR_LIT>' % idx<EOL><DEDENT>else:<EOL><INDENT>idx_str = '<STR_LIT>'<EOL><DEDENT>header = "<STR_LIT>".format(id=idx_str,<EOL>style=style)<EOL>status = widgets.HTML(<EOL>value=header % job_var.status().value)<EOL>thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,<EOL>status, header,<EOL>_interval_set))<EOL>thread.start()<EOL>job_checkers.append(status)<EOL><DEDENT>box = widgets.VBox(job_checkers)<EOL>display(box)<EOL>

A Jupyter magic function to check the status of a Qiskit job instance.


args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)<EOL>if args.type == '<STR_LIT:html>':<EOL><INDENT>HTMLProgressBar()<EOL><DEDENT>elif args.type == '<STR_LIT:text>':<EOL><INDENT>TextProgressBar()<EOL><DEDENT>else:<EOL><INDENT>raise qiskit.QiskitError('<STR_LIT>')<EOL><DEDENT>self.shell.ex(cell)<EOL>

A Jupyter magic function to generate progressbar.


status = backend.status().to_dict()<EOL>config = backend.configuration().to_dict()<EOL>config_dict = {**status, **config}<EOL>upper_list = ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>lower_list = list(set(config_dict.keys()).difference(upper_list))<EOL>lower_list.remove('<STR_LIT>')<EOL>upper_str = "<STR_LIT>"<EOL>upper_str += """<STR_LIT>"""<EOL>footer = "<STR_LIT>"<EOL>upper_str += "<STR_LIT>"<EOL>for key in upper_list:<EOL><INDENT>upper_str += "<STR_LIT>" % (<EOL>key, config_dict[key])<EOL><DEDENT>upper_str += footer<EOL>upper_table = widgets.HTML(<EOL>value=upper_str, layout=widgets.Layout(width='<STR_LIT>', grid_area='<STR_LIT:left>'))<EOL>image_widget = widgets.Output(<EOL>layout=widgets.Layout(display='<STR_LIT>', grid_area='<STR_LIT:right>',<EOL>padding='<STR_LIT>',<EOL>width='<STR_LIT>', max_height='<STR_LIT>',<EOL>align_items='<STR_LIT>'))<EOL>if not config['<STR_LIT>']:<EOL><INDENT>with image_widget:<EOL><INDENT>gate_map = plot_gate_map(backend)<EOL>display(gate_map)<EOL><DEDENT>plt.close(gate_map)<EOL><DEDENT>lower_str = "<STR_LIT>"<EOL>lower_str += """<STR_LIT>"""<EOL>lower_str += "<STR_LIT>"<EOL>for key in lower_list:<EOL><INDENT>if key != '<STR_LIT:name>':<EOL><INDENT>lower_str += "<STR_LIT>" % (<EOL>key, config_dict[key])<EOL><DEDENT><DEDENT>lower_str += footer<EOL>lower_table = widgets.HTML(value=lower_str,<EOL>layout=widgets.Layout(<EOL>width='<STR_LIT>',<EOL>grid_area='<STR_LIT>'))<EOL>grid = widgets.GridBox(children=[upper_table, image_widget, lower_table],<EOL>layout=widgets.Layout(<EOL>grid_template_rows='<STR_LIT>',<EOL>grid_template_columns='<STR_LIT>',<EOL>grid_template_areas='''<STR_LIT>''',<EOL>grid_gap='<STR_LIT>'))<EOL>return grid<EOL>

The backend configuration widget.

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        grid: A GridBox widget.


props = backend.properties().to_dict()<EOL>header_html = "<STR_LIT>"<EOL>header_html = header_html.format(key='<STR_LIT>',<EOL>value=props['<STR_LIT>'])<EOL>update_date_widget = widgets.HTML(value=header_html)<EOL>qubit_html = "<STR_LIT>"<EOL>qubit_html += """<STR_LIT>"""<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_footer = "<STR_LIT>"<EOL>for qub in range(len(props['<STR_LIT>'])):<EOL><INDENT>name = '<STR_LIT>' % qub<EOL>qubit_data = props['<STR_LIT>'][qub]<EOL>gate_data = props['<STR_LIT>'][<NUM_LIT:3>*qub:<NUM_LIT:3>*qub+<NUM_LIT:3>]<EOL>t1_info = qubit_data[<NUM_LIT:0>]<EOL>t2_info = qubit_data[<NUM_LIT:1>]<EOL>freq_info = qubit_data[<NUM_LIT:2>]<EOL>readout_info = qubit_data[<NUM_LIT:3>]<EOL>freq = str(round(freq_info['<STR_LIT:value>'], <NUM_LIT:5>))+'<STR_LIT:U+0020>'+freq_info['<STR_LIT>']<EOL>T1 = str(round(t1_info['<STR_LIT:value>'],  <EOL><NUM_LIT:5>))+'<STR_LIT:U+0020>' + t1_info['<STR_LIT>']<EOL>T2 = str(round(t2_info['<STR_LIT:value>'],  <EOL><NUM_LIT:5>))+'<STR_LIT:U+0020>' + t2_info['<STR_LIT>']<EOL>U1 = str(round(gate_data[<NUM_LIT:0>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>U2 = str(round(gate_data[<NUM_LIT:1>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>U3 = str(round(gate_data[<NUM_LIT:2>]['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>))<EOL>readout_error = round(readout_info['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html += "<STR_LIT>"<EOL>qubit_html = qubit_html % (name, freq, T1, T2, U1, U2, U3, readout_error)<EOL><DEDENT>qubit_html += qubit_footer<EOL>qubit_widget = widgets.HTML(value=qubit_html)<EOL>out = widgets.VBox([update_date_widget,<EOL>qubit_widget])<EOL>return out<EOL>

The qubits properties widget

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        VBox: A VBox widget.


config = backend.configuration().to_dict()<EOL>props = backend.properties().to_dict()<EOL>multi_qubit_gates = props['<STR_LIT>'][<NUM_LIT:3>*config['<STR_LIT>']:]<EOL>header_html = "<STR_LIT>"<EOL>header_html = header_html.format(key='<STR_LIT>',<EOL>value=props['<STR_LIT>'])<EOL>update_date_widget = widgets.HTML(value=header_html,<EOL>layout=widgets.Layout(grid_area='<STR_LIT>'))<EOL>gate_html = "<STR_LIT>"<EOL>gate_html += """<STR_LIT>"""<EOL>gate_html += "<STR_LIT>"<EOL>gate_footer = "<STR_LIT>"<EOL>left_num = math.ceil(len(multi_qubit_gates)/<NUM_LIT:3>)<EOL>mid_num = math.ceil((len(multi_qubit_gates)-left_num)/<NUM_LIT:2>)<EOL>left_table = gate_html<EOL>for qub in range(left_num):<EOL><INDENT>gate = multi_qubit_gates[qub]<EOL>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>left_table += "<STR_LIT>"<EOL>left_table += "<STR_LIT>"<EOL>left_table = left_table % (name, ttype, error)<EOL><DEDENT>left_table += gate_footer<EOL>middle_table = gate_html<EOL>for qub in range(left_num, left_num+mid_num):<EOL><INDENT>gate = multi_qubit_gates[qub]<EOL>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>middle_table += "<STR_LIT>"<EOL>middle_table += "<STR_LIT>"<EOL>middle_table = middle_table % (name, ttype, error)<EOL><DEDENT>middle_table += gate_footer<EOL>right_table = gate_html<EOL>for qub in range(left_num+mid_num, len(multi_qubit_gates)):<EOL><INDENT>gate = multi_qubit_gates[qub]<EOL>name = gate['<STR_LIT:name>']<EOL>ttype = gate['<STR_LIT>']<EOL>error = round(gate['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'], <NUM_LIT:5>)<EOL>right_table += "<STR_LIT>"<EOL>right_table += "<STR_LIT>"<EOL>right_table = right_table % (name, ttype, error)<EOL><DEDENT>right_table += gate_footer<EOL>left_table_widget = widgets.HTML(value=left_table,<EOL>layout=widgets.Layout(grid_area='<STR_LIT:left>'))<EOL>middle_table_widget = widgets.HTML(value=middle_table,<EOL>layout=widgets.Layout(grid_area='<STR_LIT>'))<EOL>right_table_widget = widgets.HTML(value=right_table,<EOL>layout=widgets.Layout(grid_area='<STR_LIT:right>'))<EOL>grid = widgets.GridBox(children=[update_date_widget,<EOL>left_table_widget,<EOL>middle_table_widget,<EOL>right_table_widget],<EOL>layout=widgets.Layout(<EOL>grid_template_rows='<STR_LIT>',<EOL>grid_template_columns='<STR_LIT>',<EOL>grid_template_areas='''<STR_LIT>''',<EOL>grid_gap='<STR_LIT>'))<EOL>return grid<EOL>

The multiple qubit gate error widget.

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        VBox: A VBox widget.


props = backend.properties().to_dict()<EOL>config = backend.configuration().to_dict()<EOL>single_gate_errors = [q['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>']<EOL>for q in props['<STR_LIT>'][<NUM_LIT:2>:<NUM_LIT:3>*config['<STR_LIT>']:<NUM_LIT:3>]]<EOL>single_norm = matplotlib.colors.Normalize(<EOL>vmin=min(single_gate_errors), vmax=max(single_gate_errors))<EOL>q_colors = [cm.viridis(single_norm(err)) for err in single_gate_errors]<EOL>cmap = config['<STR_LIT>']<EOL>cx_errors = []<EOL>for line in cmap:<EOL><INDENT>for item in props['<STR_LIT>'][<NUM_LIT:3>*config['<STR_LIT>']:]:<EOL><INDENT>if item['<STR_LIT>'] == line:<EOL><INDENT>cx_errors.append(item['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:value>'])<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>cx_norm = matplotlib.colors.Normalize(<EOL>vmin=min(cx_errors), vmax=max(cx_errors))<EOL>line_colors = [cm.viridis(cx_norm(err)) for err in cx_errors]<EOL>single_widget = widgets.Output(layout=widgets.Layout(display='<STR_LIT>', grid_area='<STR_LIT:left>',<EOL>align_items='<STR_LIT>'))<EOL>cmap_widget = widgets.Output(layout=widgets.Layout(display='<STR_LIT>', grid_area='<STR_LIT>',<EOL>width='<STR_LIT>', height='<STR_LIT>',<EOL>align_items='<STR_LIT>'))<EOL>cx_widget = widgets.Output(layout=widgets.Layout(display='<STR_LIT>', grid_area='<STR_LIT:right>',<EOL>align_items='<STR_LIT>'))<EOL>tick_locator = mpl.ticker.MaxNLocator(nbins=<NUM_LIT:5>)<EOL>with cmap_widget:<EOL><INDENT>noise_map = plot_gate_map(backend, qubit_color=q_colors,<EOL>line_color=line_colors,<EOL>qubit_size=<NUM_LIT>,<EOL>plot_directed=True)<EOL>width, height = noise_map.get_size_inches()<EOL>noise_map.set_size_inches(<NUM_LIT>*width, <NUM_LIT>*height)<EOL>display(noise_map)<EOL>plt.close(noise_map)<EOL><DEDENT>with single_widget:<EOL><INDENT>cbl_fig = plt.figure(figsize=(<NUM_LIT:3>, <NUM_LIT:1>))<EOL>ax1 = cbl_fig.add_axes([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>single_cb = mpl.colorbar.ColorbarBase(ax1, cmap=cm.viridis,<EOL>norm=single_norm,<EOL>orientation='<STR_LIT>')<EOL>single_cb.locator = tick_locator<EOL>single_cb.update_ticks()<EOL>ax1.set_title('<STR_LIT>')<EOL>display(cbl_fig)<EOL>plt.close(cbl_fig)<EOL><DEDENT>with cx_widget:<EOL><INDENT>cx_fig = plt.figure(figsize=(<NUM_LIT:3>, <NUM_LIT:1>))<EOL>ax2 = cx_fig.add_axes([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>cx_cb = mpl.colorbar.ColorbarBase(ax2, cmap=cm.viridis,<EOL>norm=cx_norm,<EOL>orientation='<STR_LIT>')<EOL>cx_cb.locator = tick_locator<EOL>cx_cb.update_ticks()<EOL>ax2.set_title('<STR_LIT>')<EOL>display(cx_fig)<EOL>plt.close(cx_fig)<EOL><DEDENT>out_box = widgets.GridBox([single_widget, cmap_widget, cx_widget],<EOL>layout=widgets.Layout(<EOL>grid_template_rows='<STR_LIT>',<EOL>grid_template_columns='<STR_LIT>',<EOL>grid_template_areas='''<STR_LIT>''',<EOL>grid_gap='<STR_LIT>'))<EOL>return out_box<EOL>

Widget for displaying detailed noise map.

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        GridBox: Widget holding noise map images.


year = widgets.Output(layout=widgets.Layout(display='<STR_LIT>',<EOL>align_items='<STR_LIT>',<EOL>min_height='<STR_LIT>'))<EOL>month = widgets.Output(layout=widgets.Layout(display='<STR_LIT>',<EOL>align_items='<STR_LIT>',<EOL>min_height='<STR_LIT>'))<EOL>week = widgets.Output(layout=widgets.Layout(display='<STR_LIT>',<EOL>align_items='<STR_LIT>',<EOL>min_height='<STR_LIT>'))<EOL>tabs = widgets.Tab(layout=widgets.Layout(max_height='<STR_LIT>'))<EOL>tabs.children = [year, month, week]<EOL>tabs.set_title(<NUM_LIT:0>, '<STR_LIT>')<EOL>tabs.set_title(<NUM_LIT:1>, '<STR_LIT>')<EOL>tabs.set_title(<NUM_LIT:2>, '<STR_LIT>')<EOL>tabs.selected_index = <NUM_LIT:1><EOL>_build_job_history(tabs, backend)<EOL>return tabs<EOL>

Widget for displaying job history

    Args:
     backend (IBMQbackend): The backend.

    Returns:
        Tab: A tab widget for history images.


def get_date(job):<EOL><INDENT>"""<STR_LIT>"""<EOL>return datetime.datetime.strptime(job.creation_date(),<EOL>'<STR_LIT>')<EOL><DEDENT>current_time = datetime.datetime.now()<EOL>if interval == '<STR_LIT>':<EOL><INDENT>bins = [(current_time - datetime.timedelta(days=k*<NUM_LIT>/<NUM_LIT:12>))<EOL>for k in range(<NUM_LIT:12>)]<EOL><DEDENT>elif interval == '<STR_LIT>':<EOL><INDENT>bins = [(current_time - datetime.timedelta(days=k)) for k in range(<NUM_LIT:30>)]<EOL><DEDENT>elif interval == '<STR_LIT>':<EOL><INDENT>bins = [(current_time - datetime.timedelta(days=k)) for k in range(<NUM_LIT:7>)]<EOL><DEDENT>binned_jobs = [<NUM_LIT:0>]*len(bins)<EOL>if interval == '<STR_LIT>':<EOL><INDENT>for job in jobs:<EOL><INDENT>for ind, dat in enumerate(bins):<EOL><INDENT>date = get_date(job)<EOL>if date.month == dat.month:<EOL><INDENT>binned_jobs[ind] += <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for job in jobs:<EOL><INDENT>for ind, dat in enumerate(bins):<EOL><INDENT>date = get_date(job)<EOL>if date.day == dat.day and date.month == dat.month:<EOL><INDENT>binned_jobs[ind] += <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>nz_bins = []<EOL>nz_idx = []<EOL>for ind, val in enumerate(binned_jobs):<EOL><INDENT>if val != <NUM_LIT:0>:<EOL><INDENT>nz_idx.append(ind)<EOL>nz_bins.append(val)<EOL><DEDENT><DEDENT>total_jobs = sum(binned_jobs)<EOL>colors = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if interval == '<STR_LIT>':<EOL><INDENT>labels = ['<STR_LIT>'.format(str(bins[b].year)[<NUM_LIT:2>:], bins[b].month) for b in nz_idx]<EOL><DEDENT>else:<EOL><INDENT>labels = ['<STR_LIT>'.format(bins[b].month, bins[b].day) for b in nz_idx]<EOL><DEDENT>fig, ax = plt.subplots(<NUM_LIT:1>, <NUM_LIT:1>, figsize=(<NUM_LIT:5>, <NUM_LIT:5>))  <EOL>ax.pie(nz_bins[::-<NUM_LIT:1>], labels=labels, colors=colors, textprops={'<STR_LIT>': <NUM_LIT>},<EOL>rotatelabels=True, counterclock=False)<EOL>ax.add_artist(Circle((<NUM_LIT:0>, <NUM_LIT:0>), <NUM_LIT>, color='<STR_LIT>', zorder=<NUM_LIT:1>))<EOL>ax.text(<NUM_LIT:0>, <NUM_LIT:0>, total_jobs, horizontalalignment='<STR_LIT>',<EOL>verticalalignment='<STR_LIT>', fontsize=<NUM_LIT>)<EOL>fig.tight_layout()<EOL>return fig<EOL>

Plots the job history of the user from the given list of jobs.

    Args:
        jobs (list): A list of jobs with type IBMQjob.
        interval (str): Interval over which to examine.

    Returns:
        fig: A Matplotlib figure instance.


@line_magic<EOL><INDENT>def qiskit_backend_monitor(self, line='<STR_LIT>', cell=None):  <DEDENT>

backend = self.shell.user_ns[line]<EOL>if not isinstance(backend, IBMQBackend):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>title_style = "<STR_LIT>"<EOL>title_style += "<STR_LIT>"<EOL>title_html = "<STR_LIT>".format(<EOL>style=title_style, name=backend.name())<EOL>details = [config_tab(backend)]<EOL>tab_contents = ['<STR_LIT>']<EOL>if not backend.configuration().simulator:<EOL><INDENT>tab_contents.extend(['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'])<EOL>details.extend([qubits_tab(backend), gates_tab(backend),<EOL>detailed_map(backend), job_history(backend)])<EOL><DEDENT>tabs = widgets.Tab(layout=widgets.Layout(overflow_y='<STR_LIT>'))<EOL>tabs.children = details<EOL>for i in range(len(details)):<EOL><INDENT>tabs.set_title(i, tab_contents[i])<EOL><DEDENT>title_widget = widgets.HTML(value=title_html,<EOL>layout=widgets.Layout(margin='<STR_LIT>'))<EOL>backend_monitor = widgets.VBox([title_widget, tabs],<EOL>layout=widgets.Layout(border='<STR_LIT>',<EOL>max_height='<STR_LIT>', min_height='<STR_LIT>',<EOL>overflow_y='<STR_LIT>'))<EOL>display(backend_monitor)<EOL>

A Jupyter magic function to monitor backends.


config = backend.configuration().to_dict()<EOL>props = backend.properties().to_dict()<EOL>name = widgets.HTML(value="<STR_LIT>".format(name=backend.name()),<EOL>layout=widgets.Layout())<EOL>n_qubits = config['<STR_LIT>']<EOL>qubit_count = widgets.HTML(value="<STR_LIT>".format(qubits=n_qubits),<EOL>layout=widgets.Layout(justify_content='<STR_LIT>'))<EOL>cmap = widgets.Output(layout=widgets.Layout(min_width='<STR_LIT>', max_width='<STR_LIT>',<EOL>max_height='<STR_LIT>',<EOL>min_height='<STR_LIT>',<EOL>justify_content='<STR_LIT>',<EOL>align_items='<STR_LIT>',<EOL>margin='<STR_LIT>'))<EOL>with cmap:<EOL><INDENT>_cmap_fig = plot_gate_map(backend,<EOL>plot_directed=False,<EOL>label_qubits=False)<EOL>if _cmap_fig is not None:<EOL><INDENT>display(_cmap_fig)<EOL>plt.close(_cmap_fig)<EOL><DEDENT><DEDENT>pending = generate_jobs_pending_widget()<EOL>is_oper = widgets.HTML(value="<STR_LIT>",<EOL>layout=widgets.Layout(justify_content='<STR_LIT>'))<EOL>least_busy = widgets.HTML(value="<STR_LIT>",<EOL>layout=widgets.Layout(justify_content='<STR_LIT>'))<EOL>t1_units = props['<STR_LIT>'][<NUM_LIT:0>][<NUM_LIT:0>]['<STR_LIT>']<EOL>avg_t1 = round(sum([q[<NUM_LIT:0>]['<STR_LIT:value>'] for q in props['<STR_LIT>']])/n_qubits, <NUM_LIT:1>)<EOL>t1_widget = widgets.HTML(value="<STR_LIT>".format(t1=avg_t1, units=t1_units),<EOL>layout=widgets.Layout())<EOL>t2_units = props['<STR_LIT>'][<NUM_LIT:0>][<NUM_LIT:1>]['<STR_LIT>']<EOL>avg_t2 = round(sum([q[<NUM_LIT:1>]['<STR_LIT:value>'] for q in props['<STR_LIT>']])/n_qubits, <NUM_LIT:1>)<EOL>t2_widget = widgets.HTML(value="<STR_LIT>".format(t2=avg_t2, units=t2_units),<EOL>layout=widgets.Layout())<EOL>out = widgets.VBox([name, cmap, qubit_count, pending,<EOL>least_busy, is_oper, t1_widget, t2_widget],<EOL>layout=widgets.Layout(display='<STR_LIT>',<EOL>flex_flow='<STR_LIT>',<EOL>align_items='<STR_LIT>'))<EOL>out._is_alive = True<EOL>return out<EOL>