text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
# This code is part of Qiskit. # # (C) Copyright IBM 2021 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Routines for producing right-angled paths through the Weyl alcove. Consider a set of native interactions with an associated minimal covering set of minimum-cost circuit polytopes, as well as a target coordinate. The coverage set associates to the target coordinate a circuit type C = (O1 ... On) consisting of a sequence of native interactions Oj. A _path_ is a sequence (I P1 ... Pn) of intermediate Weyl points, where Pj is accessible from P(j-1) by Oj. A path is said to be _right-angled_ when at each step one coordinate is fixed (up to possible Weyl reflection) when expressed in canonical coordinates. The key inputs to our method are: + A family of "b coordinates" which describe the target canonical coordinate. + A family of "a coordinates" which describe the source canonical coordinate. + A sequence of interaction strengths for which the b-coordinate can be modeled, with one selected to be stripped from the sequence ("beta"). The others are bundled as the sum of the sequence (s+), its maximum value (s1), and its second maximum value (s2). Given the b-coordinate and a set of intersection strengths, the procedure for backsolving for the a-coordinates is then extracted from the monodromy polytope. NOTE: The constants in this file are auto-generated and are not meant to be edited by hand / read. """ from __future__ import annotations import numpy as np from .polytopes import ConvexPolytopeData, PolytopeData, manual_get_vertex, polytope_has_element def get_augmented_coordinate(target_coordinate, strengths): """ Assembles a coordinate in the system used by `xx_region_polytope`. """ *strengths, beta = strengths strengths = sorted(strengths + [0, 0]) interaction_coordinate = [sum(strengths), strengths[-1], strengths[-2], beta] return [*target_coordinate, *interaction_coordinate] def decomposition_hop(target_coordinate, strengths): """ Given a `target_coordinate` and a list of interaction `strengths`, produces a new canonical coordinate which is one step back along `strengths`. `target_coordinate` is taken to be in positive canonical coordinates, and the entries of strengths are taken to be [0, pi], so that (sj / 2, 0, 0) is a positive canonical coordinate. """ target_coordinate = [x / (np.pi / 2) for x in target_coordinate] strengths = [x / np.pi for x in strengths] augmented_coordinate = get_augmented_coordinate(target_coordinate, strengths) specialized_polytope = None for cp in xx_region_polytope.convex_subpolytopes: if not polytope_has_element(cp, augmented_coordinate): continue if "AF=B1" in cp.name: af, _, _ = target_coordinate elif "AF=B2" in cp.name: _, af, _ = target_coordinate elif "AF=B3" in cp.name: _, _, af = target_coordinate else: raise ValueError("Couldn't find a coordinate to fix.") raw_convex_polytope = next( (cpp for cpp in xx_lift_polytope.convex_subpolytopes if cpp.name == cp.name), None ) coefficient_dict = {} for inequality in raw_convex_polytope.inequalities: if inequality[1] == 0 and inequality[2] == 0: continue offset = ( inequality[0] # old constant term + inequality[3] * af + inequality[4] * augmented_coordinate[0] # b1 + inequality[5] * augmented_coordinate[1] # b2 + inequality[6] * augmented_coordinate[2] # b3 + inequality[7] * augmented_coordinate[3] # s+ + inequality[8] * augmented_coordinate[4] # s1 + inequality[9] * augmented_coordinate[5] # s2 + inequality[10] * augmented_coordinate[6] # beta ) if offset <= coefficient_dict.get((inequality[1], inequality[2]), offset): coefficient_dict[(inequality[1], inequality[2])] = offset specialized_polytope = PolytopeData( convex_subpolytopes=[ ConvexPolytopeData( inequalities=[[v, h, l] for ((h, l), v) in coefficient_dict.items()] ) ] ) break if specialized_polytope is None: raise ValueError("Failed to match a constrained_polytope summand.") ah, al = manual_get_vertex(specialized_polytope) return [x * (np.pi / 2) for x in sorted([ah, al, af], reverse=True)] xx_region_polytope = PolytopeData( convex_subpolytopes=[ ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, -2], [0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, -1, 0], [1, -1, -1, 0, 0, 0, 0, 0], [0, -1, -1, -1, 1, 0, 0, 1], [0, 1, -1, 0, 0, 0, 0, 0], [0, 1, -1, -1, 1, -2, 0, 1], [0, 1, -1, -1, 1, 0, 0, -1], [0, 0, 0, -1, 1, -1, 0, 0], [0, 0, -1, 0, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, 0, 1], ], equalities=[], name=( "I ∩ A alcove ∩ " "A unreflected ∩ ah slant ∩ al frustrum ∩ B alcove ∩ B unreflected ∩ AF=B3" ), ), ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, -2], [0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, -1, 0], [1, -1, -1, 0, 0, 0, 0, 0], [1, -1, -1, -1, 1, -2, 0, 1], [0, 1, -1, 0, 0, 0, 0, 0], [-1, 1, -1, -1, 1, 0, 0, 1], [1, -1, -1, -1, 1, 0, 0, -1], [0, 0, 0, -1, 1, -1, 0, 0], [0, 0, -1, 0, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, 0, 1], ], equalities=[], name=( "I ∩ A alcove ∩ " "A reflected ∩ ah strength ∩ al frustrum ∩ B alcove ∩ B reflected ∩ AF=B3" ), ), ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, -2], [0, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, -1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, -1, 0], [0, 1, -1, -1, 1, -2, 0, 1], [0, -1, -1, -1, 1, 0, 0, 1], [0, 0, 1, -1, 0, 0, 0, 0], [1, -1, 1, -1, 0, 0, 0, -1], [0, 1, 1, -1, 1, -2, 0, -1], [0, -1, 1, -1, 1, 0, 0, -1], [0, 0, 0, -1, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, 0, 1], ], equalities=[], name=( "I ∩ A alcove ∩ " "A unreflected ∩ af slant ∩ al frustrum ∩ B alcove ∩ B unreflected ∩ AF=B1" ), ), ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, -2], [0, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, -1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, -1, 0], [-1, 1, -1, -1, 1, 0, 0, 1], [1, -1, -1, -1, 1, -2, 0, 1], [0, 0, 1, -1, 0, 0, 0, 0], [1, -1, 1, -1, 0, 0, 0, -1], [-1, 1, 1, -1, 1, 0, 0, -1], [1, -1, 1, -1, 1, -2, 0, -1], [0, 0, 0, -1, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, 0, 1], ], equalities=[], name=( "I ∩ A alcove ∩ " "A reflected ∩ af strength ∩ al frustrum ∩ B alcove ∩ B reflected ∩ AF=B1" ), ), ] ) """ For any choice of sequence of strengths, the theory of the monodromy polytope yields a polytope P so that (b1, b2, b3) belongs to P if and only if (b1, b2, b3) is the positive canonical coordinate of a program expressible by a circuit whose 2Q interactions are the prescribed sequence of fractional CX strengths, interleaved with arbitrary single-qubit gates. The polytope above has the same property as P, but (1) it is parametrized over the sequence of strengths, and (2) it is broken into a certain sum of convex regions. Each region is tagged with a name, and it is the projection of the region of `xx_lift_polytope` (see below) with the corresponding name. The coordinates are [k, b1, b2, b3, s+, s1, s2, beta]. """ xx_lift_polytope = PolytopeData( convex_subpolytopes=[ ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [1, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0], [0, -1, -1, -1, 0, 0, 0, 1, 0, 0, 0], [0, 1, -1, -1, 0, 0, 0, 1, -2, 0, 0], [0, 0, -1, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, -1, -1, -1, 1, 0, 0, 1], [0, 0, 0, 0, 1, -1, -1, 1, -2, 0, 1], [0, 0, 0, 0, 1, -1, -1, 1, 0, 0, -1], [0, 0, 0, 0, 0, 0, -1, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, -1, 1, -1, 0, 0], [0, -1, -1, 0, 1, 1, 0, 0, 0, 0, 1], [2, -1, -1, 0, -1, -1, 0, 0, 0, 0, -1], [0, 1, 1, 0, -1, -1, 0, 0, 0, 0, 1], [0, -1, 1, 0, 1, -1, 0, 0, 0, 0, 1], [0, 1, -1, 0, -1, 1, 0, 0, 0, 0, 1], [0, 1, -1, 0, 1, -1, 0, 0, 0, 0, -1], ], equalities=[[0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0]], name=( "I ∩ A alcove ∩ " "A unreflected ∩ ah slant ∩ al frustrum ∩ B alcove ∩ B unreflected ∩ AF=B3" ), ), ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [1, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0], [0, -1, -1, -1, 0, 0, 0, 1, 0, 0, 0], [0, -1, -1, 1, 0, 0, 0, 1, -2, 0, 0], [0, 0, -1, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, -1, -1, -1, 1, 0, 0, 1], [0, 0, 0, 0, 1, -1, -1, 1, -2, 0, 1], [0, 0, 0, 0, 1, -1, -1, 1, 0, 0, -1], [0, 0, 0, 0, 0, 0, -1, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, -1, 1, -1, 0, 0], [0, -1, -1, 0, 0, 1, 1, 0, 0, 0, 1], [2, -1, -1, 0, 0, -1, -1, 0, 0, 0, -1], [0, 1, 1, 0, 0, -1, -1, 0, 0, 0, 1], [0, -1, 1, 0, 0, 1, -1, 0, 0, 0, 1], [0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 1], [0, 1, -1, 0, 0, 1, -1, 0, 0, 0, -1], ], equalities=[[0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0]], name=( "I ∩ A alcove ∩ " "A unreflected ∩ af slant ∩ al frustrum ∩ B alcove ∩ B unreflected ∩ AF=B1" ), ), ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [1, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0], [1, -1, -1, -1, 0, 0, 0, 1, -2, 0, 0], [-1, -1, -1, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, -1, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0], [-1, 0, 0, 0, 1, -1, -1, 1, 0, 0, 1], [1, 0, 0, 0, -1, -1, -1, 1, 0, 0, -1], [1, 0, 0, 0, -1, -1, -1, 1, -2, 0, 1], [0, 0, 0, 0, 0, 0, -1, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, -1, 1, -1, 0, 0], [0, -1, -1, 0, 0, 1, 1, 0, 0, 0, 1], [2, -1, -1, 0, 0, -1, -1, 0, 0, 0, -1], [0, 1, 1, 0, 0, -1, -1, 0, 0, 0, 1], [0, -1, 1, 0, 0, 1, -1, 0, 0, 0, 1], [0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 1], [0, 1, -1, 0, 0, 1, -1, 0, 0, 0, -1], ], equalities=[[0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0]], name=( "I ∩ A alcove ∩ " "A reflected ∩ af strength ∩ al frustrum ∩ B alcove ∩ B reflected ∩ AF=B1" ), ), ConvexPolytopeData( inequalities=[ [0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0], [1, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0], [1, -1, -1, -1, 0, 0, 0, 1, -2, 0, 0], [-1, 1, -1, -1, 0, 0, 0, 1, 0, 0, 0], [0, 0, -1, 0, 0, 0, 0, 1, -1, -1, 0], [0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0], [-1, 0, 0, 0, 1, -1, -1, 1, 0, 0, 1], [1, 0, 0, 0, -1, -1, -1, 1, 0, 0, -1], [1, 0, 0, 0, -1, -1, -1, 1, -2, 0, 1], [0, 0, 0, 0, 0, 0, -1, 1, -1, -1, 1], [0, 0, 0, 0, 0, 0, -1, 1, -1, 0, 0], [0, -1, -1, 0, 1, 1, 0, 0, 0, 0, 1], [2, -1, -1, 0, -1, -1, 0, 0, 0, 0, -1], [0, 1, 1, 0, -1, -1, 0, 0, 0, 0, 1], [0, -1, 1, 0, 1, -1, 0, 0, 0, 0, 1], [0, 1, -1, 0, -1, 1, 0, 0, 0, 0, 1], [0, 1, -1, 0, 1, -1, 0, 0, 0, 0, -1], ], equalities=[[0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0]], name=( "I ∩ A alcove ∩ " "A reflected ∩ ah strength ∩ al frustrum ∩ B alcove ∩ B reflected ∩ AF=B3" ), ), ] ) """ For any choice of sequence of strengths, the theory of the monodromy polytope yields a polytope Q so that (a1, a2, a3, b1, b2, b3) belongs to Q if and only if: * (b1, b2, b3) is the positive canonical coordinate of a program expressible by a circuit whose 2Q interactions are the prescribed sequence of fractional CX strengths, interleaved with arbitrary single-qubit gates. * (a1, a2, a3) is the positive canonical coordinate of a program expressible by a circuit whose 2Q interactions are the prescribed sequence of fractional CX strengths _with the last interaction omitted_, interleaved with arbitrary single-qubit gates. * (b1, b2, b3) is accessible from (a1, a2, a3) using single-qubit gates and a single application of the final fractional CX strength. The polytope above is a slight variation on Q: (1) It is parametrized over the sequence of strengths. (2) It is broken into a certain sum of convex regions. If (b1, b2, b3) belongs to the projection of one of these convex regions, then that same region's projection to (a1, a2, a3) is guaranteed to be nonempty. (To test this condition, see `xx_region_polytope`.) Points in this region can thus be used to calculate circuits using `decompose_xxyy_into_xxyy_xx`. The coordinates are [k, ah, al, af, b1, b2, b3, s+, s1, s2, beta]. """
qiskit/qiskit/synthesis/two_qubit/xx_decompose/paths.py/0
{ "file_path": "qiskit/qiskit/synthesis/two_qubit/xx_decompose/paths.py", "repo_id": "qiskit", "token_count": 10898 }
200
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Matrix designed for fast multiplication by permutation and block-diagonal ones. """ import numpy as np from .layer import Layer1Q, Layer2Q class PMatrix: """ Wrapper around a matrix that enables fast multiplication by permutation matrices and block-diagonal ones. """ def __init__(self, num_qubits: int): """ Initializes the internal structures of this object but does not set the matrix yet. Args: num_qubits: number of qubits. """ dim = 2**num_qubits self._mat = np.empty(0) self._dim = dim self._temp_g2x2 = np.zeros((2, 2), dtype=np.complex128) self._temp_g4x4 = np.zeros((4, 4), dtype=np.complex128) self._temp_2x2 = self._temp_g2x2.copy() self._temp_4x4 = self._temp_g4x4.copy() self._identity_perm = np.arange(dim, dtype=np.int64) self._left_perm = self._identity_perm.copy() self._right_perm = self._identity_perm.copy() self._temp_perm = self._identity_perm.copy() self._temp_slice_dim_x_2 = np.zeros((dim, 2), dtype=np.complex128) self._temp_slice_dim_x_4 = np.zeros((dim, 4), dtype=np.complex128) self._idx_mat = self._init_index_matrix(dim) self._temp_block_diag = np.zeros(self._idx_mat.shape, dtype=np.complex128) def set_matrix(self, mat: np.ndarray): """ Copies specified matrix to internal storage. Once the matrix is set, the object is ready for use. **Note**, the matrix will be copied, mind the size issues. Args: mat: matrix we want to multiply on the left and on the right by layer matrices. """ if self._mat.size == 0: self._mat = mat.copy() else: np.copyto(self._mat, mat) @staticmethod def _init_index_matrix(dim: int) -> np.ndarray: """ Fast multiplication can be implemented by picking up a subset of entries in a sparse matrix. Args: dim: problem dimensionality. Returns: 2d-array of indices for the fast multiplication. """ all_idx = np.arange(dim * dim, dtype=np.int64).reshape(dim, dim) idx = np.full((dim // 4, 4 * 4), fill_value=0, dtype=np.int64) b = np.full((4, 4), fill_value=0, dtype=np.int64) for i in range(0, dim, 4): b[:, :] = all_idx[i : i + 4, i : i + 4] idx[i // 4, :] = b.T.ravel() return idx def mul_right_q1(self, layer: Layer1Q, temp_mat: np.ndarray, dagger: bool): """ Multiplies ``NxN`` matrix, wrapped by this object, by a 1-qubit layer matrix of the right, where ``N`` is the actual size of matrices involved, ``N = 2^{num. of qubits}``. Args: layer: 1-qubit layer, i.e. the layer with just one non-trivial 1-qubit gate and other gates are just identity operators. temp_mat: a temporary NxN matrix used as a workspace. dagger: if true, the right-hand side matrix will be taken as conjugate transposed. """ gmat, perm, inv_perm = layer.get_attr() mat = self._mat dim = perm.size # temp_mat <-- mat[:, right_perm[perm]] = mat[:, right_perm][:, perm]: np.take(mat, np.take(self._right_perm, perm, out=self._temp_perm), axis=1, out=temp_mat) # mat <-- mat[:, right_perm][:, perm] @ kron(I(N/4), gmat)^dagger, where # conjugate-transposition might be or might be not applied: gmat_right = np.conj(gmat, out=self._temp_g2x2).T if dagger else gmat for i in range(0, dim, 2): mat[:, i : i + 2] = np.dot( temp_mat[:, i : i + 2], gmat_right, out=self._temp_slice_dim_x_2 ) # Update right permutation: self._right_perm[:] = inv_perm def mul_right_q2(self, layer: Layer2Q, temp_mat: np.ndarray, dagger: bool = True): """ Multiplies ``NxN`` matrix, wrapped by this object, by a 2-qubit layer matrix on the right, where ``N`` is the actual size of matrices involved, ``N = 2^{num. of qubits}``. Args: layer: 2-qubit layer, i.e. the layer with just one non-trivial 2-qubit gate and other gates are just identity operators. temp_mat: a temporary NxN matrix used as a workspace. dagger: if true, the right-hand side matrix will be taken as conjugate transposed. """ gmat, perm, inv_perm = layer.get_attr() mat = self._mat dim = perm.size # temp_mat <-- mat[:, right_perm[perm]] = mat[:, right_perm][:, perm]: np.take(mat, np.take(self._right_perm, perm, out=self._temp_perm), axis=1, out=temp_mat) # mat <-- mat[:, right_perm][:, perm] @ kron(I(N/4), gmat)^dagger, where # conjugate-transposition might be or might be not applied: gmat_right = np.conj(gmat, out=self._temp_g4x4).T if dagger else gmat for i in range(0, dim, 4): mat[:, i : i + 4] = np.dot( temp_mat[:, i : i + 4], gmat_right, out=self._temp_slice_dim_x_4 ) # Update right permutation: self._right_perm[:] = inv_perm def mul_left_q1(self, layer: Layer1Q, temp_mat: np.ndarray): """ Multiplies ``NxN`` matrix, wrapped by this object, by a 1-qubit layer matrix of the left, where ``dim`` is the actual size of matrices involved, ``dim = 2^{num. of qubits}``. Args: layer: 1-qubit layer, i.e. the layer with just one non-trivial 1-qubit gate and other gates are just identity operators. temp_mat: a temporary NxN matrix used as a workspace. """ mat = self._mat gmat, perm, inv_perm = layer.get_attr() dim = perm.size # temp_mat <-- mat[left_perm[perm]] = mat[left_perm][perm]: np.take(mat, np.take(self._left_perm, perm, out=self._temp_perm), axis=0, out=temp_mat) # mat <-- kron(I(dim/4), gmat) @ mat[left_perm][perm]: if dim > 512: # Faster for large matrices. for i in range(0, dim, 2): np.dot(gmat, temp_mat[i : i + 2, :], out=mat[i : i + 2, :]) else: # Faster for small matrices. half = dim // 2 np.copyto( mat.reshape((2, half, dim)), np.swapaxes(temp_mat.reshape((half, 2, dim)), 0, 1) ) np.dot(gmat, mat.reshape(2, -1), out=temp_mat.reshape(2, -1)) np.copyto( mat.reshape((half, 2, dim)), np.swapaxes(temp_mat.reshape((2, half, dim)), 0, 1) ) # Update left permutation: self._left_perm[:] = inv_perm def mul_left_q2(self, layer: Layer2Q, temp_mat: np.ndarray): """ Multiplies ``NxN`` matrix, wrapped by this object, by a 2-qubit layer matrix on the left, where ``dim`` is the actual size of matrices involved, ``dim = 2^{num. of qubits}``. Args: layer: 2-qubit layer, i.e. the layer with just one non-trivial 2-qubit gate and other gates are just identity operators. temp_mat: a temporary NxN matrix used as a workspace. """ mat = self._mat gmat, perm, inv_perm = layer.get_attr() dim = perm.size # temp_mat <-- mat[left_perm[perm]] = mat[left_perm][perm]: np.take(mat, np.take(self._left_perm, perm, out=self._temp_perm), axis=0, out=temp_mat) # mat <-- kron(I(dim/4), gmat) @ mat[left_perm][perm]: if dim > 512: # Faster for large matrices. for i in range(0, dim, 4): np.dot(gmat, temp_mat[i : i + 4, :], out=mat[i : i + 4, :]) else: # Faster for small matrices. half = dim // 4 np.copyto( mat.reshape((4, half, dim)), np.swapaxes(temp_mat.reshape((half, 4, dim)), 0, 1) ) np.dot(gmat, mat.reshape(4, -1), out=temp_mat.reshape(4, -1)) np.copyto( mat.reshape((half, 4, dim)), np.swapaxes(temp_mat.reshape((4, half, dim)), 0, 1) ) # Update left permutation: self._left_perm[:] = inv_perm def product_q1(self, layer: Layer1Q, tmp1: np.ndarray, tmp2: np.ndarray) -> np.complex128: """ Computes and returns: ``Trace(mat @ C) = Trace(mat @ P^T @ gmat @ P) = Trace((P @ mat @ P^T) @ gmat) = Trace(C @ (P @ mat @ P^T)) = vec(gmat^T)^T @ vec(P @ mat @ P^T)``, where mat is ``NxN`` matrix wrapped by this object, ``C`` is matrix representation of the layer ``L``, and gmat is 2x2 matrix of underlying 1-qubit gate. **Note**: matrix of this class must be finalized beforehand. Args: layer: 1-qubit layer. tmp1: temporary, external matrix used as a workspace. tmp2: temporary, external matrix used as a workspace. Returns: trace of the matrix product. """ mat = self._mat gmat, perm, _ = layer.get_attr() # tmp2 = P @ mat @ P^T: np.take(np.take(mat, perm, axis=0, out=tmp1), perm, axis=1, out=tmp2) # matrix dot product = Tr(transposed(kron(I(dim/4), gmat)), (P @ mat @ P^T)): gmat_t, tmp3 = self._temp_g2x2, self._temp_2x2 np.copyto(gmat_t, gmat.T) _sum = 0.0 for i in range(0, mat.shape[0], 2): tmp3[:, :] = tmp2[i : i + 2, i : i + 2] _sum += np.dot(gmat_t.ravel(), tmp3.ravel()) return np.complex128(_sum) def product_q2(self, layer: Layer2Q, tmp1: np.ndarray, tmp2: np.ndarray) -> np.complex128: """ Computes and returns: ``Trace(mat @ C) = Trace(mat @ P^T @ gmat @ P) = Trace((P @ mat @ P^T) @ gmat) = Trace(C @ (P @ mat @ P^T)) = vec(gmat^T)^T @ vec(P @ mat @ P^T)``, where mat is ``NxN`` matrix wrapped by this object, ``C`` is matrix representation of the layer ``L``, and gmat is 4x4 matrix of underlying 2-qubit gate. **Note**: matrix of this class must be finalized beforehand. Args: layer: 2-qubit layer. tmp1: temporary, external matrix used as a workspace. tmp2: temporary, external matrix used as a workspace. Returns: trace of the matrix product. """ mat = self._mat gmat, perm, _ = layer.get_attr() # Compute the matrix dot product: # Tr(transposed(kron(I(dim/4), gmat)), (P @ mat @ P^T)): # The fastest version so far, but requires two NxN temp. matrices. # tmp2 = P @ mat @ P^T: np.take(np.take(mat, perm, axis=0, out=tmp1), perm, axis=1, out=tmp2) bldia = self._temp_block_diag np.take(tmp2.ravel(), self._idx_mat.ravel(), axis=0, out=bldia.ravel()) bldia *= gmat.reshape(-1, gmat.size) return np.complex128(np.sum(bldia)) def finalize(self, temp_mat: np.ndarray) -> np.ndarray: """ Applies the left (row) and right (column) permutations to the matrix. at the end of computation process. Args: temp_mat: temporary, external matrix. Returns: finalized matrix with all transformations applied. """ mat = self._mat # mat <-- mat[left_perm][:, right_perm] = P_left @ mat @ transposed(P_right) np.take(mat, self._left_perm, axis=0, out=temp_mat) np.take(temp_mat, self._right_perm, axis=1, out=mat) # Set both permutations to identity once they have been applied. self._left_perm[:] = self._identity_perm self._right_perm[:] = self._identity_perm return self._mat
qiskit/qiskit/synthesis/unitary/aqc/fast_gradient/pmatrix.py/0
{ "file_path": "qiskit/qiskit/synthesis/unitary/aqc/fast_gradient/pmatrix.py", "repo_id": "qiskit", "token_count": 5745 }
201
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Automatically require analysis passes for resource estimation.""" from qiskit.transpiler.basepasses import AnalysisPass from qiskit.transpiler.passes.analysis.depth import Depth from qiskit.transpiler.passes.analysis.width import Width from qiskit.transpiler.passes.analysis.size import Size from qiskit.transpiler.passes.analysis.count_ops import CountOps from qiskit.transpiler.passes.analysis.num_tensor_factors import NumTensorFactors from qiskit.transpiler.passes.analysis.num_qubits import NumQubits class ResourceEstimation(AnalysisPass): """Automatically require analysis passes for resource estimation. An analysis pass for automatically running: * Depth() * Width() * Size() * CountOps() * NumTensorFactors() """ def __init__(self): super().__init__() self.requires += [Depth(), Width(), Size(), CountOps(), NumTensorFactors(), NumQubits()] def run(self, _): """Run the ResourceEstimation pass on `dag`.""" pass
qiskit/qiskit/transpiler/passes/analysis/resource_estimation.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/analysis/resource_estimation.py", "repo_id": "qiskit", "token_count": 468 }
202
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Convenience function to load RZXGate based templates. """ from enum import Enum from typing import List, Dict from qiskit.circuit.library.templates import rzx def rzx_templates(template_list: List[str] = None) -> Dict: """Convenience function to get the cost_dict and templates for template matching. Args: template_list: List of instruction names. Returns: Decomposition templates and cost values. """ class RZXTemplateMap(Enum): """Mapping of instruction name to decomposition template.""" ZZ1 = rzx.rzx_zz1() ZZ2 = rzx.rzx_zz2() ZZ3 = rzx.rzx_zz3() YZ = rzx.rzx_yz() XZ = rzx.rzx_xz() CY = rzx.rzx_cy() if template_list is None: template_list = ["zz1", "zz2", "zz3", "yz", "xz", "cy"] templates = [RZXTemplateMap[gate.upper()].value for gate in template_list] cost_dict = {"rzx": 0, "cx": 6, "rz": 0, "sx": 1, "p": 0, "h": 1, "rx": 1, "ry": 1} rzx_dict = {"template_list": templates, "user_cost_dict": cost_dict} return rzx_dict
qiskit/qiskit/transpiler/passes/calibration/rzx_templates.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/calibration/rzx_templates.py", "repo_id": "qiskit", "token_count": 585 }
203
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """This module contains common utils for vf2 layout passes.""" from collections import defaultdict import statistics import random import numpy as np from rustworkx import PyDiGraph, PyGraph, connected_components from qiskit.circuit import ForLoopOp from qiskit.converters import circuit_to_dag from qiskit._accelerate import vf2_layout from qiskit._accelerate.nlayout import NLayout from qiskit._accelerate.error_map import ErrorMap def build_interaction_graph(dag, strict_direction=True): """Build an interaction graph from a dag.""" im_graph = PyDiGraph(multigraph=False) if strict_direction else PyGraph(multigraph=False) im_graph_node_map = {} reverse_im_graph_node_map = {} class MultiQEncountered(Exception): """Used to singal an error-status return from the DAG visitor.""" def _visit(dag, weight, wire_map): for node in dag.op_nodes(include_directives=False): if node.is_control_flow(): if isinstance(node.op, ForLoopOp): inner_weight = len(node.op.params[0]) * weight else: inner_weight = weight for block in node.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits) } _visit(circuit_to_dag(block), inner_weight, inner_wire_map) continue len_args = len(node.qargs) qargs = [wire_map[q] for q in node.qargs] if len_args == 1: if qargs[0] not in im_graph_node_map: weights = defaultdict(int) weights[node.name] += weight im_graph_node_map[qargs[0]] = im_graph.add_node(weights) reverse_im_graph_node_map[im_graph_node_map[qargs[0]]] = qargs[0] else: im_graph[im_graph_node_map[qargs[0]]][node.name] += weight if len_args == 2: if qargs[0] not in im_graph_node_map: im_graph_node_map[qargs[0]] = im_graph.add_node(defaultdict(int)) reverse_im_graph_node_map[im_graph_node_map[qargs[0]]] = qargs[0] if qargs[1] not in im_graph_node_map: im_graph_node_map[qargs[1]] = im_graph.add_node(defaultdict(int)) reverse_im_graph_node_map[im_graph_node_map[qargs[1]]] = qargs[1] edge = (im_graph_node_map[qargs[0]], im_graph_node_map[qargs[1]]) if im_graph.has_edge(*edge): im_graph.get_edge_data(*edge)[node.name] += weight else: weights = defaultdict(int) weights[node.name] += weight im_graph.add_edge(*edge, weights) if len_args > 2: raise MultiQEncountered() try: _visit(dag, 1, {bit: bit for bit in dag.qubits}) except MultiQEncountered: return None # Remove components with no 2q interactions from interaction graph # these will be evaluated separately independently of scoring isomorphic # mappings. This is not done for strict direction because for post layout # we need to factor in local operation constraints when evaluating a graph free_nodes = {} if not strict_direction: conn_comp = connected_components(im_graph) for comp in conn_comp: if len(comp) == 1: index = comp.pop() free_nodes[index] = im_graph[index] im_graph.remove_node(index) return im_graph, im_graph_node_map, reverse_im_graph_node_map, free_nodes def build_edge_list(im_graph): """Generate an edge list for scoring.""" return vf2_layout.EdgeList( [((edge[0], edge[1]), sum(edge[2].values())) for edge in im_graph.edge_index_map().values()] ) def build_bit_list(im_graph, bit_map): """Generate a bit list for scoring.""" bit_list = np.zeros(len(im_graph), dtype=np.int32) for node_index in bit_map.values(): try: bit_list[node_index] = sum(im_graph[node_index].values()) # If node_index not in im_graph that means there was a standalone # node we will score/sort separately outside the vf2 mapping, so we # can skip the hole except IndexError: pass return bit_list def score_layout( avg_error_map, layout_mapping, bit_map, _reverse_bit_map, im_graph, strict_direction=False, run_in_parallel=False, edge_list=None, bit_list=None, ): """Score a layout given an average error map.""" if layout_mapping: size = max(max(layout_mapping), max(layout_mapping.values())) else: size = 0 nlayout = NLayout(layout_mapping, size + 1, size + 1) if bit_list is None: bit_list = build_bit_list(im_graph, bit_map) if edge_list is None: edge_list = build_edge_list(im_graph) return vf2_layout.score_layout( bit_list, edge_list, avg_error_map, nlayout, strict_direction, run_in_parallel ) def build_average_error_map(target, properties, coupling_map): """Build an average error map used for scoring layouts pre-basis translation.""" num_qubits = 0 if target is not None and target.qargs is not None: num_qubits = target.num_qubits avg_map = ErrorMap(len(target.qargs)) elif coupling_map is not None: num_qubits = coupling_map.size() avg_map = ErrorMap(num_qubits + coupling_map.graph.num_edges()) else: # If coupling map is not defined almost certainly we don't have any # data to build an error map, but just in case initialize an empty # object avg_map = ErrorMap(0) built = False if target is not None and target.qargs is not None: for qargs in target.qargs: if qargs is None: continue qarg_error = 0.0 count = 0 for op in target.operation_names_for_qargs(qargs): inst_props = target[op].get(qargs, None) if inst_props is not None and inst_props.error is not None: count += 1 qarg_error += inst_props.error if count > 0: if len(qargs) == 1: qargs = (qargs[0], qargs[0]) avg_map.add_error(qargs, qarg_error / count) built = True elif properties is not None: errors = defaultdict(list) for qubit in range(len(properties.qubits)): errors[(qubit,)].append(properties.readout_error(qubit)) for gate in properties.gates: qubits = tuple(gate.qubits) for param in gate.parameters: if param.name == "gate_error": errors[qubits].append(param.value) for k, v in errors.items(): if len(k) == 1: qargs = (k[0], k[0]) else: qargs = k # If the properties payload contains an index outside the number of qubits # the properties are invalid for the given input. This normally happens either # with a malconstructed properties payload or if the faulty qubits feature of # BackendV1/BackendPropeties is being used. In such cases we map noise characteristics # so we should just treat the mapping as an ideal case. if qargs[0] >= num_qubits or qargs[1] >= num_qubits: continue avg_map.add_error(qargs, statistics.mean(v)) built = True # if there are no error rates in the target we should fallback to using the degree heuristic # used for a coupling map. To do this we can build the coupling map from the target before # running the fallback heuristic if not built and target is not None and coupling_map is None: coupling_map = target.build_coupling_map() if not built and coupling_map is not None: for qubit in range(num_qubits): avg_map.add_error( (qubit, qubit), (coupling_map.graph.out_degree(qubit) + coupling_map.graph.in_degree(qubit)) / num_qubits, ) for edge in coupling_map.graph.edge_list(): avg_map.add_error(edge, (avg_map[edge[0], edge[0]] + avg_map[edge[1], edge[1]]) / 2) built = True if built: return avg_map else: return None def shuffle_coupling_graph(coupling_map, seed, strict_direction=True): """Create a shuffled coupling graph from a coupling map.""" if strict_direction: cm_graph = coupling_map.graph else: cm_graph = coupling_map.graph.to_undirected(multigraph=False) cm_nodes = list(cm_graph.node_indexes()) if seed != -1: random.Random(seed).shuffle(cm_nodes) shuffled_cm_graph = type(cm_graph)() shuffled_cm_graph.add_nodes_from(cm_nodes) new_edges = [(cm_nodes[edge[0]], cm_nodes[edge[1]]) for edge in cm_graph.edge_list()] shuffled_cm_graph.add_edges_from_no_data(new_edges) cm_nodes = [k for k, v in sorted(enumerate(cm_nodes), key=lambda item: item[1])] cm_graph = shuffled_cm_graph return cm_graph, cm_nodes def map_free_qubits( free_nodes, partial_layout, num_physical_qubits, reverse_bit_map, avg_error_map ): """Add any free nodes to a layout.""" if not free_nodes: return partial_layout if avg_error_map is not None: free_qubits = sorted( set(range(num_physical_qubits)) - partial_layout.get_physical_bits().keys(), key=lambda bit: avg_error_map.get((bit, bit), 1.0), ) # If no error map is available this means there is no scoring heuristic available for this # backend and we can just randomly pick a free qubit else: free_qubits = list( set(range(num_physical_qubits)) - partial_layout.get_physical_bits().keys() ) for im_index in sorted(free_nodes, key=lambda x: sum(free_nodes[x].values())): if not free_qubits: return None selected_qubit = free_qubits.pop(0) partial_layout.add(reverse_bit_map[im_index], selected_qubit) return partial_layout
qiskit/qiskit/transpiler/passes/layout/vf2_utils.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/layout/vf2_utils.py", "repo_id": "qiskit", "token_count": 4832 }
204
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Pass for Hoare logic circuit optimization.""" from qiskit.transpiler.basepasses import TransformationPass from qiskit.circuit import QuantumRegister, ControlledGate, Gate from qiskit.dagcircuit import DAGCircuit from qiskit.circuit.library import UnitaryGate from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.library.standard_gates import CZGate, CU1Gate, MCU1Gate from qiskit.utils import optionals as _optionals @_optionals.HAS_Z3.require_in_instance class HoareOptimizer(TransformationPass): """This is a transpiler pass using Hoare logic circuit optimization. The inner workings of this are detailed in: https://arxiv.org/abs/1810.00375 """ def __init__(self, size=10): """ Args: size (int): size of gate cache, in number of gates Raises: MissingOptionalLibraryError: if unable to import z3 solver """ # This module is just a script that adds several post conditions onto existing classes. from . import _gate_extension super().__init__() self.solver = None self.variables = None self.gatenum = None self.gatecache = None self.varnum = None self.size = size def _gen_variable(self, qubit): """After each gate generate a new unique variable name for each of the qubits, using scheme: 'q[id]_[gatenum]', e.g. q1_0 -> q1_1 -> q1_2, q2_0 -> q2_1 Args: qubit (Qubit): qubit to generate new variable for Returns: BoolRef: z3 variable of qubit state """ import z3 varname = "q" + str(qubit) + "_" + str(self.gatenum[qubit]) var = z3.Bool(varname) self.gatenum[qubit] += 1 self.variables[qubit].append(var) return var def _initialize(self, dag): """create boolean variables for each qubit and apply qb == 0 condition Args: dag (DAGCircuit): input DAG to get qubits from """ import z3 for qbt in dag.qubits: self.gatenum[qbt] = 0 self.variables[qbt] = [] self.gatecache[qbt] = [] self.varnum[qbt] = {} x = self._gen_variable(qbt) self.solver.add(z3.Not(x)) def _add_postconditions(self, gate, ctrl_ones, trgtqb, trgtvar): """create boolean variables for each qubit the gate is applied to and apply the relevant post conditions. a gate rotating out of the z-basis will not have any valid post-conditions, in which case the qubit state is unknown Args: gate (Gate): gate to inspect ctrl_ones (BoolRef): z3 condition asserting all control qubits to 1 trgtqb (list((QuantumRegister, int))): list of target qubits trgtvar (list(BoolRef)): z3 variables corresponding to latest state of target qubits """ import z3 new_vars = [] for qbt in trgtqb: new_vars.append(self._gen_variable(qbt)) try: self.solver.add(z3.Implies(ctrl_ones, gate._postconditions(*(trgtvar + new_vars)))) except AttributeError: pass for i, tvar in enumerate(trgtvar): self.solver.add(z3.Implies(z3.Not(ctrl_ones), new_vars[i] == tvar)) def _test_gate(self, gate, ctrl_ones, trgtvar): """use z3 sat solver to determine triviality of gate Args: gate (Gate): gate to inspect ctrl_ones (BoolRef): z3 condition asserting all control qubits to 1 trgtvar (list(BoolRef)): z3 variables corresponding to latest state of target qubits Returns: bool: if gate is trivial """ import z3 trivial = False self.solver.push() try: triv_cond = gate._trivial_if(*trgtvar) except AttributeError: self.solver.add(ctrl_ones) trivial = self.solver.check() == z3.unsat else: if isinstance(triv_cond, bool): if triv_cond and len(trgtvar) == 1: self.solver.add(z3.Not(z3.And(ctrl_ones, trgtvar[0]))) sol1 = self.solver.check() == z3.unsat self.solver.pop() self.solver.push() self.solver.add(z3.And(ctrl_ones, trgtvar[0])) sol2 = self.solver.check() == z3.unsat trivial = sol1 or sol2 else: self.solver.add(z3.And(ctrl_ones, z3.Not(triv_cond))) trivial = self.solver.check() == z3.unsat self.solver.pop() return trivial def _remove_control(self, gate, ctrlvar, trgtvar): """use z3 sat solver to determine if all control qubits are in 1 state, and if so replace the Controlled - U by U. Args: gate (Gate): gate to inspect ctrlvar (list(BoolRef)): z3 variables corresponding to latest state of control qubits trgtvar (list(BoolRef)): z3 variables corresponding to latest state of target qubits Returns: Tuple(bool, DAGCircuit, List):: * bool:if controlled gate can be replaced. * DAGCircuit: with U applied to the target qubits. * List: with indices of target qubits. """ remove = False qarg = QuantumRegister(gate.num_qubits) dag = DAGCircuit() dag.add_qreg(qarg) qb = list(range(len(ctrlvar), gate.num_qubits)) # last qubits as target. if isinstance(gate, ControlledGate): remove = self._check_removal(ctrlvar) # try with other qubit as 'target'. if isinstance(gate, (CZGate, CU1Gate, MCU1Gate)): while not remove and qb[0] > 0: qb[0] = qb[0] - 1 ctrl_vars = ctrlvar[: qb[0]] + ctrlvar[qb[0] + 1 :] + trgtvar remove = self._check_removal(ctrl_vars) if remove: qubits = [qarg[qi] for qi in qb] dag.apply_operation_back(gate.base_gate, qubits) return remove, dag, qb def _check_removal(self, ctrlvar): import z3 ctrl_ones = z3.And(*ctrlvar) self.solver.push() self.solver.add(z3.Not(ctrl_ones)) remove = self.solver.check() == z3.unsat self.solver.pop() return remove def _traverse_dag(self, dag): """traverse DAG in topological order for each gate check: if any control is 0, or if triviality conditions are satisfied if yes remove gate from dag apply postconditions of gate Args: dag (DAGCircuit): input DAG to optimize in place """ import z3 for node in dag.topological_op_nodes(): gate = node.op ctrlqb, ctrlvar, trgtqb, trgtvar = self._seperate_ctrl_trgt(node) ctrl_ones = z3.And(*ctrlvar) remove_ctrl, new_dag, qb_idx = self._remove_control(gate, ctrlvar, trgtvar) if remove_ctrl: dag.substitute_node_with_dag(node, new_dag) gate = gate.base_gate node.op = gate.to_mutable() node.name = gate.name node.qargs = tuple((ctrlqb + trgtqb)[qi] for qi in qb_idx) _, ctrlvar, trgtqb, trgtvar = self._seperate_ctrl_trgt(node) ctrl_ones = z3.And(*ctrlvar) trivial = self._test_gate(gate, ctrl_ones, trgtvar) if trivial: dag.remove_op_node(node) elif self.size > 1: for qbt in node.qargs: self.gatecache[qbt].append(node) self.varnum[qbt][node] = self.gatenum[qbt] - 1 for qbt in node.qargs: if len(self.gatecache[qbt]) >= self.size: self._multigate_opt(dag, qbt) self._add_postconditions(gate, ctrl_ones, trgtqb, trgtvar) def _remove_successive_identity(self, dag, qubit, from_idx=None): """remove gates that have the same set of target qubits, follow each other immediately on these target qubits, and combine to the identity (consider sequences of length 2 for now) Args: dag (DAGCircuit): the directed acyclic graph to run on. qubit (Qubit): qubit cache to inspect from_idx (int): only gates whose indexes in the cache are larger than this value can be removed """ i = 0 while i < len(self.gatecache[qubit]) - 1: append = True node1 = self.gatecache[qubit][i] node2 = self.gatecache[qubit][i + 1] trgtqb1 = self._seperate_ctrl_trgt(node1)[2] trgtqb2 = self._seperate_ctrl_trgt(node2)[2] i += 1 if trgtqb1 != trgtqb2: continue try: for qbt in trgtqb1: idx = self.gatecache[qbt].index(node1) if self.gatecache[qbt][idx + 1] is not node2: append = False except (IndexError, ValueError): continue seq = [node1, node2] if append and self._is_identity(seq) and self._seq_as_one(seq): i += 1 for node in seq: dag.remove_op_node(node) if from_idx is None or self.gatecache[qubit].index(node) > from_idx: for qbt in node.qargs: self.gatecache[qbt].remove(node) def _is_identity(self, sequence): """determine whether the sequence of gates combines to the identity (consider sequences of length 2 for now) Args: sequence (list(DAGOpNode)): gate sequence to inspect Returns: bool: if gate sequence combines to identity """ assert len(sequence) == 2 # some Instructions (e.g measurements) may not have an inverse. try: gate1, gate2 = sequence[0].op, sequence[1].op.inverse() except CircuitError: return False par1, par2 = gate1.params, gate2.params def1, def2 = gate1.definition, gate2.definition if isinstance(gate1, ControlledGate): gate1 = gate1.base_gate gate1 = gate1.base_class if isinstance(gate2, ControlledGate): gate2 = gate2.base_gate gate2 = gate2.base_class # equality of gates can be determined via type and parameters, unless # the gates have no specific type, in which case definition is used # or they are unitary gates, in which case matrix equality is used if gate1 is Gate and gate2 is Gate: return def1 == def2 and def1 and def2 elif gate1 is UnitaryGate and gate2 is UnitaryGate: return matrix_equal(par1[0], par2[0], ignore_phase=True) return gate1 == gate2 and par1 == par2 def _seq_as_one(self, sequence): """use z3 solver to determine if the gates in the sequence are either all executed or none of them are executed, based on control qubits (consider sequences of length 2 for now) Args: sequence (list(DAGOpNode)): gate sequence to inspect Returns: bool: if gate sequence is only executed completely or not at all """ from z3 import Or, And, Not import z3 assert len(sequence) == 2 ctrlvar1 = self._seperate_ctrl_trgt(sequence[0])[1] ctrlvar2 = self._seperate_ctrl_trgt(sequence[1])[1] self.solver.push() self.solver.add( Or(And(And(*ctrlvar1), Not(And(*ctrlvar2))), And(Not(And(*ctrlvar1)), And(*ctrlvar2))) ) res = self.solver.check() == z3.unsat self.solver.pop() return res def _multigate_opt(self, dag, qubit, max_idx=None, dnt_rec=None): """ Args: dag (DAGCircuit): the directed acyclic graph to run on. qubit (Qubit): qubit whose gate cache is to be optimized max_idx (int): a value indicates a recursive call, optimize and remove gates up to this point in the cache dnt_rec (list(int)): don't recurse on these qubit caches (again) """ if not self.gatecache[qubit]: return # try to optimize this qubit's pipeline self._remove_successive_identity(dag, qubit, max_idx) if len(self.gatecache[qubit]) < self.size and max_idx is None: # unless in a rec call, we are done if the cache isn't full return elif max_idx is None: # need to remove at least one gate from cache, so remove oldest max_idx = 0 dnt_rec = set() dnt_rec.add(qubit) gates_tbr = [self.gatecache[qubit][0]] else: # need to remove all gates up to max_idx (in reverse order) gates_tbr = self.gatecache[qubit][max_idx::-1] for node in gates_tbr: # for rec call, only look at qubits that haven't been optimized yet new_qb = [x for x in node.qargs if x not in dnt_rec] dnt_rec.update(new_qb) for qbt in new_qb: idx = self.gatecache[qbt].index(node) # recursive chain to optimize all gates in this qubit's cache self._multigate_opt(dag, qbt, max_idx=idx, dnt_rec=dnt_rec) # truncate gatecache for this qubit to after above gate self.gatecache[qubit] = self.gatecache[qubit][max_idx + 1 :] def _seperate_ctrl_trgt(self, node): """Get the target qubits and control qubits if available, as well as their respective z3 variables. """ gate = node.op if isinstance(gate, ControlledGate): numctrl = gate.num_ctrl_qubits else: numctrl = 0 ctrlqb = node.qargs[:numctrl] trgtqb = node.qargs[numctrl:] try: ctrlvar = [self.variables[qb][self.varnum[qb][node]] for qb in ctrlqb] trgtvar = [self.variables[qb][self.varnum[qb][node]] for qb in trgtqb] except KeyError: ctrlvar = [self.variables[qb][-1] for qb in ctrlqb] trgtvar = [self.variables[qb][-1] for qb in trgtqb] return (ctrlqb, ctrlvar, trgtqb, trgtvar) def _reset(self): """Reset HoareOptimize internal state, so it can be run multiple times. """ import z3 self.solver = z3.Solver() self.variables = {} self.gatenum = {} self.gatecache = {} self.varnum = {} def run(self, dag): """ Args: dag (DAGCircuit): the directed acyclic graph to run on. Returns: DAGCircuit: Transformed DAG. """ self._reset() self._initialize(dag) self._traverse_dag(dag) if self.size > 1: for qbt in dag.qubits: self._multigate_opt(dag, qbt) return dag
qiskit/qiskit/transpiler/passes/optimization/hoare_opt.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/optimization/hoare_opt.py", "repo_id": "qiskit", "token_count": 7810 }
205
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Template matching in the forward direction, it takes an initial match, a configuration of qubit and both circuit and template as inputs. The result is a list of match between the template and the circuit. **Reference:** [1] Iten, R., Moyard, R., Metger, T., Sutter, D. and Woerner, S., 2020. Exact and practical pattern matching for quantum circuit optimization. `arXiv:1909.05270 <https://arxiv.org/abs/1909.05270>`_ """ from qiskit.circuit.controlledgate import ControlledGate class ForwardMatch: """ Object to apply template matching in the forward direction. """ def __init__( self, circuit_dag_dep, template_dag_dep, node_id_c, node_id_t, qubits, clbits=None ): """ Create a ForwardMatch class with necessary arguments. Args: circuit_dag_dep (DAGDependency): circuit in the dag dependency form. template_dag_dep (DAGDependency): template in the dag dependency form. node_id_c (int): index of the first gate matched in the circuit. node_id_t (int): index of the first gate matched in the template. qubits (list): list of considered qubits in the circuit. clbits (list): list of considered clbits in the circuit. """ # The dag dependency representation of the circuit self.circuit_dag_dep = circuit_dag_dep.copy() # The dag dependency representation of the template self.template_dag_dep = template_dag_dep.copy() # List of qubit on which the node of the circuit is acting on self.qubits = qubits # List of qubit on which the node of the circuit is acting on self.clbits = clbits if clbits is not None else [] # Id of the node in the circuit self.node_id_c = node_id_c # Id of the node in the template self.node_id_t = node_id_t # List of match self.match = [] # List of candidates for the forward match self.candidates = [] # List of nodes in circuit which are matched self.matched_nodes_list = [] # Transformation of the qarg indices of the circuit to be adapted to the template indices self.qarg_indices = [] # Transformation of the carg indices of the circuit to be adapted to the template indices self.carg_indices = [] def _init_successors_to_visit(self): """ Initialize the attribute list 'SuccessorsToVisit' """ for i in range(0, self.circuit_dag_dep.size()): if i == self.node_id_c: self.circuit_dag_dep.get_node(i).successorstovisit = ( self.circuit_dag_dep.direct_successors(i) ) def _init_matched_with_circuit(self): """ Initialize the attribute 'MatchedWith' in the template DAG dependency. """ for i in range(0, self.circuit_dag_dep.size()): if i == self.node_id_c: self.circuit_dag_dep.get_node(i).matchedwith = [self.node_id_t] else: self.circuit_dag_dep.get_node(i).matchedwith = [] def _init_matched_with_template(self): """ Initialize the attribute 'MatchedWith' in the circuit DAG dependency. """ for i in range(0, self.template_dag_dep.size()): if i == self.node_id_t: self.template_dag_dep.get_node(i).matchedwith = [self.node_id_c] else: self.template_dag_dep.get_node(i).matchedwith = [] def _init_is_blocked_circuit(self): """ Initialize the attribute 'IsBlocked' in the circuit DAG dependency. """ for i in range(0, self.circuit_dag_dep.size()): self.circuit_dag_dep.get_node(i).isblocked = False def _init_is_blocked_template(self): """ Initialize the attribute 'IsBlocked' in the template DAG dependency. """ for i in range(0, self.template_dag_dep.size()): self.template_dag_dep.get_node(i).isblocked = False def _init_list_match(self): """ Initialize the list of matched nodes between the circuit and the template with the first match found. """ self.match.append([self.node_id_t, self.node_id_c]) def _find_forward_candidates(self, node_id_t): """ Find the candidate nodes to be matched in the template for a given node. Args: node_id_t (int): considered node id. """ matches = [] for match in self.match: matches.append(match[0]) pred = matches.copy() if len(pred) > 1: pred.sort() pred.remove(node_id_t) if self.template_dag_dep.direct_successors(node_id_t): maximal_index = self.template_dag_dep.direct_successors(node_id_t)[-1] pred = [elem for elem in pred if elem <= maximal_index] block = [] for node_id in pred: for dir_succ in self.template_dag_dep.direct_successors(node_id): if dir_succ not in matches: succ = self.template_dag_dep.successors(dir_succ) block = block + succ self.candidates = list( set(self.template_dag_dep.direct_successors(node_id_t)) - set(matches) - set(block) ) def _init_matched_nodes(self): """ Initialize the list of current matched nodes. """ self.matched_nodes_list.append( [self.node_id_c, self.circuit_dag_dep.get_node(self.node_id_c)] ) def _get_node_forward(self, list_id): """ Return a node from the matched_node_list for a given list id. Args: list_id (int): considered list id of the desired node. Returns: DAGDepNode: DAGDepNode object corresponding to i-th node of the matched_node_list. """ node = self.matched_nodes_list[list_id][1] return node def _remove_node_forward(self, list_id): """ Remove a node of the current matched list for a given list id. Args: list_id (int): considered list id of the desired node. """ self.matched_nodes_list.pop(list_id) def _update_successor(self, node, successor_id): """ Return a node with an updated attribute 'SuccessorToVisit'. Args: node (DAGDepNode): current node. successor_id (int): successor id to remove. Returns: DAGOpNode or DAGOutNode: Node with updated attribute 'SuccessorToVisit'. """ node_update = node node_update.successorstovisit.pop(successor_id) return node_update def _get_successors_to_visit(self, node, list_id): """ Return the successor for a given node and id. Args: node (DAGOpNode or DAGOutNode): current node. list_id (int): id in the list for the successor to get. Returns: int: id of the successor to get. """ successor_id = node.successorstovisit[list_id] return successor_id def _update_qarg_indices(self, qarg): """ Change qubits indices of the current circuit node in order to be comparable with the indices of the template qubits list. Args: qarg (list): list of qubits indices from the circuit for a given node. """ self.qarg_indices = [] for q in qarg: if q in self.qubits: self.qarg_indices.append(self.qubits.index(q)) if len(qarg) != len(self.qarg_indices): self.qarg_indices = [] def _update_carg_indices(self, carg): """ Change clbits indices of the current circuit node in order to be comparable with the indices of the template qubits list. Args: carg (list): list of clbits indices from the circuit for a given node. """ self.carg_indices = [] if carg: for q in carg: if q in self.clbits: self.carg_indices.append(self.clbits.index(q)) if len(carg) != len(self.carg_indices): self.carg_indices = [] def _is_same_op(self, node_circuit, node_template): """ Check if two instructions are the same. Args: node_circuit (DAGDepNode): node in the circuit. node_template (DAGDepNode): node in the template. Returns: bool: True if the same, False otherwise. """ return node_circuit.op.soft_compare(node_template.op) def _is_same_q_conf(self, node_circuit, node_template): """ Check if the qubits configurations are compatible. Args: node_circuit (DAGDepNode): node in the circuit. node_template (DAGDepNode): node in the template. Returns: bool: True if possible, False otherwise. """ if isinstance(node_circuit.op, ControlledGate): c_template = node_template.op.num_ctrl_qubits if c_template == 1: return self.qarg_indices == node_template.qindices else: control_qubits_template = node_template.qindices[:c_template] control_qubits_circuit = self.qarg_indices[:c_template] if set(control_qubits_circuit) == set(control_qubits_template): target_qubits_template = node_template.qindices[c_template::] target_qubits_circuit = self.qarg_indices[c_template::] if node_template.op.base_gate.name in [ "rxx", "ryy", "rzz", "swap", "iswap", "ms", ]: return set(target_qubits_template) == set(target_qubits_circuit) else: return target_qubits_template == target_qubits_circuit else: return False else: if node_template.op.name in ["rxx", "ryy", "rzz", "swap", "iswap", "ms"]: return set(self.qarg_indices) == set(node_template.qindices) else: return self.qarg_indices == node_template.qindices def _is_same_c_conf(self, node_circuit, node_template): """ Check if the clbits configurations are compatible. Args: node_circuit (DAGDepNode): node in the circuit. node_template (DAGDepNode): node in the template. Returns: bool: True if possible, False otherwise. """ if ( node_circuit.type == "op" and getattr(node_circuit.op, "condition", None) and node_template.type == "op" and getattr(node_template.op, "condition", None) ): if set(self.carg_indices) != set(node_template.cindices): return False if ( getattr(node_circuit.op, "condition", None)[1] != getattr(node_template.op, "condition", None)[1] ): return False return True def run_forward_match(self): """ Apply the forward match algorithm and returns the list of matches given an initial match and a circuit qubits configuration. """ # Initialize the new attributes of the DAGDepNodes of the DAGDependency object self._init_successors_to_visit() self._init_matched_with_circuit() self._init_matched_with_template() self._init_is_blocked_circuit() self._init_is_blocked_template() # Initialize the list of matches and the stack of matched nodes (circuit) self._init_list_match() self._init_matched_nodes() # While the list of matched nodes is not empty while self.matched_nodes_list: # Return first element of the matched_nodes_list and removes it from the list v_first = self._get_node_forward(0) self._remove_node_forward(0) # If there is no successors to visit go to the end if not v_first.successorstovisit: continue # Get the label and the node of the first successor to visit label = self._get_successors_to_visit(v_first, 0) v = [label, self.circuit_dag_dep.get_node(label)] # Update of the SuccessorsToVisit attribute v_first = self._update_successor(v_first, 0) # Update the matched_nodes_list with new attribute successor to visit and sort the list. self.matched_nodes_list.append([v_first.node_id, v_first]) self.matched_nodes_list.sort(key=lambda x: x[1].successorstovisit) # If the node is blocked and already matched go to the end if v[1].isblocked | (v[1].matchedwith != []): continue # Search for potential candidates in the template self._find_forward_candidates(v_first.matchedwith[0]) qarg1 = self.circuit_dag_dep.get_node(label).qindices carg1 = self.circuit_dag_dep.get_node(label).cindices # Update the indices for both qubits and clbits in order to be comparable with the # indices in the template circuit. self._update_qarg_indices(qarg1) self._update_carg_indices(carg1) match = False # For loop over the candidates (template) to find a match. for i in self.candidates: # Break the for loop if a match is found. if match: break # Compare the indices of qubits and the operation, # if True; a match is found node_circuit = self.circuit_dag_dep.get_node(label) node_template = self.template_dag_dep.get_node(i) # Necessary but not sufficient conditions for a match to happen. if ( len(self.qarg_indices) != len(node_template.qindices) or set(self.qarg_indices) != set(node_template.qindices) or node_circuit.name != node_template.name ): continue # Check if the qubit, clbit configuration are compatible for a match, # also check if the operation are the same. if ( self._is_same_q_conf(node_circuit, node_template) and self._is_same_c_conf(node_circuit, node_template) and self._is_same_op(node_circuit, node_template) ): v[1].matchedwith = [i] self.template_dag_dep.get_node(i).matchedwith = [label] # Append the new match to the list of matches. self.match.append([i, label]) # Potential successors to visit (circuit) for a given match. potential = self.circuit_dag_dep.direct_successors(label) # If the potential successors to visit are blocked or match, it is removed. for potential_id in potential: if self.circuit_dag_dep.get_node(potential_id).isblocked | ( self.circuit_dag_dep.get_node(potential_id).matchedwith != [] ): potential.remove(potential_id) sorted_potential = sorted(potential) # Update the successor to visit attribute v[1].successorstovisit = sorted_potential # Add the updated node to the stack. self.matched_nodes_list.append([v[0], v[1]]) self.matched_nodes_list.sort(key=lambda x: x[1].successorstovisit) match = True continue # If no match is found, block the node and all the successors. if not match: v[1].isblocked = True for succ in v[1].successors: self.circuit_dag_dep.get_node(succ).isblocked = True if self.circuit_dag_dep.get_node(succ).matchedwith: self.match.remove( [self.circuit_dag_dep.get_node(succ).matchedwith[0], succ] ) match_id = self.circuit_dag_dep.get_node(succ).matchedwith[0] self.template_dag_dep.get_node(match_id).matchedwith = [] self.circuit_dag_dep.get_node(succ).matchedwith = []
qiskit/qiskit/transpiler/passes/optimization/template_matching/forward_match.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/optimization/template_matching/forward_match.py", "repo_id": "qiskit", "token_count": 8150 }
206
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Map (with minimum effort) a DAGCircuit onto a ``coupling_map`` adding swap gates.""" from __future__ import annotations import numpy as np from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.layout import Layout from qiskit.transpiler.passes.routing.algorithms import ApproximateTokenSwapper from qiskit.transpiler.target import Target class LayoutTransformation(TransformationPass): """Adds a Swap circuit for a given (partial) permutation to the circuit. This circuit is found by a 4-approximation algorithm for Token Swapping. More details are available in the routing code. """ def __init__( self, coupling_map: CouplingMap | Target | None, from_layout: Layout | str, to_layout: Layout | str, seed: int | np.random.Generator | None = None, trials=4, ): """LayoutTransformation initializer. Args: coupling_map: Directed graph representing a coupling map. from_layout (Union[Layout, str]): The starting layout of qubits onto physical qubits. If the type is str, look up `property_set` when this pass runs. to_layout (Union[Layout, str]): The final layout of qubits on physical qubits. If the type is str, look up ``property_set`` when this pass runs. seed (Union[int, np.random.default_rng]): Seed to use for random trials. trials (int): How many randomized trials to perform, taking the best circuit as output. """ super().__init__() self.from_layout = from_layout self.to_layout = to_layout if isinstance(coupling_map, Target): self.target = coupling_map self.coupling_map = self.target.build_coupling_map() else: self.target = None self.coupling_map = coupling_map if self.coupling_map is None: self.coupling_map = CouplingMap.from_full(len(to_layout)) graph = self.coupling_map.graph.to_undirected() self.token_swapper = ApproximateTokenSwapper(graph, seed) self.trials = trials def run(self, dag): """Apply the specified partial permutation to the circuit. Args: dag (DAGCircuit): DAG to transform the layout of. Returns: DAGCircuit: The DAG with transformed layout. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG. Or if either of string from/to_layout is not found in `property_set`. """ if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("LayoutTransform runs on physical circuits only") if len(dag.qubits) > len(self.coupling_map.physical_qubits): raise TranspilerError("The layout does not match the amount of qubits in the DAG") from_layout = self.from_layout if isinstance(from_layout, str): try: from_layout = self.property_set[from_layout] except Exception as ex: raise TranspilerError(f"No {from_layout} (from_layout) in property_set.") from ex to_layout = self.to_layout if isinstance(to_layout, str): try: to_layout = self.property_set[to_layout] except Exception as ex: raise TranspilerError(f"No {to_layout} (to_layout) in property_set.") from ex # Find the permutation between the initial physical qubits and final physical qubits. permutation = { pqubit: to_layout.get_virtual_bits()[vqubit] for vqubit, pqubit in from_layout.get_virtual_bits().items() } perm_circ = self.token_swapper.permutation_circuit(permutation, self.trials) qubits = [dag.qubits[i[0]] for i in sorted(perm_circ.inputmap.items(), key=lambda x: x[0])] dag.compose(perm_circ.circuit, qubits=qubits) return dag
qiskit/qiskit/transpiler/passes/routing/layout_transformation.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/routing/layout_transformation.py", "repo_id": "qiskit", "token_count": 1903 }
207
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A qubit state tracker for synthesizing operations with auxiliary qubits.""" from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass @dataclass class QubitTracker: """Track qubits (by global index) and their state. The states are distinguished into clean (meaning in state :math:`|0\rangle`) or dirty (an unknown state). """ # This could in future be extended to track different state types, if necessary. # However, using sets of integers here is much faster than e.g. storing a dictionary with # {index: state} entries. qubits: tuple[int] clean: set[int] dirty: set[int] def num_clean(self, active_qubits: Iterable[int] | None = None): """Return the number of clean qubits, not considering the active qubits.""" # this could be cached if getting the set length becomes a performance bottleneck return len(self.clean.difference(active_qubits or set())) def num_dirty(self, active_qubits: Iterable[int] | None = None): """Return the number of dirty qubits, not considering the active qubits.""" return len(self.dirty.difference(active_qubits or set())) def borrow(self, num_qubits: int, active_qubits: Iterable[int] | None = None) -> list[int]: """Get ``num_qubits`` qubits, excluding ``active_qubits``.""" active_qubits = set(active_qubits or []) available_qubits = [qubit for qubit in self.qubits if qubit not in active_qubits] if num_qubits > (available := len(available_qubits)): raise RuntimeError(f"Cannot borrow {num_qubits} qubits, only {available} available.") # for now, prioritize returning clean qubits available_clean = [qubit for qubit in available_qubits if qubit in self.clean] available_dirty = [qubit for qubit in available_qubits if qubit in self.dirty] borrowed = available_clean[:num_qubits] return borrowed + available_dirty[: (num_qubits - len(borrowed))] def used(self, qubits: Iterable[int], check: bool = True) -> None: """Set the state of ``qubits`` to used (i.e. False).""" qubits = set(qubits) if check: if len(untracked := qubits.difference(self.qubits)) > 0: raise ValueError(f"Setting state of untracked qubits: {untracked}. Tracker: {self}") self.clean -= qubits self.dirty |= qubits def reset(self, qubits: Iterable[int], check: bool = True) -> None: """Set the state of ``qubits`` to 0 (i.e. True).""" qubits = set(qubits) if check: if len(untracked := qubits.difference(self.qubits)) > 0: raise ValueError(f"Setting state of untracked qubits: {untracked}. Tracker: {self}") self.clean |= qubits self.dirty -= qubits def drop(self, qubits: Iterable[int], check: bool = True) -> None: """Drop qubits from the tracker, meaning that they are no longer available.""" qubits = set(qubits) if check: if len(untracked := qubits.difference(self.qubits)) > 0: raise ValueError(f"Dropping untracked qubits: {untracked}. Tracker: {self}") self.qubits = tuple(qubit for qubit in self.qubits if qubit not in qubits) self.clean -= qubits self.dirty -= qubits def copy( self, qubit_map: dict[int, int] | None = None, drop: Iterable[int] | None = None ) -> "QubitTracker": """Copy self. Args: qubit_map: If provided, apply the mapping ``{old_qubit: new_qubit}`` to the qubits in the tracker. Only those old qubits in the mapping will be part of the new one. drop: If provided, drop these qubits in the copied tracker. This argument is ignored if ``qubit_map`` is given, since the qubits can then just be dropped in the map. """ if qubit_map is None and drop is not None: remaining_qubits = [qubit for qubit in self.qubits if qubit not in drop] qubit_map = dict(zip(remaining_qubits, remaining_qubits)) if qubit_map is None: clean = self.clean.copy() dirty = self.dirty.copy() qubits = self.qubits # tuple is immutable, no need to copy else: clean, dirty = set(), set() for old_index, new_index in qubit_map.items(): if old_index in self.clean: clean.add(new_index) elif old_index in self.dirty: dirty.add(new_index) else: raise ValueError(f"Unknown old qubit index: {old_index}. Tracker: {self}") qubits = tuple(qubit_map.values()) return QubitTracker(qubits, clean=clean, dirty=dirty) def __str__(self) -> str: return ( f"QubitTracker({len(self.qubits)}, clean: {self.num_clean()}, dirty: {self.num_dirty()})" + f"\n\tclean: {self.clean}" + f"\n\tdirty: {self.dirty}" )
qiskit/qiskit/transpiler/passes/synthesis/qubit_tracker.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/synthesis/qubit_tracker.py", "repo_id": "qiskit", "token_count": 2225 }
208
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Return a circuit with any adjacent barriers merged together.""" from qiskit.transpiler.basepasses import TransformationPass from qiskit.circuit.barrier import Barrier class MergeAdjacentBarriers(TransformationPass): """Return a circuit with any adjacent barriers merged together. Only barriers which can be merged without affecting the barrier structure of the DAG will be merged. Not all redundant barriers will necessarily be merged, only adjacent barriers are merged. For example, the circuit:: qr = QuantumRegister(3, 'q') circuit = QuantumCircuit(qr) circuit.barrier(qr[0]) circuit.barrier(qr[1]) circuit.barrier(qr) Will be transformed into a circuit corresponding to:: circuit.barrier(qr[0]) circuit.barrier(qr) i.e, .. parsed-literal:: ░ ░ ░ ░ q_0: ─░──░─ q_0: ─░──░─ ░ ░ ░ ░ q_1: ─░──░─ => q_1: ────░─ ░ ░ ░ q_2: ────░─ q_2: ────░─ ░ after one iteration of the pass. These two barriers were not merged by the first pass as they are not adjacent in the initial circuit. The pass then can be reapplied to merge the newly adjacent barriers. """ def run(self, dag): """Run the MergeAdjacentBarriers pass on `dag`.""" indices = {qubit: index for index, qubit in enumerate(dag.qubits)} # sorted to so that they are in the order they appear in the DAG # so ancestors/descendants makes sense barriers = [nd for nd in dag.topological_op_nodes() if nd.name == "barrier"] # get dict of barrier merges node_to_barrier_qubits = MergeAdjacentBarriers._collect_potential_merges(dag, barriers) if not node_to_barrier_qubits: return dag for barrier in barriers: if barrier in node_to_barrier_qubits: barrier_to_add, nodes = node_to_barrier_qubits[barrier] dag.replace_block_with_op( nodes, barrier_to_add, wire_pos_map=indices, cycle_check=False ) return dag @staticmethod def _collect_potential_merges(dag, barriers): """Return the potential merges. Returns a dict of DAGOpNode: (Barrier, [DAGOpNode]) objects, where the barrier needs to be inserted where the corresponding index DAGOpNode appears in the main DAG, in replacement of the listed DAGOpNodes. """ # if only got 1 or 0 barriers then can't merge if len(barriers) < 2: return None # mapping from the node that will be the main barrier to the # barrier object that gets built up node_to_barrier_qubits = {} # Start from the first barrier current_barrier = barriers[0] end_of_barrier = current_barrier current_barrier_nodes = [current_barrier] current_qubits = set(current_barrier.qargs) current_ancestors = dag.ancestors(current_barrier) current_descendants = dag.descendants(current_barrier) barrier_to_add = Barrier(len(current_qubits)) for next_barrier in barriers[1:]: # Ensure barriers are adjacent before checking if they are mergeable. if dag._has_edge(end_of_barrier._node_id, next_barrier._node_id): # Remove all barriers that have already been included in this new barrier from the # set of ancestors/descendants as they will be removed from the new DAG when it is # created. next_ancestors = { nd for nd in dag.ancestors(next_barrier) if nd not in current_barrier_nodes } next_descendants = { nd for nd in dag.descendants(next_barrier) if nd not in current_barrier_nodes } next_qubits = set(next_barrier.qargs) if ( not current_qubits.isdisjoint(next_qubits) and current_ancestors.isdisjoint(next_descendants) and current_descendants.isdisjoint(next_ancestors) ): # can be merged current_ancestors = current_ancestors | next_ancestors current_descendants = current_descendants | next_descendants current_qubits = current_qubits | next_qubits # update the barrier that will be added back to include this barrier barrier_to_add = Barrier(len(current_qubits)) end_of_barrier = next_barrier current_barrier_nodes.append(end_of_barrier) continue # Fallback if barriers are not adjacent or not mergeable. # store the previously made barrier if barrier_to_add: node_to_barrier_qubits[end_of_barrier] = (barrier_to_add, current_barrier_nodes) # reset the properties current_qubits = set(next_barrier.qargs) current_ancestors = dag.ancestors(next_barrier) current_descendants = dag.descendants(next_barrier) barrier_to_add = Barrier(len(current_qubits)) current_barrier_nodes = [] end_of_barrier = next_barrier current_barrier_nodes.append(end_of_barrier) if barrier_to_add: node_to_barrier_qubits[end_of_barrier] = (barrier_to_add, current_barrier_nodes) return node_to_barrier_qubits
qiskit/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/utils/merge_adjacent_barriers.py", "repo_id": "qiskit", "token_count": 2694 }
209
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=too-many-return-statements """ A target object represents the minimum set of information the transpiler needs from a backend """ from __future__ import annotations import itertools import warnings from typing import Optional, List, Any from collections.abc import Mapping import datetime import io import logging import inspect import rustworkx as rx # import target class from the rust side from qiskit._accelerate.target import ( BaseTarget, BaseInstructionProperties, ) from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterValueType from qiskit.circuit.gate import Gate from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.pulse.calibration_entries import CalibrationEntry, ScheduleDef from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.timing_constraints import TimingConstraints from qiskit.providers.exceptions import BackendPropertyError from qiskit.pulse.exceptions import PulseError, UnassignedDurationError from qiskit.exceptions import QiskitError # import QubitProperties here to provide convenience alias for building a # full target from qiskit.providers.backend import QubitProperties # pylint: disable=unused-import from qiskit.providers.models.backendproperties import BackendProperties from qiskit.utils import deprecate_func logger = logging.getLogger(__name__) class InstructionProperties(BaseInstructionProperties): """A representation of the properties of a gate implementation. This class provides the optional properties that a backend can provide about an instruction. These represent the set that the transpiler can currently work with if present. However, if your backend provides additional properties for instructions you should subclass this to add additional custom attributes for those custom/additional properties by the backend. """ __slots__ = [ "_calibration", ] def __new__( # pylint: disable=keyword-arg-before-vararg cls, duration=None, # pylint: disable=keyword-arg-before-vararg error=None, # pylint: disable=keyword-arg-before-vararg *args, # pylint: disable=unused-argument **kwargs, # pylint: disable=unused-argument ): return super(InstructionProperties, cls).__new__( # pylint: disable=too-many-function-args cls, duration, error ) def __init__( self, duration: float | None = None, # pylint: disable=unused-argument error: float | None = None, # pylint: disable=unused-argument calibration: Schedule | ScheduleBlock | CalibrationEntry | None = None, ): """Create a new ``InstructionProperties`` object Args: duration: The duration, in seconds, of the instruction on the specified set of qubits error: The average error rate for the instruction on the specified set of qubits. calibration: The pulse representation of the instruction. """ super().__init__() self._calibration: CalibrationEntry | None = None self.calibration = calibration @property def calibration(self): """The pulse representation of the instruction. .. note:: This attribute always returns a Qiskit pulse program, but it is internally wrapped by the :class:`.CalibrationEntry` to manage unbound parameters and to uniformly handle different data representation, for example, un-parsed Pulse Qobj JSON that a backend provider may provide. This value can be overridden through the property setter in following manner. When you set either :class:`.Schedule` or :class:`.ScheduleBlock` this is always treated as a user-defined (custom) calibration and the transpiler may automatically attach the calibration data to the output circuit. This calibration data may appear in the wire format as an inline calibration, which may further update the backend standard instruction set architecture. If you are a backend provider who provides a default calibration data that is not needed to be attached to the transpiled quantum circuit, you can directly set :class:`.CalibrationEntry` instance to this attribute, in which you should set :code:`user_provided=False` when you define calibration data for the entry. End users can still intentionally utilize the calibration data, for example, to run pulse-level simulation of the circuit. However, such entry doesn't appear in the wire format, and backend must use own definition to compile the circuit down to the execution format. """ if self._calibration is None: return None return self._calibration.get_schedule() @calibration.setter def calibration(self, calibration: Schedule | ScheduleBlock | CalibrationEntry): if isinstance(calibration, (Schedule, ScheduleBlock)): new_entry = ScheduleDef() new_entry.define(calibration, user_provided=True) else: new_entry = calibration self._calibration = new_entry def __repr__(self): return ( f"InstructionProperties(duration={self.duration}, error={self.error}" f", calibration={self._calibration})" ) def __getstate__(self) -> tuple: return (super().__getstate__(), self.calibration, self._calibration) def __setstate__(self, state: tuple): super().__setstate__(state[0]) self.calibration = state[1] self._calibration = state[2] class Target(BaseTarget): """ The intent of the ``Target`` object is to inform Qiskit's compiler about the constraints of a particular backend so the compiler can compile an input circuit to something that works and is optimized for a device. It currently contains a description of instructions on a backend and their properties as well as some timing information. However, this exact interface may evolve over time as the needs of the compiler change. These changes will be done in a backwards compatible and controlled manner when they are made (either through versioning, subclassing, or mixins) to add on to the set of information exposed by a target. As a basic example, let's assume backend has two qubits, supports :class:`~qiskit.circuit.library.UGate` on both qubits and :class:`~qiskit.circuit.library.CXGate` in both directions. To model this you would create the target like:: from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, CXGate from qiskit.circuit import Parameter gmap = Target() theta = Parameter('theta') phi = Parameter('phi') lam = Parameter('lambda') u_props = { (0,): InstructionProperties(duration=5.23e-8, error=0.00038115), (1,): InstructionProperties(duration=4.52e-8, error=0.00032115), } gmap.add_instruction(UGate(theta, phi, lam), u_props) cx_props = { (0,1): InstructionProperties(duration=5.23e-7, error=0.00098115), (1,0): InstructionProperties(duration=4.52e-7, error=0.00132115), } gmap.add_instruction(CXGate(), cx_props) Each instruction in the ``Target`` is indexed by a unique string name that uniquely identifies that instance of an :class:`~qiskit.circuit.Instruction` object in the Target. There is a 1:1 mapping between a name and an :class:`~qiskit.circuit.Instruction` instance in the target and each name must be unique. By default, the name is the :attr:`~qiskit.circuit.Instruction.name` attribute of the instruction, but can be set to anything. This lets a single target have multiple instances of the same instruction class with different parameters. For example, if a backend target has two instances of an :class:`~qiskit.circuit.library.RXGate` one is parameterized over any theta while the other is tuned up for a theta of pi/6 you can add these by doing something like:: import math from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import RXGate from qiskit.circuit import Parameter target = Target() theta = Parameter('theta') rx_props = { (0,): InstructionProperties(duration=5.23e-8, error=0.00038115), } target.add_instruction(RXGate(theta), rx_props) rx_30_props = { (0,): InstructionProperties(duration=1.74e-6, error=.00012) } target.add_instruction(RXGate(math.pi / 6), rx_30_props, name='rx_30') Then in the ``target`` object accessing by ``rx_30`` will get the fixed angle :class:`~qiskit.circuit.library.RXGate` while ``rx`` will get the parameterized :class:`~qiskit.circuit.library.RXGate`. .. note:: This class assumes that qubit indices start at 0 and are a contiguous set if you want a submapping the bits will need to be reindexed in a new``Target`` object. .. note:: This class only supports additions of gates, qargs, and qubits. If you need to remove one of these the best option is to iterate over an existing object and create a new subset (or use one of the methods to do this). The object internally caches different views and these would potentially be invalidated by removals. """ __slots__ = ( "_gate_map", "_coupling_graph", "_instruction_durations", "_instruction_schedule_map", ) def __new__( # pylint: disable=keyword-arg-before-vararg cls, description: str | None = None, num_qubits: int = 0, dt: float | None = None, granularity: int = 1, min_length: int = 1, pulse_alignment: int = 1, acquire_alignment: int = 1, qubit_properties: list | None = None, concurrent_measurements: list | None = None, *args, # pylint: disable=unused-argument disable=keyword-arg-before-vararg **kwargs, # pylint: disable=unused-argument ): """ Create a new ``Target`` object Args: description (str): An optional string to describe the Target. num_qubits (int): An optional int to specify the number of qubits the backend target has. If not set it will be implicitly set based on the qargs when :meth:`~qiskit.Target.add_instruction` is called. Note this must be set if the backend target is for a noiseless simulator that doesn't have constraints on the instructions so the transpiler knows how many qubits are available. dt (float): The system time resolution of input signals in seconds granularity (int): An integer value representing minimum pulse gate resolution in units of ``dt``. A user-defined pulse gate should have duration of a multiple of this granularity value. min_length (int): An integer value representing minimum pulse gate length in units of ``dt``. A user-defined pulse gate should be longer than this length. pulse_alignment (int): An integer value representing a time resolution of gate instruction starting time. Gate instruction should start at time which is a multiple of the alignment value. acquire_alignment (int): An integer value representing a time resolution of measure instruction starting time. Measure instruction should start at time which is a multiple of the alignment value. qubit_properties (list): A list of :class:`~.QubitProperties` objects defining the characteristics of each qubit on the target device. If specified the length of this list must match the number of qubits in the target, where the index in the list matches the qubit number the properties are defined for. If some qubits don't have properties available you can set that entry to ``None`` concurrent_measurements(list): A list of sets of qubits that must be measured together. This must be provided as a nested list like ``[[0, 1], [2, 3, 4]]``. Raises: ValueError: If both ``num_qubits`` and ``qubit_properties`` are both defined and the value of ``num_qubits`` differs from the length of ``qubit_properties``. """ if description is not None: description = str(description) return super(Target, cls).__new__( # pylint: disable=too-many-function-args cls, description, num_qubits, dt, granularity, min_length, pulse_alignment, acquire_alignment, qubit_properties, concurrent_measurements, ) def __init__( self, description=None, # pylint: disable=unused-argument num_qubits=0, # pylint: disable=unused-argument dt=None, # pylint: disable=unused-argument granularity=1, # pylint: disable=unused-argument min_length=1, # pylint: disable=unused-argument pulse_alignment=1, # pylint: disable=unused-argument acquire_alignment=1, # pylint: disable=unused-argument qubit_properties=None, # pylint: disable=unused-argument concurrent_measurements=None, # pylint: disable=unused-argument ): # A nested mapping of gate name -> qargs -> properties self._gate_map = {} self._coupling_graph = None self._instruction_durations = None self._instruction_schedule_map = None def add_instruction(self, instruction, properties=None, name=None): """Add a new instruction to the :class:`~qiskit.transpiler.Target` As ``Target`` objects are strictly additive this is the primary method for modifying a ``Target``. Typically, you will use this to fully populate a ``Target`` before using it in :class:`~qiskit.providers.BackendV2`. For example:: from qiskit.circuit.library import CXGate from qiskit.transpiler import Target, InstructionProperties target = Target() cx_properties = { (0, 1): None, (1, 0): None, (0, 2): None, (2, 0): None, (0, 3): None, (2, 3): None, (3, 0): None, (3, 2): None } target.add_instruction(CXGate(), cx_properties) Will add a :class:`~qiskit.circuit.library.CXGate` to the target with no properties (duration, error, etc) with the coupling edge list: ``(0, 1), (1, 0), (0, 2), (2, 0), (0, 3), (2, 3), (3, 0), (3, 2)``. If there are properties available for the instruction you can replace the ``None`` value in the properties dictionary with an :class:`~qiskit.transpiler.InstructionProperties` object. This pattern is repeated for each :class:`~qiskit.circuit.Instruction` the target supports. Args: instruction (Union[qiskit.circuit.Instruction, Type[qiskit.circuit.Instruction]]): The operation object to add to the map. If it's parameterized any value of the parameter can be set. Optionally for variable width instructions (such as control flow operations such as :class:`~.ForLoop` or :class:`~MCXGate`) you can specify the class. If the class is specified than the ``name`` argument must be specified. When a class is used the gate is treated as global and not having any properties set. properties (dict): A dictionary of qarg entries to an :class:`~qiskit.transpiler.InstructionProperties` object for that instruction implementation on the backend. Properties are optional for any instruction implementation, if there are no :class:`~qiskit.transpiler.InstructionProperties` available for the backend the value can be None. If there are no constraints on the instruction (as in a noiseless/ideal simulation) this can be set to ``{None, None}`` which will indicate it runs on all qubits (or all available permutations of qubits for multi-qubit gates). The first ``None`` indicates it applies to all qubits and the second ``None`` indicates there are no :class:`~qiskit.transpiler.InstructionProperties` for the instruction. By default, if properties is not set it is equivalent to passing ``{None: None}``. name (str): An optional name to use for identifying the instruction. If not specified the :attr:`~qiskit.circuit.Instruction.name` attribute of ``gate`` will be used. All gates in the ``Target`` need unique names. Backends can differentiate between different parameterization of a single gate by providing a unique name for each (e.g. `"rx30"`, `"rx60", ``"rx90"`` similar to the example in the documentation for the :class:`~qiskit.transpiler.Target` class). Raises: AttributeError: If gate is already in map TranspilerError: If an operation class is passed in for ``instruction`` and no name is specified or ``properties`` is set. """ is_class = inspect.isclass(instruction) if not is_class: instruction_name = name or instruction.name else: # Invalid to have class input without a name with characters set "" is not a valid name if not name: raise TranspilerError( "A name must be specified when defining a supported global operation by class" ) if properties is not None: raise TranspilerError( "An instruction added globally by class can't have properties set." ) instruction_name = name if properties is None or is_class: properties = {None: None} if instruction_name in self._gate_map: raise AttributeError(f"Instruction {instruction_name} is already in the target") super().add_instruction(instruction, instruction_name, properties) self._gate_map[instruction_name] = properties self._coupling_graph = None self._instruction_durations = None self._instruction_schedule_map = None def update_instruction_properties(self, instruction, qargs, properties): """Update the property object for an instruction qarg pair already in the Target Args: instruction (str): The instruction name to update qargs (tuple): The qargs to update the properties of properties (InstructionProperties): The properties to set for this instruction Raises: KeyError: If ``instruction`` or ``qarg`` are not in the target """ super().update_instruction_properties(instruction, qargs, properties) self._gate_map[instruction][qargs] = properties self._instruction_durations = None self._instruction_schedule_map = None def update_from_instruction_schedule_map(self, inst_map, inst_name_map=None, error_dict=None): """Update the target from an instruction schedule map. If the input instruction schedule map contains new instructions not in the target they will be added. However, if it contains additional qargs for an existing instruction in the target it will error. Args: inst_map (InstructionScheduleMap): The instruction inst_name_map (dict): An optional dictionary that maps any instruction name in ``inst_map`` to an instruction object. If not provided, instruction is pulled from the standard Qiskit gates, and finally custom gate instance is created with schedule name. error_dict (dict): A dictionary of errors of the form:: {gate_name: {qarg: error}} for example:: {'rx': {(0, ): 1.4e-4, (1, ): 1.2e-4}} For each entry in the ``inst_map`` if ``error_dict`` is defined a when updating the ``Target`` the error value will be pulled from this dictionary. If one is not found in ``error_dict`` then ``None`` will be used. """ get_calibration = getattr(inst_map, "_get_calibration_entry") # Expand name mapping with custom gate name provided by user. qiskit_inst_name_map = get_standard_gate_name_mapping() if inst_name_map is not None: qiskit_inst_name_map.update(inst_name_map) for inst_name in inst_map.instructions: # Prepare dictionary of instruction properties out_props = {} for qargs in inst_map.qubits_with_instruction(inst_name): try: qargs = tuple(qargs) except TypeError: qargs = (qargs,) try: props = self._gate_map[inst_name][qargs] except (KeyError, TypeError): props = None entry = get_calibration(inst_name, qargs) if entry.user_provided and getattr(props, "_calibration", None) != entry: # It only copies user-provided calibration from the inst map. # Backend defined entry must already exist in Target. if self.dt is not None: try: duration = entry.get_schedule().duration * self.dt except UnassignedDurationError: # duration of schedule is parameterized duration = None else: duration = None props = InstructionProperties( duration=duration, calibration=entry, ) else: if props is None: # Edge case. Calibration is backend defined, but this is not # registered in the backend target. Ignore this entry. continue try: # Update gate error if provided. props.error = error_dict[inst_name][qargs] except (KeyError, TypeError): pass out_props[qargs] = props if not out_props: continue # Prepare Qiskit Gate object assigned to the entries if inst_name not in self._gate_map: # Entry not found: Add new instruction if inst_name in qiskit_inst_name_map: # Remove qargs with length that doesn't match with instruction qubit number inst_obj = qiskit_inst_name_map[inst_name] normalized_props = {} for qargs, prop in out_props.items(): if len(qargs) != inst_obj.num_qubits: continue normalized_props[qargs] = prop self.add_instruction(inst_obj, normalized_props, name=inst_name) else: # Check qubit length parameter name uniformity. qlen = set() param_names = set() for qargs in inst_map.qubits_with_instruction(inst_name): if isinstance(qargs, int): qargs = (qargs,) qlen.add(len(qargs)) cal = getattr(out_props[tuple(qargs)], "_calibration") param_names.add(tuple(cal.get_signature().parameters.keys())) if len(qlen) > 1 or len(param_names) > 1: raise QiskitError( f"Schedules for {inst_name} are defined non-uniformly for " f"multiple qubit lengths {qlen}, " f"or different parameter names {param_names}. " "Provide these schedules with inst_name_map or define them with " "different names for different gate parameters." ) inst_obj = Gate( name=inst_name, num_qubits=next(iter(qlen)), params=list(map(Parameter, next(iter(param_names)))), ) self.add_instruction(inst_obj, out_props, name=inst_name) else: # Entry found: Update "existing" instructions. for qargs, prop in out_props.items(): if qargs not in self._gate_map[inst_name]: continue self.update_instruction_properties(inst_name, qargs, prop) def qargs_for_operation_name(self, operation): """Get the qargs for a given operation name Args: operation (str): The operation name to get qargs for Returns: set: The set of qargs the gate instance applies to. """ if None in self._gate_map[operation]: return None return self._gate_map[operation].keys() def durations(self): """Get an InstructionDurations object from the target Returns: InstructionDurations: The instruction duration represented in the target """ if self._instruction_durations is not None: return self._instruction_durations out_durations = [] for instruction, props_map in self._gate_map.items(): for qarg, properties in props_map.items(): if properties is not None and properties.duration is not None: out_durations.append((instruction, list(qarg), properties.duration, "s")) self._instruction_durations = InstructionDurations(out_durations, dt=self.dt) return self._instruction_durations def timing_constraints(self): """Get an :class:`~qiskit.transpiler.TimingConstraints` object from the target Returns: TimingConstraints: The timing constraints represented in the ``Target`` """ return TimingConstraints( self.granularity, self.min_length, self.pulse_alignment, self.acquire_alignment ) def instruction_schedule_map(self): """Return an :class:`~qiskit.pulse.InstructionScheduleMap` for the instructions in the target with a pulse schedule defined. Returns: InstructionScheduleMap: The instruction schedule map for the instructions in this target with a pulse schedule defined. """ if self._instruction_schedule_map is not None: return self._instruction_schedule_map out_inst_schedule_map = InstructionScheduleMap() for instruction, qargs in self._gate_map.items(): for qarg, properties in qargs.items(): # Directly getting CalibrationEntry not to invoke .get_schedule(). # This keeps PulseQobjDef un-parsed. cal_entry = getattr(properties, "_calibration", None) if cal_entry is not None: # Use fast-path to add entries to the inst map. out_inst_schedule_map._add(instruction, qarg, cal_entry) self._instruction_schedule_map = out_inst_schedule_map return out_inst_schedule_map def has_calibration( self, operation_name: str, qargs: tuple[int, ...], ) -> bool: """Return whether the instruction (operation + qubits) defines a calibration. Args: operation_name: The name of the operation for the instruction. qargs: The tuple of qubit indices for the instruction. Returns: Returns ``True`` if the calibration is supported and ``False`` if it isn't. """ qargs = tuple(qargs) if operation_name not in self._gate_map: return False if qargs not in self._gate_map[operation_name]: return False return getattr(self._gate_map[operation_name][qargs], "_calibration", None) is not None def get_calibration( self, operation_name: str, qargs: tuple[int, ...], *args: ParameterValueType, **kwargs: ParameterValueType, ) -> Schedule | ScheduleBlock: """Get calibrated pulse schedule for the instruction. If calibration is templated with parameters, one can also provide those values to build a schedule with assigned parameters. Args: operation_name: The name of the operation for the instruction. qargs: The tuple of qubit indices for the instruction. args: Parameter values to build schedule if any. kwargs: Parameter values with name to build schedule if any. Returns: Calibrated pulse schedule of corresponding instruction. """ if not self.has_calibration(operation_name, qargs): raise KeyError( f"Calibration of instruction {operation_name} for qubit {qargs} is not defined." ) cal_entry = getattr(self._gate_map[operation_name][qargs], "_calibration") return cal_entry.get_schedule(*args, **kwargs) @property def operation_names(self): """Get the operation names in the target.""" return self._gate_map.keys() @property def instructions(self): """Get the list of tuples ``(:class:`~qiskit.circuit.Instruction`, (qargs))`` for the target For globally defined variable width operations the tuple will be of the form ``(class, None)`` where class is the actual operation class that is globally defined. """ return [ (self._gate_name_map[op], qarg) for op, qargs in self._gate_map.items() for qarg in qargs ] def instruction_properties(self, index): """Get the instruction properties for a specific instruction tuple This method is to be used in conjunction with the :attr:`~qiskit.transpiler.Target.instructions` attribute of a :class:`~qiskit.transpiler.Target` object. You can use this method to quickly get the instruction properties for an element of :attr:`~qiskit.transpiler.Target.instructions` by using the index in that list. However, if you're not working with :attr:`~qiskit.transpiler.Target.instructions` directly it is likely more efficient to access the target directly via the name and qubits to get the instruction properties. For example, if :attr:`~qiskit.transpiler.Target.instructions` returned:: [(XGate(), (0,)), (XGate(), (1,))] you could get the properties of the ``XGate`` on qubit 1 with:: props = target.instruction_properties(1) but just accessing it directly via the name would be more efficient:: props = target['x'][(1,)] (assuming the ``XGate``'s canonical name in the target is ``'x'``) This is especially true for larger targets as this will scale worse with the number of instruction tuples in a target. Args: index (int): The index of the instruction tuple from the :attr:`~qiskit.transpiler.Target.instructions` attribute. For, example if you want the properties from the third element in :attr:`~qiskit.transpiler.Target.instructions` you would set this to be ``2``. Returns: InstructionProperties: The instruction properties for the specified instruction tuple """ instruction_properties = [ inst_props for qargs in self._gate_map.values() for inst_props in qargs.values() ] return instruction_properties[index] def _build_coupling_graph(self): self._coupling_graph = rx.PyDiGraph(multigraph=False) if self.num_qubits is not None: self._coupling_graph.add_nodes_from([{} for _ in range(self.num_qubits)]) for gate, qarg_map in self._gate_map.items(): if qarg_map is None: if self._gate_name_map[gate].num_qubits == 2: self._coupling_graph = None # pylint: disable=attribute-defined-outside-init return continue for qarg, properties in qarg_map.items(): if qarg is None: if self.operation_from_name(gate).num_qubits == 2: self._coupling_graph = None return continue if len(qarg) == 1: self._coupling_graph[qarg[0]] = ( properties # pylint: disable=attribute-defined-outside-init ) elif len(qarg) == 2: try: edge_data = self._coupling_graph.get_edge_data(*qarg) edge_data[gate] = properties except rx.NoEdgeBetweenNodes: self._coupling_graph.add_edge(*qarg, {gate: properties}) qargs = self.qargs if self._coupling_graph.num_edges() == 0 and ( qargs is None or any(x is None for x in qargs) ): self._coupling_graph = None # pylint: disable=attribute-defined-outside-init def build_coupling_map(self, two_q_gate=None, filter_idle_qubits=False): """Get a :class:`~qiskit.transpiler.CouplingMap` from this target. If there is a mix of two qubit operations that have a connectivity constraint and those that are globally defined this will also return ``None`` because the globally connectivity means there is no constraint on the target. If you wish to see the constraints of the two qubit operations that have constraints you should use the ``two_q_gate`` argument to limit the output to the gates which have a constraint. Args: two_q_gate (str): An optional gate name for a two qubit gate in the ``Target`` to generate the coupling map for. If specified the output coupling map will only have edges between qubits where this gate is present. filter_idle_qubits (bool): If set to ``True`` the output :class:`~.CouplingMap` will remove any qubits that don't have any operations defined in the target. Note that using this argument will result in an output :class:`~.CouplingMap` object which has holes in its indices which might differ from the assumptions of the class. The typical use case of this argument is to be paired with :meth:`.CouplingMap.connected_components` which will handle the holes as expected. Returns: CouplingMap: The :class:`~qiskit.transpiler.CouplingMap` object for this target. If there are no connectivity constraints in the target this will return ``None``. Raises: ValueError: If a non-two qubit gate is passed in for ``two_q_gate``. IndexError: If an Instruction not in the ``Target`` is passed in for ``two_q_gate``. """ if self.qargs is None: return None if None not in self.qargs and any(len(x) > 2 for x in self.qargs): logger.warning( "This Target object contains multiqubit gates that " "operate on > 2 qubits. This will not be reflected in " "the output coupling map." ) if two_q_gate is not None: coupling_graph = rx.PyDiGraph(multigraph=False) coupling_graph.add_nodes_from([None] * self.num_qubits) for qargs, properties in self[two_q_gate].items(): if len(qargs) != 2: raise ValueError( f"Specified two_q_gate: {two_q_gate} is not a 2 qubit instruction" ) coupling_graph.add_edge(*qargs, {two_q_gate: properties}) cmap = CouplingMap() cmap.graph = coupling_graph return cmap if self._coupling_graph is None: self._build_coupling_graph() # if there is no connectivity constraints in the coupling graph treat it as not # existing and return if self._coupling_graph is not None: cmap = CouplingMap() if filter_idle_qubits: cmap.graph = self._filter_coupling_graph() else: cmap.graph = self._coupling_graph.copy() return cmap else: return None def _filter_coupling_graph(self): has_operations = set(itertools.chain.from_iterable(x for x in self.qargs if x is not None)) graph = self._coupling_graph.copy() to_remove = set(graph.node_indices()).difference(has_operations) if to_remove: graph.remove_nodes_from(list(to_remove)) return graph def __iter__(self): return iter(self._gate_map) def __getitem__(self, key): return self._gate_map[key] def get(self, key, default=None): """Gets an item from the Target. If not found return a provided default or `None`.""" try: return self[key] except KeyError: return default def __len__(self): return len(self._gate_map) def __contains__(self, item): return item in self._gate_map def keys(self): """Return the keys (operation_names) of the Target""" return self._gate_map.keys() def values(self): """Return the Property Map (qargs -> InstructionProperties) of every instruction in the Target""" return self._gate_map.values() def items(self): """Returns pairs of Gate names and its property map (str, dict[tuple, InstructionProperties])""" return self._gate_map.items() def __str__(self): output = io.StringIO() if self.description is not None: output.write(f"Target: {self.description}\n") else: output.write("Target\n") output.write(f"Number of qubits: {self.num_qubits}\n") output.write("Instructions:\n") for inst, qarg_props in self._gate_map.items(): output.write(f"\t{inst}\n") for qarg, props in qarg_props.items(): if qarg is None: continue if props is None: output.write(f"\t\t{qarg}\n") continue prop_str_pieces = [f"\t\t{qarg}:\n"] duration = getattr(props, "duration", None) if duration is not None: prop_str_pieces.append(f"\t\t\tDuration: {duration:g} sec.\n") error = getattr(props, "error", None) if error is not None: prop_str_pieces.append(f"\t\t\tError Rate: {error:g}\n") schedule = getattr(props, "_calibration", None) if schedule is not None: prop_str_pieces.append("\t\t\tWith pulse schedule calibration\n") extra_props = getattr(props, "properties", None) if extra_props is not None: extra_props_pieces = [ f"\t\t\t\t{key}: {value}\n" for key, value in extra_props.items() ] extra_props_str = "".join(extra_props_pieces) prop_str_pieces.append(f"\t\t\tExtra properties:\n{extra_props_str}\n") output.write("".join(prop_str_pieces)) return output.getvalue() def __getstate__(self) -> dict: return { "_gate_map": self._gate_map, "coupling_graph": self._coupling_graph, "instruction_durations": self._instruction_durations, "instruction_schedule_map": self._instruction_schedule_map, "base": super().__getstate__(), } def __setstate__(self, state: tuple): self._gate_map = state["_gate_map"] self._coupling_graph = state["coupling_graph"] self._instruction_durations = state["instruction_durations"] self._instruction_schedule_map = state["instruction_schedule_map"] super().__setstate__(state["base"]) @classmethod def from_configuration( cls, basis_gates: list[str], num_qubits: int | None = None, coupling_map: CouplingMap | None = None, inst_map: InstructionScheduleMap | None = None, backend_properties: BackendProperties | None = None, instruction_durations: InstructionDurations | None = None, concurrent_measurements: Optional[List[List[int]]] = None, dt: float | None = None, timing_constraints: TimingConstraints | None = None, custom_name_mapping: dict[str, Any] | None = None, ) -> Target: """Create a target object from the individual global configuration Prior to the creation of the :class:`~.Target` class, the constraints of a backend were represented by a collection of different objects which combined represent a subset of the information contained in the :class:`~.Target`. This function provides a simple interface to convert those separate objects to a :class:`~.Target`. This constructor will use the input from ``basis_gates``, ``num_qubits``, and ``coupling_map`` to build a base model of the backend and the ``instruction_durations``, ``backend_properties``, and ``inst_map`` inputs are then queried (in that order) based on that model to look up the properties of each instruction and qubit. If there is an inconsistency between the inputs any extra or conflicting information present in ``instruction_durations``, ``backend_properties``, or ``inst_map`` will be ignored. Args: basis_gates: The list of basis gate names for the backend. For the target to be created these names must either be in the output from :func:`~.get_standard_gate_name_mapping` or present in the specified ``custom_name_mapping`` argument. num_qubits: The number of qubits supported on the backend. coupling_map: The coupling map representing connectivity constraints on the backend. If specified all gates from ``basis_gates`` will be supported on all qubits (or pairs of qubits). inst_map: The instruction schedule map representing the pulse :class:`~.Schedule` definitions for each instruction. If this is specified ``coupling_map`` must be specified. The ``coupling_map`` is used as the source of truth for connectivity and if ``inst_map`` is used the schedule is looked up based on the instructions from the pair of ``basis_gates`` and ``coupling_map``. If you want to define a custom gate for a particular qubit or qubit pair, you can manually build :class:`.Target`. backend_properties: The :class:`~.BackendProperties` object which is used for instruction properties and qubit properties. If specified and instruction properties are intended to be used then the ``coupling_map`` argument must be specified. This is only used to lookup error rates and durations (unless ``instruction_durations`` is specified which would take precedence) for instructions specified via ``coupling_map`` and ``basis_gates``. instruction_durations: Optional instruction durations for instructions. If specified it will take priority for setting the ``duration`` field in the :class:`~InstructionProperties` objects for the instructions in the target. concurrent_measurements(list): A list of sets of qubits that must be measured together. This must be provided as a nested list like ``[[0, 1], [2, 3, 4]]``. dt: The system time resolution of input signals in seconds timing_constraints: Optional timing constraints to include in the :class:`~.Target` custom_name_mapping: An optional dictionary that maps custom gate/operation names in ``basis_gates`` to an :class:`~.Operation` object representing that gate/operation. By default, most standard gates names are mapped to the standard gate object from :mod:`qiskit.circuit.library` this only needs to be specified if the input ``basis_gates`` defines gates in names outside that set. Returns: Target: the target built from the input configuration Raises: TranspilerError: If the input basis gates contain > 2 qubits and ``coupling_map`` is specified. KeyError: If no mapping is available for a specified ``basis_gate``. """ granularity = 1 min_length = 1 pulse_alignment = 1 acquire_alignment = 1 if timing_constraints is not None: granularity = timing_constraints.granularity min_length = timing_constraints.min_length pulse_alignment = timing_constraints.pulse_alignment acquire_alignment = timing_constraints.acquire_alignment qubit_properties = None if backend_properties is not None: # pylint: disable=cyclic-import from qiskit.providers.backend_compat import qubit_props_list_from_props qubit_properties = qubit_props_list_from_props(properties=backend_properties) target = cls( num_qubits=num_qubits, dt=dt, granularity=granularity, min_length=min_length, pulse_alignment=pulse_alignment, acquire_alignment=acquire_alignment, qubit_properties=qubit_properties, concurrent_measurements=concurrent_measurements, ) name_mapping = get_standard_gate_name_mapping() if custom_name_mapping is not None: name_mapping.update(custom_name_mapping) # While BackendProperties can also contain coupling information we # rely solely on CouplingMap to determine connectivity. This is because # in legacy transpiler usage (and implicitly in the BackendV1 data model) # the coupling map is used to define connectivity constraints and # the properties is only used for error rate and duration population. # If coupling map is not specified we ignore the backend_properties if coupling_map is None: for gate in basis_gates: if gate not in name_mapping: raise KeyError( f"The specified basis gate: {gate} is not present in the standard gate " "names or a provided custom_name_mapping" ) target.add_instruction(name_mapping[gate], name=gate) else: one_qubit_gates = [] two_qubit_gates = [] global_ideal_variable_width_gates = [] # pylint: disable=invalid-name if num_qubits is None: num_qubits = len(coupling_map.graph) for gate in basis_gates: if gate not in name_mapping: raise KeyError( f"The specified basis gate: {gate} is not present in the standard gate " "names or a provided custom_name_mapping" ) gate_obj = name_mapping[gate] if gate_obj.num_qubits == 1: one_qubit_gates.append(gate) elif gate_obj.num_qubits == 2: two_qubit_gates.append(gate) elif inspect.isclass(gate_obj): global_ideal_variable_width_gates.append(gate) else: raise TranspilerError( f"The specified basis gate: {gate} has {gate_obj.num_qubits} " "qubits. This constructor method only supports fixed width operations " "with <= 2 qubits (because connectivity is defined on a CouplingMap)." ) for gate in one_qubit_gates: gate_properties: dict[tuple, InstructionProperties] = {} for qubit in range(num_qubits): error = None duration = None calibration = None if backend_properties is not None: if duration is None: try: duration = backend_properties.gate_length(gate, qubit) except BackendPropertyError: duration = None try: error = backend_properties.gate_error(gate, qubit) except BackendPropertyError: error = None if inst_map is not None: try: calibration = inst_map._get_calibration_entry(gate, qubit) # If we have dt defined and there is a custom calibration which is user # generate use that custom pulse schedule for the duration. If it is # not user generated than we assume it's the same duration as what is # defined in the backend properties if dt and calibration.user_provided: duration = calibration.get_schedule().duration * dt except PulseError: calibration = None # Durations if specified manually should override model objects if instruction_durations is not None: try: duration = instruction_durations.get(gate, qubit, unit="s") except TranspilerError: duration = None if error is None and duration is None and calibration is None: gate_properties[(qubit,)] = None else: gate_properties[(qubit,)] = InstructionProperties( duration=duration, error=error, calibration=calibration ) target.add_instruction(name_mapping[gate], properties=gate_properties, name=gate) edges = list(coupling_map.get_edges()) for gate in two_qubit_gates: gate_properties = {} for edge in edges: error = None duration = None calibration = None if backend_properties is not None: if duration is None: try: duration = backend_properties.gate_length(gate, edge) except BackendPropertyError: duration = None try: error = backend_properties.gate_error(gate, edge) except BackendPropertyError: error = None if inst_map is not None: try: calibration = inst_map._get_calibration_entry(gate, edge) # If we have dt defined and there is a custom calibration which is user # generate use that custom pulse schedule for the duration. If it is # not user generated than we assume it's the same duration as what is # defined in the backend properties if dt and calibration.user_provided: duration = calibration.get_schedule().duration * dt except PulseError: calibration = None # Durations if specified manually should override model objects if instruction_durations is not None: try: duration = instruction_durations.get(gate, edge, unit="s") except TranspilerError: duration = None if error is None and duration is None and calibration is None: gate_properties[edge] = None else: gate_properties[edge] = InstructionProperties( duration=duration, error=error, calibration=calibration ) target.add_instruction(name_mapping[gate], properties=gate_properties, name=gate) for gate in global_ideal_variable_width_gates: target.add_instruction(name_mapping[gate], name=gate) return target Mapping.register(Target) @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", additional_msg="This method is used to build an element from the deprecated " "``qiskit.providers.models`` module. These models are part of the deprecated `BackendV1` " "workflow and no longer necessary for `BackendV2`. If a user workflow requires these " "representations it likely relies on deprecated functionality and " "should be updated to use `BackendV2`.", ) def target_to_backend_properties(target: Target): """Convert a :class:`~.Target` object into a legacy :class:`~.BackendProperties`""" properties_dict: dict[str, Any] = { "backend_name": "", "backend_version": "", "last_update_date": None, "general": [], } gates = [] qubits = [] for gate, qargs_list in target.items(): if gate != "measure": for qargs, props in qargs_list.items(): property_list = [] if getattr(props, "duration", None) is not None: property_list.append( { "date": datetime.datetime.now(datetime.timezone.utc), "name": "gate_length", "unit": "s", "value": props.duration, } ) if getattr(props, "error", None) is not None: property_list.append( { "date": datetime.datetime.now(datetime.timezone.utc), "name": "gate_error", "unit": "", "value": props.error, } ) if property_list: gates.append( { "gate": gate, "qubits": list(qargs), "parameters": property_list, "name": gate + "_".join([str(x) for x in qargs]), } ) else: qubit_props: dict[int, Any] = {} if target.num_qubits is not None: qubit_props = {x: None for x in range(target.num_qubits)} for qargs, props in qargs_list.items(): if qargs is None: continue qubit = qargs[0] props_list = [] if getattr(props, "error", None) is not None: props_list.append( { "date": datetime.datetime.now(datetime.timezone.utc), "name": "readout_error", "unit": "", "value": props.error, } ) if getattr(props, "duration", None) is not None: props_list.append( { "date": datetime.datetime.now(datetime.timezone.utc), "name": "readout_length", "unit": "s", "value": props.duration, } ) if not props_list: qubit_props = {} break qubit_props[qubit] = props_list if qubit_props and all(x is not None for x in qubit_props.values()): qubits = [qubit_props[i] for i in range(target.num_qubits)] if gates or qubits: properties_dict["gates"] = gates properties_dict["qubits"] = qubits with warnings.catch_warnings(): # This raises BackendProperties internally warnings.filterwarnings("ignore", category=DeprecationWarning) return BackendProperties.from_dict(properties_dict) else: return None
qiskit/qiskit/transpiler/target.py/0
{ "file_path": "qiskit/qiskit/transpiler/target.py", "repo_id": "qiskit", "token_count": 26524 }
210
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Common circuit visualization utilities.""" import re from collections import OrderedDict from warnings import warn import numpy as np from qiskit.circuit import ( ClassicalRegister, Clbit, ControlFlowOp, ControlledGate, Delay, Gate, Instruction, Measure, QuantumCircuit, Qubit, ) from qiskit.circuit.annotated_operation import AnnotatedOperation, InverseModifier, PowerModifier from qiskit.circuit.controlflow import condition_resources from qiskit.circuit.library import PauliEvolutionGate from qiskit.circuit.tools import pi_check from qiskit.converters import circuit_to_dag from qiskit.utils import optionals as _optionals from ..exceptions import VisualizationError def _is_boolean_expression(gate_text, op): if not _optionals.HAS_TWEEDLEDUM: return False from qiskit.circuit.classicalfunction import BooleanExpression return isinstance(op, BooleanExpression) and gate_text == op.name def get_gate_ctrl_text(op, drawer, style=None, calibrations=None): """Load the gate_text and ctrl_text strings based on names and labels""" anno_list = [] anno_text = "" if isinstance(op, AnnotatedOperation) and op.modifiers: for modifier in op.modifiers: if isinstance(modifier, InverseModifier): anno_list.append("Inv") elif isinstance(modifier, PowerModifier): anno_list.append("Pow(" + str(round(modifier.power, 1)) + ")") anno_text = ", ".join(anno_list) op_label = getattr(op, "label", None) op_type = type(op) base_name = base_label = base_type = None if hasattr(op, "base_gate"): base_name = op.base_gate.name base_label = op.base_gate.label base_type = type(op.base_gate) if hasattr(op, "base_op"): base_name = op.base_op.name ctrl_text = None if base_label: gate_text = base_label ctrl_text = op_label elif op_label and isinstance(op, ControlledGate): gate_text = base_name ctrl_text = op_label elif op_label: gate_text = op_label elif base_name: gate_text = base_name else: gate_text = op.name # raw_gate_text is used in color selection in mpl instead of op.name, since # if it's a controlled gate, the color will likely not be the base_name color raw_gate_text = op.name if gate_text == base_name else gate_text # For mpl and latex drawers, check style['disptex'] in qcstyle.py if drawer != "text" and gate_text in style["disptex"]: # First check if this entry is in the old style disptex that # included "$\\mathrm{ }$". If so, take it as is. if style["disptex"][gate_text][0] == "$" and style["disptex"][gate_text][-1] == "$": gate_text = style["disptex"][gate_text] else: gate_text = f"$\\mathrm{{{style['disptex'][gate_text]}}}$" elif drawer == "latex": # Special formatting for Booleans in latex (due to '~' causing crash) if _is_boolean_expression(gate_text, op): gate_text = gate_text.replace("~", "$\\neg$").replace("&", "\\&") gate_text = f"$\\texttt{{{gate_text}}}$" # Capitalize if not a user-created gate or instruction elif ( (gate_text == op.name and op_type not in (Gate, Instruction)) or (gate_text == base_name and base_type not in (Gate, Instruction)) ) and (op_type is not PauliEvolutionGate): gate_text = f"$\\mathrm{{{gate_text.capitalize()}}}$" else: gate_text = f"$\\mathrm{{{gate_text}}}$" # Remove mathmode _, ^, and - formatting from user names and labels gate_text = gate_text.replace("_", "\\_") gate_text = gate_text.replace("^", "\\string^") gate_text = gate_text.replace("-", "\\mbox{-}") ctrl_text = f"$\\mathrm{{{ctrl_text}}}$" # Only capitalize internally-created gate or instruction names elif ( (gate_text == op.name and op_type not in (Gate, Instruction)) or (gate_text == base_name and base_type not in (Gate, Instruction)) ) and (op_type is not PauliEvolutionGate): gate_text = gate_text.capitalize() if drawer == "mpl" and op.name in calibrations: if isinstance(op, ControlledGate): ctrl_text = "" if ctrl_text is None else ctrl_text ctrl_text = "(cal)\n" + ctrl_text else: gate_text = gate_text + "\n(cal)" if anno_text: gate_text += " - " + anno_text return gate_text, ctrl_text, raw_gate_text def get_param_str(op, drawer, ndigits=3): """Get the params as a string to add to the gate text display""" if ( not hasattr(op, "params") or any(isinstance(param, np.ndarray) for param in op.params) or any(isinstance(param, QuantumCircuit) for param in op.params) ): return "" if isinstance(op, Delay): param_list = [f"{op.params[0]}[{op.unit}]"] else: param_list = [] for count, param in enumerate(op.params): # Latex drawer will cause an xy-pic error and mpl drawer will overwrite # the right edge if param string too long, so limit params. if (drawer == "latex" and count > 3) or (drawer == "mpl" and count > 15): param_list.append("...") break try: param_list.append(pi_check(param, output=drawer, ndigits=ndigits)) except TypeError: param_list.append(str(param)) param_str = "" if param_list: if drawer == "latex": param_str = f"\\,(\\mathrm{{{','.join(param_list)}}})" elif drawer == "mpl": param_str = f"{', '.join(param_list)}".replace("-", "$-$") else: param_str = f"({','.join(param_list)})" return param_str def get_wire_map(circuit, bits, cregbundle): """Map the bits and registers to the index from the top of the drawing. The key to the dict is either the (Qubit, Clbit) or if cregbundle True, the register that is being bundled. Args: circuit (QuantumCircuit): the circuit being drawn bits (list(Qubit, Clbit)): the Qubit's and Clbit's in the circuit cregbundle (bool): if True bundle classical registers. Default: ``True``. Returns: dict((Qubit, Clbit, ClassicalRegister): index): map of bits/registers to index """ prev_reg = None wire_index = 0 wire_map = {} for bit in bits: register = get_bit_register(circuit, bit) if register is None or not isinstance(bit, Clbit) or not cregbundle: wire_map[bit] = wire_index wire_index += 1 elif register is not None and cregbundle and register != prev_reg: prev_reg = register wire_map[register] = wire_index wire_index += 1 return wire_map def get_bit_register(circuit, bit): """Get the register for a bit if there is one Args: circuit (QuantumCircuit): the circuit being drawn bit (Qubit, Clbit): the bit to use to find the register and indexes Returns: ClassicalRegister: register associated with the bit """ bit_loc = circuit.find_bit(bit) return bit_loc.registers[0][0] if bit_loc.registers else None def get_bit_reg_index(circuit, bit): """Get the register for a bit if there is one, and the index of the bit from the top of the circuit, or the index of the bit within a register. Args: circuit (QuantumCircuit): the circuit being drawn bit (Qubit, Clbit): the bit to use to find the register and indexes Returns: (ClassicalRegister, None): register associated with the bit int: index of the bit from the top of the circuit int: index of the bit within the register, if there is a register """ bit_loc = circuit.find_bit(bit) bit_index = bit_loc.index register, reg_index = bit_loc.registers[0] if bit_loc.registers else (None, None) return register, bit_index, reg_index def get_wire_label(drawer, register, index, layout=None, cregbundle=True): """Get the bit labels to display to the left of the wires. Args: drawer (str): which drawer is calling ("text", "mpl", or "latex") register (QuantumRegister or ClassicalRegister): get wire_label for this register index (int): index of bit in register layout (Layout): Optional. mapping of virtual to physical bits cregbundle (bool): Optional. if set True bundle classical registers. Default: ``True``. Returns: str: label to display for the register/index """ index_str = f"{index}" if drawer == "text" else f"{{{index}}}" if register is None: wire_label = index_str return wire_label if drawer == "text": reg_name = f"{register.name}" reg_name_index = f"{register.name}_{index}" else: reg_name = f"{{{fix_special_characters(register.name)}}}" reg_name_index = f"{reg_name}_{{{index}}}" # Clbits if isinstance(register, ClassicalRegister): if cregbundle and drawer != "latex": wire_label = f"{register.name}" return wire_label if register.size == 1 or cregbundle: wire_label = reg_name else: wire_label = reg_name_index return wire_label # Qubits if register.size == 1: wire_label = reg_name elif layout is None: wire_label = reg_name_index elif layout[index]: virt_bit = layout[index] try: virt_reg = next(reg for reg in layout.get_registers() if virt_bit in reg) if drawer == "text": wire_label = f"{virt_reg.name}_{virt_reg[:].index(virt_bit)} -> {index}" else: wire_label = ( f"{{{virt_reg.name}}}_{{{virt_reg[:].index(virt_bit)}}} \\mapsto {{{index}}}" ) except StopIteration: if drawer == "text": wire_label = f"{virt_bit} -> {index}" else: wire_label = f"{{{virt_bit}}} \\mapsto {{{index}}}" if drawer != "text": wire_label = wire_label.replace(" ", "\\;") # use wider spaces else: wire_label = index_str return wire_label def get_condition_label_val(condition, circuit, cregbundle): """Get the label and value list to display a condition Args: condition (Union[Clbit, ClassicalRegister], int): classical condition circuit (QuantumCircuit): the circuit that is being drawn cregbundle (bool): if set True bundle classical registers Returns: str: label to display for the condition list(str): list of 1's and 0's indicating values of condition """ cond_is_bit = bool(isinstance(condition[0], Clbit)) cond_val = int(condition[1]) # if condition on a register, return list of 1's and 0's indicating # closed or open, else only one element is returned if isinstance(condition[0], ClassicalRegister) and not cregbundle: val_bits = list(f"{cond_val:0{condition[0].size}b}")[::-1] else: val_bits = list(str(cond_val)) label = "" if cond_is_bit and cregbundle: register, _, reg_index = get_bit_reg_index(circuit, condition[0]) if register is not None: label = f"{register.name}_{reg_index}={hex(cond_val)}" elif not cond_is_bit: label = hex(cond_val) return label, val_bits def fix_special_characters(label): """ Convert any special characters for mpl and latex drawers. Currently only checks for multiple underscores in register names and uses wider space for mpl and latex drawers. Args: label (str): the label to fix Returns: str: label to display """ label = label.replace("_", r"\_").replace(" ", "\\;") return label @_optionals.HAS_PYLATEX.require_in_call("the latex and latex_source circuit drawers") def generate_latex_label(label): """Convert a label to a valid latex string.""" from pylatexenc.latexencode import utf8tolatex regex = re.compile(r"(?<!\\)\$(.*)(?<!\\)\$") match = regex.search(label) if not match: label = label.replace(r"\$", "$") final_str = utf8tolatex(label, non_ascii_only=True) else: mathmode_string = match.group(1).replace(r"\$", "$") before_match = label[: match.start()] before_match = before_match.replace(r"\$", "$") after_match = label[match.end() :] after_match = after_match.replace(r"\$", "$") final_str = ( utf8tolatex(before_match, non_ascii_only=True) + mathmode_string + utf8tolatex(after_match, non_ascii_only=True) ) return final_str.replace(" ", "\\,") # Put in proper spaces def _get_valid_justify_arg(justify): """Returns a valid `justify` argument, warning if necessary.""" if isinstance(justify, str): justify = justify.lower() if justify is None: justify = "left" if justify not in ("left", "right", "none"): # This code should be changed to an error raise, once the deprecation is complete. warn( f"Setting QuantumCircuit.draw()’s or circuit_drawer()'s justify argument: {justify}, to a " "value other than 'left', 'right', 'none' or None (='left'). Default 'left' will be used. " "Support for invalid justify arguments is deprecated as of Qiskit 1.2.0. Starting no " "earlier than 3 months after the release date, invalid arguments will error.", DeprecationWarning, 2, ) justify = "left" return justify def _get_layered_instructions( circuit, reverse_bits=False, justify=None, idle_wires=True, wire_order=None, wire_map=None ): """ Given a circuit, return a tuple (qubits, clbits, nodes) where qubits and clbits are the quantum and classical registers in order (based on reverse_bits or wire_order) and nodes is a list of DAGOpNodes. Args: circuit (QuantumCircuit): From where the information is extracted. reverse_bits (bool): If true the order of the bits in the registers is reversed. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. If an invalid value is provided, default `left` will be used. idle_wires (bool): Include idle wires. Default is True. wire_order (list): A list of ints that modifies the order of the bits. Returns: Tuple(list,list,list): To be consumed by the visualizer directly. Raises: VisualizationError: if both reverse_bits and wire_order are entered. """ justify = _get_valid_justify_arg(justify) if wire_map is not None: qubits = [bit for bit in wire_map if isinstance(bit, Qubit)] else: qubits = circuit.qubits.copy() clbits = circuit.clbits.copy() nodes = [] # Create a mapping of each register to the max layer number for all measure ops # with that register as the target. Then when an op with condition is seen, # it will be placed to the right of the measure op if the register matches. measure_map = OrderedDict([(c, -1) for c in clbits]) if reverse_bits and wire_order is not None: raise VisualizationError("Cannot set both reverse_bits and wire_order in the same drawing.") if reverse_bits: qubits.reverse() clbits.reverse() elif wire_order is not None: new_qubits = [] new_clbits = [] for bit in wire_order: if bit < len(qubits): new_qubits.append(qubits[bit]) else: new_clbits.append(clbits[bit - len(qubits)]) qubits = new_qubits clbits = new_clbits dag = circuit_to_dag(circuit) if justify == "none": for node in dag.topological_op_nodes(): nodes.append([node]) else: nodes = _LayerSpooler(dag, qubits, clbits, justify, measure_map) # Optionally remove all idle wires and instructions that are on them and # on them only. if not idle_wires: for wire in dag.idle_wires(ignore=["barrier", "delay"]): if wire in qubits: qubits.remove(wire) if wire in clbits: clbits.remove(wire) nodes = [[node for node in layer if any(q in qubits for q in node.qargs)] for layer in nodes] return qubits, clbits, nodes def _sorted_nodes(dag_layer): """Convert DAG layer into list of nodes sorted by node_id qiskit-terra #2802 """ nodes = dag_layer["graph"].op_nodes() # sort into the order they were input nodes.sort(key=lambda nd: nd._node_id) return nodes def _get_gate_span(qubits, node): """Get the list of qubits drawing this gate would cover qiskit-terra #2802 """ min_index = len(qubits) max_index = 0 for qreg in node.qargs: index = qubits.index(qreg) if index < min_index: min_index = index if index > max_index: max_index = index # Because of wrapping boxes for mpl control flow ops, this # type of op must be the only op in the layer if isinstance(node.op, ControlFlowOp): span = qubits elif node.cargs or getattr(node.op, "condition", None): span = qubits[min_index : len(qubits)] else: span = qubits[min_index : max_index + 1] return span def _any_crossover(qubits, node, nodes): """Return True .IFF. 'node' crosses over any 'nodes'.""" return bool( set(_get_gate_span(qubits, node)).intersection( bit for check_node in nodes for bit in _get_gate_span(qubits, check_node) ) ) _GLOBAL_NID = 0 class _LayerSpooler(list): """Manipulate list of layer dicts for _get_layered_instructions.""" def __init__(self, dag, qubits, clbits, justification, measure_map): """Create spool""" super().__init__() self.dag = dag self.qubits = qubits self.clbits = clbits self.justification = justification self.measure_map = measure_map self.cregs = [self.dag.cregs[reg] for reg in self.dag.cregs] if self.justification == "left": for dag_layer in dag.layers(): current_index = len(self) - 1 dag_nodes = _sorted_nodes(dag_layer) for node in dag_nodes: self.add(node, current_index) else: dag_layers = [] for dag_layer in dag.layers(): dag_layers.append(dag_layer) # going right to left! dag_layers.reverse() for dag_layer in dag_layers: current_index = 0 dag_nodes = _sorted_nodes(dag_layer) for node in dag_nodes: self.add(node, current_index) def is_found_in(self, node, nodes): """Is any qreq in node found in any of nodes?""" all_qargs = [] for a_node in nodes: for qarg in a_node.qargs: all_qargs.append(qarg) return any(i in node.qargs for i in all_qargs) def insertable(self, node, nodes): """True .IFF. we can add 'node' to layer 'nodes'""" return not _any_crossover(self.qubits, node, nodes) def slide_from_left(self, node, index): """Insert node into first layer where there is no conflict going l > r""" measure_layer = None if isinstance(node.op, Measure): measure_bit = next(bit for bit in self.measure_map if node.cargs[0] == bit) if not self: inserted = True self.append([node]) else: inserted = False curr_index = index last_insertable_index = -1 index_stop = -1 if (condition := getattr(node.op, "condition", None)) is not None: index_stop = max( (self.measure_map[bit] for bit in condition_resources(condition).clbits), default=index_stop, ) if node.cargs: for carg in node.cargs: try: carg_bit = next(bit for bit in self.measure_map if carg == bit) if self.measure_map[carg_bit] > index_stop: index_stop = self.measure_map[carg_bit] except StopIteration: pass while curr_index > index_stop: if self.is_found_in(node, self[curr_index]): break if self.insertable(node, self[curr_index]): last_insertable_index = curr_index curr_index = curr_index - 1 if last_insertable_index >= 0: inserted = True self[last_insertable_index].append(node) measure_layer = last_insertable_index else: inserted = False curr_index = index while curr_index < len(self): if self.insertable(node, self[curr_index]): self[curr_index].append(node) measure_layer = curr_index inserted = True break curr_index = curr_index + 1 if not inserted: self.append([node]) if isinstance(node.op, Measure): if not measure_layer: measure_layer = len(self) - 1 if measure_layer > self.measure_map[measure_bit]: self.measure_map[measure_bit] = measure_layer def slide_from_right(self, node, index): """Insert node into rightmost layer as long there is no conflict.""" if not self: self.insert(0, [node]) inserted = True else: inserted = False curr_index = index last_insertable_index = None while curr_index < len(self): if self.is_found_in(node, self[curr_index]): break if self.insertable(node, self[curr_index]): last_insertable_index = curr_index curr_index = curr_index + 1 if last_insertable_index: self[last_insertable_index].append(node) inserted = True else: curr_index = index while curr_index > -1: if self.insertable(node, self[curr_index]): self[curr_index].append(node) inserted = True break curr_index = curr_index - 1 if not inserted: self.insert(0, [node]) def add(self, node, index): """Add 'node' where it belongs, starting the try at 'index'.""" # Before we add the node, we set its node ID to be globally unique # within this spooler. This is necessary because nodes may span # layers (which are separate DAGs), and thus can falsely compare # as equal if their contents and node IDs happen to be the same. # This is particularly important for the matplotlib drawer, which # keys several of its internal data structures with these nodes. global _GLOBAL_NID # pylint: disable=global-statement node._node_id = _GLOBAL_NID _GLOBAL_NID += 1 if self.justification == "left": self.slide_from_left(node, index) else: self.slide_from_right(node, index)
qiskit/qiskit/visualization/circuit/_utils.py/0
{ "file_path": "qiskit/qiskit/visualization/circuit/_utils.py", "repo_id": "qiskit", "token_count": 10644 }
211
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module for visualizing device coupling maps""" import math from typing import List import numpy as np import rustworkx as rx from rustworkx.visualization import graphviz_draw from qiskit.exceptions import QiskitError from qiskit.utils import optionals as _optionals from qiskit.providers.exceptions import BackendPropertyError from qiskit.transpiler.coupling import CouplingMap from .exceptions import VisualizationError def _get_backend_interface_version(backend): backend_interface_version = getattr(backend, "version", None) return backend_interface_version @_optionals.HAS_MATPLOTLIB.require_in_call def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="white", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (Backend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. qubit_coordinates (Sequence): An optional sequence input (list or array being the most common) of 2d coordinates for each qubit. The length of the sequence much match the number of qubits on the backend. The sequence should be the planar coordinates in a 0-based square grid where each qubit is located. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. plot:: :include-source: from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.visualization import plot_gate_map backend = GenericBackendV2(num_qubits=5) plot_gate_map(backend) """ qubit_coordinates_map = {} qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] qubit_coordinates_map[127] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10], [0, 11], [0, 12], [0, 13], [1, 0], [1, 4], [1, 8], [1, 12], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [2, 11], [2, 12], [2, 13], [2, 14], [3, 2], [3, 6], [3, 10], [3, 14], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [4, 11], [4, 12], [4, 13], [4, 14], [5, 0], [5, 4], [5, 8], [5, 12], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [6, 11], [6, 12], [6, 13], [6, 14], [7, 2], [7, 6], [7, 10], [7, 14], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], [8, 11], [8, 12], [8, 13], [8, 14], [9, 0], [9, 4], [9, 8], [9, 12], [10, 0], [10, 1], [10, 2], [10, 3], [10, 4], [10, 5], [10, 6], [10, 7], [10, 8], [10, 9], [10, 10], [10, 11], [10, 12], [10, 13], [10, 14], [11, 2], [11, 6], [11, 10], [11, 14], [12, 1], [12, 2], [12, 3], [12, 4], [12, 5], [12, 6], [12, 7], [12, 8], [12, 9], [12, 10], [12, 11], [12, 12], [12, 13], [12, 14], ] qubit_coordinates_map[433] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10], [0, 11], [0, 12], [0, 13], [0, 14], [0, 15], [0, 16], [0, 17], [0, 18], [0, 19], [0, 20], [0, 21], [0, 22], [0, 23], [0, 24], [0, 25], [1, 0], [1, 4], [1, 8], [1, 12], [1, 16], [1, 20], [1, 24], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [2, 11], [2, 12], [2, 13], [2, 14], [2, 15], [2, 16], [2, 17], [2, 18], [2, 19], [2, 20], [2, 21], [2, 22], [2, 23], [2, 24], [2, 25], [2, 26], [3, 2], [3, 6], [3, 10], [3, 14], [3, 18], [3, 22], [3, 26], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [4, 11], [4, 12], [4, 13], [4, 14], [4, 15], [4, 16], [4, 17], [4, 18], [4, 19], [4, 20], [4, 21], [4, 22], [4, 23], [4, 24], [4, 25], [4, 26], [5, 0], [5, 4], [5, 8], [5, 12], [5, 16], [5, 20], [5, 24], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [6, 11], [6, 12], [6, 13], [6, 14], [6, 15], [6, 16], [6, 17], [6, 18], [6, 19], [6, 20], [6, 21], [6, 22], [6, 23], [6, 24], [6, 25], [6, 26], [7, 2], [7, 6], [7, 10], [7, 14], [7, 18], [7, 22], [7, 26], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], [8, 11], [8, 12], [8, 13], [8, 14], [8, 15], [8, 16], [8, 17], [8, 18], [8, 19], [8, 20], [8, 21], [8, 22], [8, 23], [8, 24], [8, 25], [8, 26], [9, 0], [9, 4], [9, 8], [9, 12], [9, 16], [9, 20], [9, 24], [10, 0], [10, 1], [10, 2], [10, 3], [10, 4], [10, 5], [10, 6], [10, 7], [10, 8], [10, 9], [10, 10], [10, 11], [10, 12], [10, 13], [10, 14], [10, 15], [10, 16], [10, 17], [10, 18], [10, 19], [10, 20], [10, 21], [10, 22], [10, 23], [10, 24], [10, 25], [10, 26], [11, 2], [11, 6], [11, 10], [11, 14], [11, 18], [11, 22], [11, 26], [12, 0], [12, 1], [12, 2], [12, 3], [12, 4], [12, 5], [12, 6], [12, 7], [12, 8], [12, 9], [12, 10], [12, 11], [12, 12], [12, 13], [12, 14], [12, 15], [12, 16], [12, 17], [12, 18], [12, 19], [12, 20], [12, 21], [12, 22], [12, 23], [12, 24], [12, 25], [12, 26], [13, 0], [13, 4], [13, 8], [13, 12], [13, 16], [13, 20], [13, 24], [14, 0], [14, 1], [14, 2], [14, 3], [14, 4], [14, 5], [14, 6], [14, 7], [14, 8], [14, 9], [14, 10], [14, 11], [14, 12], [14, 13], [14, 14], [14, 15], [14, 16], [14, 17], [14, 18], [14, 19], [14, 20], [14, 21], [14, 22], [14, 23], [14, 24], [14, 25], [14, 26], [15, 2], [15, 6], [15, 10], [15, 14], [15, 18], [15, 22], [15, 26], [16, 0], [16, 1], [16, 2], [16, 3], [16, 4], [16, 5], [16, 6], [16, 7], [16, 8], [16, 9], [16, 10], [16, 11], [16, 12], [16, 13], [16, 14], [16, 15], [16, 16], [16, 17], [16, 18], [16, 19], [16, 20], [16, 21], [16, 22], [16, 23], [16, 24], [16, 25], [16, 26], [17, 0], [17, 4], [17, 8], [17, 12], [17, 16], [17, 20], [17, 24], [18, 0], [18, 1], [18, 2], [18, 3], [18, 4], [18, 5], [18, 6], [18, 7], [18, 8], [18, 9], [18, 10], [18, 11], [18, 12], [18, 13], [18, 14], [18, 15], [18, 16], [18, 17], [18, 18], [18, 19], [18, 20], [18, 21], [18, 22], [18, 23], [18, 24], [18, 25], [18, 26], [19, 2], [19, 6], [19, 10], [19, 14], [19, 18], [19, 22], [19, 26], [20, 0], [20, 1], [20, 2], [20, 3], [20, 4], [20, 5], [20, 6], [20, 7], [20, 8], [20, 9], [20, 10], [20, 11], [20, 12], [20, 13], [20, 14], [20, 15], [20, 16], [20, 17], [20, 18], [20, 19], [20, 20], [20, 21], [20, 22], [20, 23], [20, 24], [20, 25], [20, 26], [21, 0], [21, 4], [21, 8], [21, 12], [21, 16], [21, 20], [21, 24], [22, 0], [22, 1], [22, 2], [22, 3], [22, 4], [22, 5], [22, 6], [22, 7], [22, 8], [22, 9], [22, 10], [22, 11], [22, 12], [22, 13], [22, 14], [22, 15], [22, 16], [22, 17], [22, 18], [22, 19], [22, 20], [22, 21], [22, 22], [22, 23], [22, 24], [22, 25], [22, 26], [23, 2], [23, 6], [23, 10], [23, 14], [23, 18], [23, 22], [23, 26], [24, 1], [24, 2], [24, 3], [24, 4], [24, 5], [24, 6], [24, 7], [24, 8], [24, 9], [24, 10], [24, 11], [24, 12], [24, 13], [24, 14], [24, 15], [24, 16], [24, 17], [24, 18], [24, 19], [24, 20], [24, 21], [24, 22], [24, 23], [24, 24], [24, 25], [24, 26], ] backend_version = _get_backend_interface_version(backend) if backend_version <= 1: if backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") config = backend.configuration() num_qubits = config.n_qubits coupling_map = CouplingMap(config.coupling_map) name = backend.name() else: num_qubits = backend.num_qubits coupling_map = backend.coupling_map name = backend.name if qubit_coordinates is None and ("ibm" in name or "fake" in name): qubit_coordinates = qubit_coordinates_map.get(num_qubits, None) if qubit_coordinates: if len(qubit_coordinates) != num_qubits: raise QiskitError( f"The number of specified qubit coordinates {len(qubit_coordinates)} " f"does not match the device number of qubits: {num_qubits}" ) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map.get_edges(), figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) @_optionals.HAS_MATPLOTLIB.require_in_call @_optionals.HAS_GRAPHVIZ.require_in_call def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="white", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: If matplotlib or graphviz is not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. plot:: :include-source: from qiskit.visualization import plot_coupling_map num_qubits = 8 qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] plot_coupling_map(num_qubits, qubit_coordinates, coupling_map) """ import matplotlib.pyplot as plt from .utils import matplotlib_close_if_inline input_axes = False if ax: input_axes = True if qubit_size is None: qubit_size = 30 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if not label_qubits: qubit_labels = [""] * num_qubits # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if num_qubits == 1: graph = rx.PyDiGraph() graph.add_node(0) else: graph = CouplingMap(coupling_map).graph if not plot_directed: line_color_map = dict(zip(graph.edge_list(), line_color)) graph = graph.to_undirected(multigraph=False) line_color = [line_color_map[edge] for edge in graph.edge_list()] for node in graph.node_indices(): graph[node] = node for edge_index in graph.edge_indices(): graph.update_edge_by_index(edge_index, edge_index) # pixel-to-inch conversion px = 1.15 / plt.rcParams["figure.dpi"] if qubit_coordinates: qubit_coordinates = [coordinates[::-1] for coordinates in qubit_coordinates] if font_size is None: max_characters = max(1, max(len(str(x)) for x in qubit_labels)) font_size = max(int(20 / max_characters), 1) def color_node(node): if qubit_coordinates: out_dict = { "label": str(qubit_labels[node]), "color": f'"{qubit_color[node]}"', "fillcolor": f'"{qubit_color[node]}"', "style": "filled", "shape": "circle", "pos": f'"{qubit_coordinates[node][0]},{qubit_coordinates[node][1]}"', "pin": "True", } else: out_dict = { "label": str(qubit_labels[node]), "color": f'"{qubit_color[node]}"', "fillcolor": f'"{qubit_color[node]}"', "style": "filled", "shape": "circle", } out_dict["fontcolor"] = f'"{font_color}"' out_dict["fontsize"] = str(font_size) out_dict["height"] = str(qubit_size * px) out_dict["fixedsize"] = "True" out_dict["fontname"] = '"DejaVu Sans"' return out_dict def color_edge(edge): out_dict = { "color": f'"{line_color[edge]}"', "fillcolor": f'"{line_color[edge]}"', "penwidth": str(line_width), } return out_dict plot = graphviz_draw( graph, method="neato", node_attr_fn=color_node, edge_attr_fn=color_edge, filename=filename, ) if filename: return None if not input_axes: if figsize is None: width, height = plot.size figsize = (width * px, height * px) fig, ax = plt.subplots(figsize=figsize) ax.axis("off") ax.imshow(plot) if not input_axes: matplotlib_close_if_inline(fig) return fig def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (Backend): Target backend. view (str): How to label qubits in the layout. Options: - ``"virtual"``: Label each qubit with the index of the virtual qubit that mapped to it. - ``"physical"``: Label each qubit with the index of the physical qubit that it corresponds to on the device. qubit_coordinates (Sequence): An optional sequence input (list or array being the most common) of 2d coordinates for each qubit. The length of the sequence must match the number of qubits on the backend. The sequence should be the planar coordinates in a 0-based square grid where each qubit is located. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. plot:: :include-source: from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.visualization import plot_circuit_layout ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) backend = GenericBackendV2(num_qubits=5) new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") backend_version = _get_backend_interface_version(backend) if backend_version <= 1: num_qubits = backend.configuration().n_qubits cmap = backend.configuration().coupling_map cmap_len = len(cmap) else: num_qubits = backend.num_qubits cmap = backend.coupling_map cmap_len = cmap.graph.num_edges() qubits = [] qubit_labels = [""] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.initial_layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.initial_layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.initial_layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = str(bit_locations[key]["index"]) elif view == "physical": for key, val in circuit._layout.initial_layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = str(key) else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "black" lcolors = ["#648fff"] * cmap_len for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "black" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig @_optionals.HAS_MATPLOTLIB.require_in_call @_optionals.HAS_SEABORN.require_in_call def plot_error_map(backend, figsize=(15, 12), show_title=True, qubit_coordinates=None): """Plots the error map of a given backend. Args: backend (Backend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. qubit_coordinates (Sequence): An optional sequence input (list or array being the most common) of 2d coordinates for each qubit. The length of the sequence much mast the number of qubits on the backend. The sequence should be the planar coordinates in a 0-based square grid where each qubit is located. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If matplotlib or seaborn is not installed. Example: .. plot:: :include-source: from qiskit.visualization import plot_error_map from qiskit.providers.fake_provider import GenericBackendV2 backend = GenericBackendV2(num_qubits=5) plot_error_map(backend) """ import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker import seaborn as sns from .utils import matplotlib_close_if_inline color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) backend_version = _get_backend_interface_version(backend) if backend_version <= 1: backend_name = backend.name() num_qubits = backend.configuration().n_qubits cmap = backend.configuration().coupling_map props = backend.properties() props_dict = props.to_dict() single_gate_errors = [0] * num_qubits read_err = [0] * num_qubits cx_errors = [] # sx error rates for gate in props_dict["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) if cmap: directed = False if num_qubits < 20: for edge in cmap: if not [edge[1], edge[0]] in cmap: directed = True break for line in cmap: for item in props_dict["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break for qubit in range(num_qubits): try: read_err[qubit] = props.readout_error(qubit) except BackendPropertyError: pass else: backend_name = backend.name num_qubits = backend.num_qubits cmap = backend.coupling_map two_q_error_map = {} single_gate_errors = [0] * num_qubits read_err = [0] * num_qubits cx_errors = [] for gate, prop_dict in backend.target.items(): if prop_dict is None or None in prop_dict: continue for qargs, inst_props in prop_dict.items(): if inst_props is None: continue if gate == "measure": if inst_props.error is not None: read_err[qargs[0]] = inst_props.error elif len(qargs) == 1: if inst_props.error is not None: single_gate_errors[qargs[0]] = max( single_gate_errors[qargs[0]], inst_props.error ) elif len(qargs) == 2: if inst_props.error is not None: two_q_error_map[qargs] = max( two_q_error_map.get(qargs, 0), inst_props.error ) if cmap: directed = False if num_qubits < 20: for edge in cmap: if not [edge[1], edge[0]] in cmap: directed = True break for line in cmap.get_edges(): err = two_q_error_map.get(tuple(line), 0) cx_errors.append(err) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [matplotlib.colors.to_hex(color_map(single_norm(err))) for err in single_gate_errors] directed = False line_colors = [] if cmap: # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [matplotlib.colors.to_hex(color_map(cx_norm(err))) for err in cx_errors] read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, qubit_coordinates=qubit_coordinates, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA" ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels([str(kk) for kk in range(num_left, num_qubits)], fontsize=12) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend_name} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
qiskit/qiskit/visualization/gate_map.py/0
{ "file_path": "qiskit/qiskit/visualization/gate_map.py", "repo_id": "qiskit", "token_count": 20926 }
212
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Special data types. """ from enum import Enum from typing import NamedTuple, List, Union, NewType, Tuple, Dict from qiskit import circuit ScheduledGate = NamedTuple( "ScheduledGate", [ ("t0", int), ("operand", circuit.Gate), ("duration", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int), ], ) ScheduledGate.__doc__ = "A gate instruction with embedded time." ScheduledGate.t0.__doc__ = "Time when the instruction is issued." ScheduledGate.operand.__doc__ = "Gate object associated with the gate." ScheduledGate.duration.__doc__ = "Time duration of the instruction." ScheduledGate.bits.__doc__ = "List of bit associated with the gate." ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source." GateLink = NamedTuple( "GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])] ) GateLink.__doc__ = "Dedicated object to represent a relationship between instructions." GateLink.t0.__doc__ = "A position where the link is placed." GateLink.opname.__doc__ = "Name of gate associated with this link." GateLink.bits.__doc__ = "List of bit associated with the instruction." Barrier = NamedTuple( "Barrier", [("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)], ) Barrier.__doc__ = "Dedicated object to represent a barrier instruction." Barrier.t0.__doc__ = "A position where the barrier is placed." Barrier.bits.__doc__ = "List of bit associated with the instruction." Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source." HorizontalAxis = NamedTuple( "HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)] ) HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis." HorizontalAxis.window.__doc__ = "Left and right edge of graph." HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location." HorizontalAxis.label.__doc__ = "Label of horizontal axis." class BoxType(str, Enum): """Box type. SCHED_GATE: Box that represents occupation time by gate. DELAY: Box associated with delay. TIMELINE: Box that represents time slot of a bit. """ SCHED_GATE = "Box.ScheduledGate" DELAY = "Box.Delay" TIMELINE = "Box.Timeline" class LineType(str, Enum): """Line type. BARRIER: Line that represents barrier instruction. GATE_LINK: Line that represents a link among gates. """ BARRIER = "Line.Barrier" GATE_LINK = "Line.GateLink" class SymbolType(str, Enum): """Symbol type. FRAME: Symbol that represents zero time frame change (Rz) instruction. """ FRAME = "Symbol.Frame" class LabelType(str, Enum): """Label type. GATE_NAME: Label that represents name of gate. DELAY: Label associated with delay. GATE_PARAM: Label that represents parameter of gate. BIT_NAME: Label that represents name of bit. """ GATE_NAME = "Label.Gate.Name" DELAY = "Label.Delay" GATE_PARAM = "Label.Gate.Param" BIT_NAME = "Label.Bit.Name" class AbstractCoordinate(Enum): """Abstract coordinate that the exact value depends on the user preference. RIGHT: The horizontal coordinate at t0 shifted by the left margin. LEFT: The horizontal coordinate at tf shifted by the right margin. TOP: The vertical coordinate at the top of the canvas. BOTTOM: The vertical coordinate at the bottom of the canvas. """ RIGHT = "RIGHT" LEFT = "LEFT" TOP = "TOP" BOTTOM = "BOTTOM" class Plotter(str, Enum): """Name of timeline plotter APIs. MPL: Matplotlib plotter interface. Show timeline in 2D canvas. """ MPL = "mpl" # convenient type to represent union of drawing data DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType]) # convenient type to represent union of values to represent a coordinate Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate]) # Valid bit objects Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
qiskit/qiskit/visualization/timeline/types.py/0
{ "file_path": "qiskit/qiskit/visualization/timeline/types.py", "repo_id": "qiskit", "token_count": 1525 }
213
--- other: - | ``matplotlib.figure.Figure`` objects returned by visualization functions are no longer always closed by default. Instead the returned figure objects are only closed if the configured matplotlib backend is an inline jupyter backend(either set with ``%matplotlib inline`` or ``%matplotlib notebook``). Output figure objects are still closed with these backends to avoid duplicate outputs in jupyter notebooks (which is why the ``Figure.close()`` were originally added).
qiskit/releasenotes/notes/0.10/matplotlib-close-306c5a9ea2d118bf.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.10/matplotlib-close-306c5a9ea2d118bf.yaml", "repo_id": "qiskit", "token_count": 137 }
214
--- features: - | Add ``ControlledGate`` class for representing controlled gates. Controlled gate instances are created with the ``control(n)`` method of ``Gate`` objects where ``n`` represents the number of controls. The control qubits come before the controlled qubits in the new gate. For example:: from qiskit import QuantumCircuit from qiskit.extensions import HGate hgate = HGate() circ = QuantumCircuit(4) circ.append(hgate.control(3), [0, 1, 2, 3]) print(circ) generates:: q_0: |0>──■── │ q_1: |0>──■── │ q_2: |0>──■── ┌─┴─┐ q_3: |0>┤ H ├ └───┘
qiskit/releasenotes/notes/0.11/add_ControlledGate_class-010c5c90f8f95e78.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.11/add_ControlledGate_class-010c5c90f8f95e78.yaml", "repo_id": "qiskit", "token_count": 337 }
215
--- features: - | PassManagers can now be sliced to create a new Passmanager containing a subset of passes using the square bracket operator. This allow running or drawing a portion of the Passmanager for easier testing and visualization. For example let's try to draw the first 3 passes of a PassManager pm, or run just the second pass on our circuit: .. code-block:: python pm[0:4].draw() circuit2 = pm[1].run(circuit) Also now, PassManagers can be created by adding two PassManagers or by directly adding a pass/list of passes to a PassManager. .. code-block:: python pm = pm1[0] + pm2[1:3] pm += [setLayout, unroller]
qiskit/releasenotes/notes/0.11/passmanager_slicing-57ad2824b43ed75a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.11/passmanager_slicing-57ad2824b43ed75a.yaml", "repo_id": "qiskit", "token_count": 223 }
216
--- features: - | A new method :meth:`qiskit.transpiler.CouplingMap.draw` was added to :class:`qiskit.transpiler.CouplingMap` to generate a graphviz images from the coupling map graph. For example: .. code-block:: from qiskit.transpiler import CouplingMap coupling_map = CouplingMap( [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]) coupling_map.draw()
qiskit/releasenotes/notes/0.12/add-couplingmap-draw-45b8750065719e2c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.12/add-couplingmap-draw-45b8750065719e2c.yaml", "repo_id": "qiskit", "token_count": 193 }
217
--- features: - | Added a new abstract method :meth:`qiskit.quantum_info.Operator.dot` to the abstract ``BaseOperator`` class, so it is included for all implementations of that abstract class, including :class:`qiskit.quantum_info.Operator` and ``QuantumChannel`` (e.g., :class:`qiskit.quantum_info.Choi`) objects. This method returns the right operator multiplication ``a.dot(b)`` :math:`= a \cdot b`. This is equivalent to calling the operator :meth:`qiskit.quantum_info.Operator.compose` method with the kwarg ``front`` set to ``True``. upgrade: - | Changed :class:`qiskit.quantum_info.Operator` magic methods so that ``__mul__`` (which gets executed by python's multiplication operation, if the left hand side of the operation has it defined) implements right matrix multiplication (i.e. :meth:`qiskit.quantum_info.Operator.dot`), and ``__rmul__`` (which gets executed by python's multiplication operation from the right hand side of the operation if the left does not have ``__mul__`` defined) implements scalar multiplication (i.e. :meth:`qiskit.quantum_info.Operator.multiply`). Previously both methods implemented scalar multiplication.
qiskit/releasenotes/notes/0.12/operator-dot-fd90e7e5ad99ff9b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.12/operator-dot-fd90e7e5ad99ff9b.yaml", "repo_id": "qiskit", "token_count": 413 }
218
--- features: - | A new method, :meth:`~qiskit.circuit.QuantumCircuit.assign_parameters` has been added to the :class:`qiskit.circuit.QuantumCircuit` class. This method accepts a parameter dictionary with both floats and Parameters objects in a single dictionary. In other words this new method allows you to bind floats, Parameters or both in a single dictionary. Also, by using the ``inplace`` kwarg it can be specified you can optionally modify the original circuit in place. By default this is set to ``False`` and a copy of the original circuit will be returned from the method.
qiskit/releasenotes/notes/0.13/bind-parameters-mixed-values-and-in-place-48a68c882a03070b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/bind-parameters-mixed-values-and-in-place-48a68c882a03070b.yaml", "repo_id": "qiskit", "token_count": 178 }
219
--- upgrade: - | The :class:`~qiskit.circuit.QuantumCircuit` method :meth:`~qiskit.circuit.QuantumCircuit.draw` and :func:`qiskit.visualization.circuit_drawer` function will no longer include the initial state included in visualizations by default. If you would like to retain the initial state in the output visualization you need to set the ``initial_state`` kwarg to ``True``. For example, running: .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.measure_all() circuit.draw(output='text') This no longer includes the initial state. If you'd like to retain it you can run: .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.measure_all() circuit.draw(output='text', initial_state=True) features: - | A new kwarg, ``initial_state`` has been added to the :func:`qiskit.visualization.circuit_drawer` function and the :class:`~qiskit.circuit.QuantumCircuit` method :meth:`~qiskit.circuit.QuantumCircuit.draw`. When set to ``True`` the initial state will be included in circuit visualizations for all backends. For example: .. code-block:: from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.measure_all() circuit.draw(output='mpl', initial_state=True)
qiskit/releasenotes/notes/0.13/initial_state_draw_parameter-f360ac4e998ee944.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/initial_state_draw_parameter-f360ac4e998ee944.yaml", "repo_id": "qiskit", "token_count": 540 }
220
--- features: - | A new visualization function :func:`qiskit.visualization.visualize_transition` for visualizing single qubit gate transitions has been added. It takes in a single qubit circuit and returns an animation of qubit state transitions on a Bloch sphere. To use this function you must have installed the dependencies for and configured globally a matplotlib animation writer. You can refer to the `matplotlib documentation <https://matplotlib.org/api/animation_api.html#writer-classes>`_ for more details on this. However, in the default case simply ensuring that `FFmpeg <https://www.ffmpeg.org/>`_ is installed is sufficient to use this function. It supports circuits with the following gates: * :class:`~qiskit.extensions.HGate` * :class:`~qiskit.extensions.XGate` * :class:`~qiskit.extensions.YGate` * :class:`~qiskit.extensions.ZGate` * :class:`~qiskit.extensions.RXGate` * :class:`~qiskit.extensions.RYGate` * :class:`~qiskit.extensions.RZGate` * :class:`~qiskit.extensions.SGate` * :class:`~qiskit.extensions.SdgGate` * :class:`~qiskit.extensions.TGate` * :class:`~qiskit.extensions.TdgGate` * :class:`~qiskit.extensions.U1Gate` For example: .. code-block:: from qiskit.visualization import visualize_transition from qiskit import * qc = QuantumCircuit(1) qc.h(0) qc.ry(70,0) qc.rx(90,0) qc.rz(120,0) visualize_transition(qc, fpg=20, spg=1, trace=True)
qiskit/releasenotes/notes/0.13/quibit-transition-visualization-a62d0d119569fa05.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/quibit-transition-visualization-a62d0d119569fa05.yaml", "repo_id": "qiskit", "token_count": 610 }
221
--- features: - | Add :meth:`~qiskit.quantum_info.Clifford.from_label` method to the :class:`qiskit.quantum_info.Clifford` class for initializing as the tensor product of single-qubit I, X, Y, Z, H, or S gates.
qiskit/releasenotes/notes/0.14/clifford-from-label-4ac8a987109916ef.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.14/clifford-from-label-4ac8a987109916ef.yaml", "repo_id": "qiskit", "token_count": 93 }
222
--- features: - | The methods on the :class:`qiskit.circuit.QuantumCircuit` class for adding gates (for example :meth:`~qiskit.circuit.QuantumCircuit.h`) which were previously added dynamically at run time to the class definition have been refactored to be statically defined methods of the class. This means that static analyzer (such as IDEs) can now read these methods. deprecations: - | The ``qiskit.extensions.standard`` module is deprecated and will be removed in a future release. The gate classes in that module have been moved to :mod:`qiskit.circuit.library.standard_gates`.
qiskit/releasenotes/notes/0.14/stop-monkeypatching-circuit-gates-e0a9fc1e78f54ebe.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.14/stop-monkeypatching-circuit-gates-e0a9fc1e78f54ebe.yaml", "repo_id": "qiskit", "token_count": 193 }
223
--- features: - | Two new classes, :class:`~qiskit.circuit.AncillaRegister` and :class:`~qiskit.circuit.AncillaQubit` have been added to the :mod:`qiskit.circuit` module. These are subclasses of :class:`~qiskit.circuit.QuantumRegister` and :class:`~qiskit.circuit.Qubit` respectively and enable marking qubits being ancillas. This will allow these qubits to be re-used in larger circuits and algorithms.
qiskit/releasenotes/notes/0.15/ancilla-qubit-cdf5fb28373b8553.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/ancilla-qubit-cdf5fb28373b8553.yaml", "repo_id": "qiskit", "token_count": 158 }
224
--- fixes: - | Previously it was possible to set the number of control qubits to zero in which case the the original, potentially non-controlled, operation would be returned. This could cause an ``AttributeError`` to be raised if the caller attempted to access an attribute which only :class:`~qiskit.circuit.ControlledGate` object have. This has been fixed by adding a getter and setter for :attr:`~qiskit.circuit.ControlledGate.num_ctrl_qubits` to validate that a valid value is being used. Fixes `#4576 <https://github.com/Qiskit/qiskit-terra/issues/4576>`__
qiskit/releasenotes/notes/0.15/disallow_num_ctrl_qubits_zero-eb102aa087f30250.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/disallow_num_ctrl_qubits_zero-eb102aa087f30250.yaml", "repo_id": "qiskit", "token_count": 192 }
225
--- features: - | A new class, :class:`~qiskit.circuit.library.QuadraticForm` to the :mod:`qiskit.circuit.library` module for implementing a a quadratic form on binary variables. The circuit library element implements the operation .. math:: |x\rangle |0\rangle \mapsto |x\rangle |Q(x) \mod 2^m\rangle for the quadratic form :math:`Q` and :math:`m` output qubits. The result is in the :math:`m` output qubits is encoded in two's complement. If :math:`m` is not specified, the circuit will choose the minimal number of qubits required to represent the result without applying a modulo operation. The quadratic form is specified using a matrix for the quadratic terms, a vector for the linear terms and a constant offset. If all terms are integers, the circuit implements the quadratic form exactly, otherwise it is only an approximation. For example:: import numpy as np from qiskit.circuit.library import QuadraticForm A = np.array([[1, 2], [-1, 0]]) b = np.array([3, -3]) c = -2 m = 4 quad_form_circuit = QuadraticForm(m, A, b, c)
qiskit/releasenotes/notes/0.15/quadratic-form-circuit-f0ddb1694960cbc1.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/quadratic-form-circuit-f0ddb1694960cbc1.yaml", "repo_id": "qiskit", "token_count": 416 }
226
--- features: - | Added the method :meth:`~qiskit.pulse.Schedule.replace` to the :class:`qiskit.pulse.Schedule` class which allows a pulse instruction to be replaced with another. For example:: .. code-block:: python from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new)
qiskit/releasenotes/notes/0.15/schedule-replace-2c5634a6133db237.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/schedule-replace-2c5634a6133db237.yaml", "repo_id": "qiskit", "token_count": 219 }
227
--- features: - | A new color scheme, ``iqx``, has been added to the ``mpl`` backend for the circuit drawer :func:`qiskit.visualization.circuit_drawer` and :meth:`qiskit.circuit.QuantumCircuit.draw`. This uses the same color scheme as the Circuit Composer on the IBM Quantum Experience website. There are now 3 available color schemes - ``default``, ``iqx``, and ``bw``. There are two ways to select a color scheme. The first is to use a user config file, by default in the ``~/.qiskit`` directory, in the file ``settings.conf`` under the ``[Default]`` heading, a user can enter ``circuit_mpl_style = iqx`` to select the ``iqx`` color scheme. The second way is to add ``{'name': 'iqx'}`` to the ``style`` kwarg to the ``QuantumCircuit.draw`` method or to the ``circuit_drawer`` function. The second way will override the setting in the settings.conf file. For example: .. code-block:: from qiskit.circuit import QuantumCircuit circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() circuit.draw('mpl', style={'name': 'iqx'}) - | In the ``style`` kwarg for the the circuit drawer :func:`qiskit.visualization.circuit_drawer` and :meth:`qiskit.circuit.QuantumCircuit.draw` the ``displaycolor`` field with the ``mpl`` backend now allows for entering both the gate color and the text color for each gate type in the form ``(gate_color, text_color)``. This allows the use of light and dark gate colors with contrasting text colors. Users can still set only the gate color, in which case the ``gatetextcolor`` field will be used. Gate colors can be set in the ``style`` dict for any number of gate types, from one to the entire ``displaycolor`` dict. For example: .. code-block:: from qiskit.circuit import QuantumCircuit circuit = QuantumCircuit(1) circuit.h(0) style_dict = {'displaycolor': {'h': ('#FA74A6', '#000000')}} circuit.draw('mpl', style=style_dict) or .. code-block:: style_dict = {'displaycolor': {'h': '#FA74A6'}} circuit.draw('mpl', style=style_dict)
qiskit/releasenotes/notes/0.16/add-iqx-color-scheme-0de42f0d004fad31.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/add-iqx-color-scheme-0de42f0d004fad31.yaml", "repo_id": "qiskit", "token_count": 775 }
228
--- fixes: - | Fixes a bug where setting ``ctrl_state`` of a :class:`~qiskit.extensions.UnitaryGate` would be applied twice; once in the creation of the matrix for the controlled unitary and again when calling the :meth:`~qiskit.circuit.ControlledGate.definition` method of the :class:`qiskit.circuit.ControlledGate` class. This would give the appearance that setting ``ctrl_state`` had no effect.
qiskit/releasenotes/notes/0.16/fix-bug-in-controlled-unitary-when-setting-ctrl_state-2f9af3b9f0f7903f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/fix-bug-in-controlled-unitary-when-setting-ctrl_state-2f9af3b9f0f7903f.yaml", "repo_id": "qiskit", "token_count": 138 }
229
--- upgrade: - | The keyword arguments for the circuit gate methods (for example: :class:`qiskit.circuit.QuantumCircuit.cx`) ``q``, ``ctl*``, and ``tgt*``, which were deprecated in the 0.12.0 release, have been removed. Instead, only ``qubit``, ``control_qubit*`` and ``target_qubit*`` can be used as named arguments for these methods.
qiskit/releasenotes/notes/0.16/remove-deprecated-gate-args-b29ba17badcb77ca.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/remove-deprecated-gate-args-b29ba17badcb77ca.yaml", "repo_id": "qiskit", "token_count": 128 }
230
--- features: - | Added a new function :func:`~qiskit.visualization.array_to_latex` to the :mod:`qiskit.visualization` module that can be used to represent and visualize vectors and matrices with LaTeX. .. code-block:: from qiskit.visualization import array_to_latex from numpy import sqrt, exp, pi mat = [[0, exp(pi*.75j)], [1/sqrt(8), 0.875]] array_to_latex(mat)
qiskit/releasenotes/notes/0.17/add_array_to_latex-0b5f655a47f132c0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/add_array_to_latex-0b5f655a47f132c0.yaml", "repo_id": "qiskit", "token_count": 208 }
231
--- fixes: - | Fixed an issue with the :func:`qiskit.visualization.circuit_drawer` function and :meth:`qiskit.circuit.QuantumCircuit.draw` method when visualizing a :class:`~qiskit.circuit.QuantumCircuit` with a :class:`~qiskit.circuit.Gate` that has a classical condition after a :class:`~qiskit.circuit.Measure` that used the same :class:`~qiskit.circuit.ClassicalRegister`, it was possible for the conditional :class:`~qiskit.circuit.Gate` to be displayed to the left of the :class:`~qiskit.circuit.Measure`. Fixed `#5387 <https://github.com/Qiskit/qiskit-terra/issues/5387>`__
qiskit/releasenotes/notes/0.17/conditional-displays-after-measure-3f53a86800b2c459.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/conditional-displays-after-measure-3f53a86800b2c459.yaml", "repo_id": "qiskit", "token_count": 239 }
232
--- fixes: - | Fixed the handling of breakpoints in the :class:`~qiskit.circuit.library.PiecewisePolynomialPauliRotations` class in the :mod:`qiskit.circuit.library`. Now for ``n`` intervals, ``n+1`` breakpoints are allowed. This enables specifying another end interval other than :math:`2^\text{num qubits}`. This is important because from the end of the last interval to :math:`2^\text{num qubits}` the function is the identity.
qiskit/releasenotes/notes/0.17/fix-piecewise-breakpoints-21db5a7823fdfbed.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/fix-piecewise-breakpoints-21db5a7823fdfbed.yaml", "repo_id": "qiskit", "token_count": 157 }
233
--- features: - | A new transpiler pass, :py:class:`qiskit.transpiler.passes.RZXCalibrationBuilder`, capable of generating calibrations and adding them to a quantum circuit has been introduced. This pass takes calibrated :class:`~qiskit.circuit.library.CXGate` objects and creates the calibrations for :class:`qiskit.circuit.library.RZXGate` objects with an arbitrary rotation angle. The schedules are created by stretching and compressing the :class:`~qiskit.pulse.GaussianSquare` pulses of the echoed-cross resonance gates. - | New template circuits for using :class:`qiskit.circuit.library.RZXGate` are added to the :mod:`qiskit.circuit.library` module (eg :class:`~qiskit.circuit.library.rzx_yz`). This enables pairing the :class:`~qiskit.transpiler.passes.TemplateOptimization` pass with the :py:class:`qiskit.transpiler.passes.RZXCalibrationBuilder` pass to automatically find and replace gate sequences, such as ``CNOT - P(theta) - CNOT``, with more efficient circuits based on :class:`qiskit.circuit.library.RZXGate` with a calibration.
qiskit/releasenotes/notes/0.17/issue-5751-1b6249f6263c9c30.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/issue-5751-1b6249f6263c9c30.yaml", "repo_id": "qiskit", "token_count": 382 }
234
--- upgrade: - | The previously deprecated kwarg ``callback`` on the constructor for the :class:`~qiskit.transpiler.PassManager` class has been removed. This kwarg has been deprecated since the 0.13.0 release (April, 9th 2020). Instead you can pass the ``callback`` kwarg to the :meth:`qiskit.transpiler.PassManager.run` method directly. For example, if you were using:: from qiskit.circuit.random import random_circuit from qiskit.transpiler import PassManager qc = random_circuit(2, 2) def callback(**kwargs) print(kwargs['pass_']) pm = PassManager(callback=callback) pm.run(qc) this can be replaced with:: from qiskit.circuit.random import random_circuit from qiskit.transpiler import PassManager qc = random_circuit(2, 2) def callback(**kwargs) print(kwargs['pass_']) pm = PassManager() pm.run(qc, callback=callback)
qiskit/releasenotes/notes/0.17/pm_cb_remove_5522-30358587a8db2701.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/pm_cb_remove_5522-30358587a8db2701.yaml", "repo_id": "qiskit", "token_count": 369 }
235
--- features: - | The ``latex`` output method for the :func:`qiskit.visualization.circuit_drawer` function and the :meth:`~qiskit.circuit.QuantumCircuit.draw` method now will use a user defined label on gates in the output visualization. For example:: import math from qiskit.circuit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.rx(math.pi/2, 0, label='My Special Rotation') qc.draw(output='latex') fixes: - | In a number of cases, the ``latex`` output method for the :func:`qiskit.visualization.circuit_drawer` function and the :meth:`~qiskit.circuit.QuantumCircuit.draw` method did not display the gate name correctly, and in other cases, did not include gate parameters where they should be. Now the gate names will be displayed the same way as they are displayed with the ``mpl`` output method, and parameters will display for all the gates that have them. In addition, some of the gates did not display in the correct form, and these have been fixed. Fixes `#5605 <https://github.com/Qiskit/qiskit-terra/issues/5605>`__, `#4938 <https://github.com/Qiskit/qiskit-terra/issues/4938>`__, and `#3765 <https://github.com/Qiskit/qiskit-terra/issues/3765>`__
qiskit/releasenotes/notes/0.17/revise_latex_drawer-43ac082445a8611d.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/revise_latex_drawer-43ac082445a8611d.yaml", "repo_id": "qiskit", "token_count": 470 }
236
--- features: - | A new kwarg, ``line_discipline``, has been added to the :func:`~qiskit.tools.job_monitor` function. This kwarg enables changing the carriage return characters used in the ``job_monitor`` output. The ``line_discipline`` kwarg defaults to ``'\r'``, which is what was in use before.
qiskit/releasenotes/notes/0.18/add-line_discipline-to-job_monitor-dc9b66a9d819dbfa.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/add-line_discipline-to-job_monitor-dc9b66a9d819dbfa.yaml", "repo_id": "qiskit", "token_count": 107 }
237
--- deprecations: - | The legacy providers interface, which consisted of the :class:`qiskit.providers.BaseBackend`, :class:`qiskit.providers.BaseJob`, and :class:`qiskit.providers.BaseProvider` abstract classes, has been deprecated and will be removed in a future release. Instead you should use the versioned interface, which the current abstract class versions are :class:`qiskit.providers.BackendV1`, :class:`qiskit.providers.JobV1`, and :class:`qiskit.providers.ProviderV1`. The V1 objects are mostly backwards compatible to ease migration from the legacy interface to the versioned one. However, expect future versions of the abstract interfaces to diverge more. You can refer to the :mod:`qiskit.providers` documentation for more high level details about the versioned interface.
qiskit/releasenotes/notes/0.18/deprecate-legacy-providers-383bf4142153297a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/deprecate-legacy-providers-383bf4142153297a.yaml", "repo_id": "qiskit", "token_count": 249 }
238
--- fixes: - | Fixed an issue where the QASM output generated by the :meth:`~qiskit.circuit.QuantumCircuit.qasm` method of :class:`~qiskit.circuit.QuantumCircuit` for composite gates such as :class:`~qiskit.circuit.library.MCXGate` and its variants ( :class:`~qiskit.circuit.library.MCXGrayCode`, :class:`~qiskit.circuit.library.MCXRecursive`, and :class:`~qiskit.circuit.library.MCXVChain`) would be incorrect. Now if a :class:`~qiskit.circuit.Gate` in the circuit is not present in ``qelib1.inc``, its definition is added to the output QASM string. Fixed `#4943 <https://github.com/Qiskit/qiskit-terra/issues/4943>`__ and `#3945 <https://github.com/Qiskit/qiskit-terra/issues/3945>`__
qiskit/releasenotes/notes/0.18/fix-qasm-output-for-composite-gates-cc847103eec26c85.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/fix-qasm-output-for-composite-gates-cc847103eec26c85.yaml", "repo_id": "qiskit", "token_count": 300 }
239
--- fixes: - | Fixed an issue with the phase of the :class:`qiskit.opflow.gradients.QFI` class when the ``qfi_method`` is set to ``lin_comb_full`` which caused the incorrect observable to be evaluated.
qiskit/releasenotes/notes/0.18/phase_fix_fix-e6bff434a4b1e88d.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/phase_fix_fix-e6bff434a4b1e88d.yaml", "repo_id": "qiskit", "token_count": 74 }
240
--- fixes: - | Fixed a bug where many layout methods would ignore 3-or-more qubit gates, resulting in unexpected layout-allocation decisions. The transpiler pass :class:`.Unroll3qOrMore` is now being executed before the layout pass in all the preset pass managers when :func:`~.compiler.transpile` is called. Fixed `#7156 <https://github.com/Qiskit/qiskit-terra/issues/7156>`__.
qiskit/releasenotes/notes/0.19/7156-df1a60c608b93184.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/7156-df1a60c608b93184.yaml", "repo_id": "qiskit", "token_count": 136 }
241
--- features: - | Introduced a new option ``qubit_subset`` to the constructor of :class:`.BIPMapping`. The option enables us to specify physical qubits to be used (in ``coupling_map`` of the device) during the mapping in one line: .. code-block:: python mapped_circ = BIPMapping( coupling_map=CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]), qubit_subset=[1, 3, 4] )(circ) Previously, to do the same thing, we had to supply a reduced ``coupling_map`` which contains only the qubits to be used, embed the resulting circuit onto the original ``coupling_map`` and update the ``QuantumCircuit._layout`` accordingly: .. code-block:: python reduced_coupling = coupling_map.reduce(qubit_to_use) mapped = BIPMapping(reduced_coupling)(circ) # skip the definition of fill_with_ancilla() # recover circuit on original coupling map layout = Layout({q: qubit_to_use[i] for i, q in enumerate(mapped.qubits)}) for reg in mapped.qregs: layout.add_register(reg) property_set = {"layout": fill_with_ancilla(layout)} recovered = ApplyLayout()(mapped, property_set) # recover layout overall_layout = Layout({v: qubit_to_use[q] for v, q in mapped._layout.get_virtual_bits().items()}) for reg in mapped.qregs: overall_layout.add_register(reg) recovered._layout = fill_with_ancilla(overall_layout)
qiskit/releasenotes/notes/0.19/add-qubit-subset-to-bip-mapper-e1c6234d04484d58.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/add-qubit-subset-to-bip-mapper-e1c6234d04484d58.yaml", "repo_id": "qiskit", "token_count": 553 }
242
--- deprecations: - | The ``label`` property of class :class:`~qiskit.circuit.library.MCMT` and subclass :class:`~qiskit.circuit.library.MCMTVChain` has been deprecated and will be removed in a future release. Consequently, the ``label`` kwarg on the constructor for both classes is also deprecated, along with the ``label`` kwarg of method :meth:`.MCMT.control`. Currently, the ``label`` property is used to name the controlled target when it is comprised of more than one target qubit, however, this was never intended to be user-specifiable, and can result in an incorrect MCMT gate if the name of a well-known operation is used. After deprecation, the ``label`` property will no longer be user-specifiable. However, you can get the generated name of the controlled target via :: MCMT.data[0][0].base_gate.name
qiskit/releasenotes/notes/0.19/deprecate-mcmt-label-12865e041ce67658.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/deprecate-mcmt-label-12865e041ce67658.yaml", "repo_id": "qiskit", "token_count": 277 }
243
--- fixes: - | Fixed an issue where calling :meth:`.QuantumCircuit.decompose()` on a circuit containing an :class:`~qiskit.circuit.Instruction` whose :attr:`~.Instruction.definition` attribute was empty would leave the instruction in place, instead of decomposing it into zero operations. For example, with a circuit:: from qiskit.circuit import QuantumCircuit empty = QuantumCircuit(1, name="decompose me!") circuit = QuantumCircuit(1) circuit.append(empty.to_gate(), [0]) Previously, calling ``circuit.decompose()`` would not change the circuit. Now, the decomposition will correct decompose ``empty`` into zero instructions. See `#6997 <https://github.com/Qiskit/qiskit-terra/pull/6997>`__ for more.
qiskit/releasenotes/notes/0.19/fix-decompose-empty-gate-71455847dcaaea26.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/fix-decompose-empty-gate-71455847dcaaea26.yaml", "repo_id": "qiskit", "token_count": 284 }
244
--- features: - | The ``text`` output method for the :func:`~qiskit.visualization.circuit_drawer` function and the :meth:`.QuantumCircuit.draw` method can now draw circuits that contain gates with single bit condition. This was added for compatibility of text drawer with the new feature of supporting classical conditioning of gates on single classical bits.
qiskit/releasenotes/notes/0.19/fix-text-drawer-bit-cond-a3b02f0b0b6e3ec2.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/fix-text-drawer-bit-cond-a3b02f0b0b6e3ec2.yaml", "repo_id": "qiskit", "token_count": 108 }
245
--- features: - | Added a :class:`~qiskit.circuit.library.PauliEvolutionGate` to the circuit library (:mod:`qiskit.circuit.library`) which defines a gate performing time evolution of (sums or sums-of-sums of) :obj:`.Pauli`\ s. The synthesis of this gate is performed by :class:`~qiskit.synthesis.EvolutionSynthesis` and is decoupled from the gate itself. Currently available synthesis methods are: * :class:`~qiskit.synthesis.LieTrotter`: first order Trotterization * :class:`~qiskit.synthesis.SuzukiTrotter`: higher order Trotterization * :class:`~qiskit.synthesis.MatrixExponential`: exact, matrix-based evolution For example:: from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import PauliEvolutionGate from qiskit.quantum_info import SparsePauliOp from qiskit.synthesis import SuzukiTrotter operator = SparsePauliOp.from_list([ ("XIZ", 0.5), ("ZZX", 0.5), ("IYY", -1) ]) time = 0.12 # evolution time synth = SuzukiTrotter(order=4, reps=2) evo = PauliEvolutionGate(operator, time=time, synthesis=synth) circuit = QuantumCircuit(3) circuit.append(evo, range(3))
qiskit/releasenotes/notes/0.19/pauli-evolution-gate-ad767a3e43714fa7.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/pauli-evolution-gate-ad767a3e43714fa7.yaml", "repo_id": "qiskit", "token_count": 498 }
246
--- upgrade: - | Various methods of assigning parameters to operands of pulse program instructions have been removed, having been deprecated in Qiskit Terra 0.17. These include: * the ``assign()`` method of :obj:`.pulse.Instruction`. * the ``assign()`` method of ``Channel``, which is the base of :obj:`.AcquireChannel`, :obj:`.SnapshotChannel`, :obj:`.MemorySlot` and :obj:`.RegisterSlot`. * the ``assign()`` and ``assign_parameters()`` methods of ``ParametricPulse``, which is the base of :obj:`.pulse.Gaussian`, :obj:`.pulse.GaussianSquare`, :obj:`.pulse.Drag` and :obj:`.pulse.Constant`. These parameters should be assigned from the pulse program (:class:`.pulse.Schedule` and :class:`.pulse.ScheduleBlock`) rather than operands of the pulse program instruction. - | The ``flatten()`` method of :class:`.pulse.Instruction` and :class:`qiskit.pulse.Schedule` has been removed and no longer exists as per the deprecation notice from Qiskit Terra 0.17. This transformation is defined as a standalone function in :func:`qiskit.pulse.transforms.canonicalization.flatten`. - | ``qiskit.pulse.interfaces.ScheduleComponent`` has been removed and no longer exists as per the deprecation notice from Qiskit Terra 0.15. No alternative class will be provided. - | Legacy pulse drawer arguments have been removed from :meth:`.pulse.Waveform.draw`, :meth:`.Schedule.draw` and :meth:`.ScheduleBlock.draw` and no longer exist as per the deprecation notice from Qiskit Terra 0.16. Now these draw methods support only V2 pulse drawer arguments. See method documentations for details. - | The ``qiskit.pulse.reschedule`` module has been removed and this import path no longer exist as per the deprecation notice from Qiskit Terra 0.14. Use :mod:`qiskit.pulse.transforms` instead. - | A protected method ``Schedule._children()`` has been removed and replaced by a protected instance variable as per the deprecation notice from Qiskit Terra 0.17. This is now provided as a public attribute :obj:`.Schedule.children`. - | Timeslot relevant methods and properties have been removed and no longer exist in :class:`~.pulse.ScheduleBlock` as per the deprecation notice from Qiskit Terra 0.17. Since this representation doesn't have notion of instruction time ``t0``, the timeslot information will be available after it is transformed to a :obj:`~.pulse.Schedule`. Corresponding attributes have been provided after this conversion, but they are no longer supported. The following attributes are removed: * ``timeslots`` * ``start_time`` * ``stop_time`` * ``ch_start_time`` * ``ch_stop_time`` * ``shift`` * ``insert`` - | Alignment pulse schedule transforms have been removed and no longer exist as per the deprecation notice from Qiskit Terra 0.17. These transforms are integrated and implemented in the ``AlignmentKind`` context of the schedule block. The following explicit transform functions are removed: * ``qiskit.pulse.transforms.align_equispaced`` * ``qiskit.pulse.transforms.align_func`` * ``qiskit.pulse.transforms.align_left`` * ``qiskit.pulse.transforms.align_right`` * ``qiskit.pulse.transforms.align_sequential`` - | Redundant pulse builder commands have been removed and no longer exist as per the deprecation notice from Qiskit Terra 0.17. ``pulse.builder.call_schedule`` and ``pulse.builder.call_circuit`` have been integrated into :func:`.pulse.builder.call`.
qiskit/releasenotes/notes/0.19/remove-deprecated-pulse-code-57ec531224e45b5f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/remove-deprecated-pulse-code-57ec531224e45b5f.yaml", "repo_id": "qiskit", "token_count": 1189 }
247
--- features: - | Added a new transpiler pass, :class:`~qiskit.transpiler.passes.VF2Layout`. This pass models the layout allocation problem as a subgraph isomorphism problem and uses the `VF2 algorithm`_ implementation in `retworkx <https://qiskit.org/documentation/retworkx/stubs/retworkx.vf2_mapping.html>`__ to find a perfect layout (a layout which would not require additional routing) if one exists. The functionality exposed by this new pass is very similar to existing :class:`~qiskit.transpiler.passes.CSPLayout` but :class:`~qiskit.transpiler.passes.VF2Layout` is significantly faster. .. _VF2 algorithm: https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.101.5342&rep=rep1&type=pdf
qiskit/releasenotes/notes/0.19/vf2layout-4cea88087c355769.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/vf2layout-4cea88087c355769.yaml", "repo_id": "qiskit", "token_count": 263 }
248
--- features: - | The ``FakeBogota``, ``FakeManila``, ``FakeRome``, and ``FakeSantiago`` fake backends which can be found in the ``qiskit.providers.fake_provider`` module can now be used as backends in Pulse experiments as they now include a :class:`~qiskit.providers.models.PulseDefaults` created from a snapshot of the equivalent IBM Quantum machine's properties.
qiskit/releasenotes/notes/0.20/bogota-manila-rome-santiago-as-fakepulsebackends-2907dec149997a27.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/bogota-manila-rome-santiago-as-fakepulsebackends-2907dec149997a27.yaml", "repo_id": "qiskit", "token_count": 126 }
249
--- fixes: - | Fixed an endianness bug in :meth:`.BaseReadoutMitigator.expectation_value` when a string ``diagonal`` was passed. It will now correctly be interpreted as little endian in the same manner as the rest of Qiskit Terra, instead of big endian.
qiskit/releasenotes/notes/0.20/fix-mitigator-endian-ead88499eb7e12ea.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/fix-mitigator-endian-ead88499eb7e12ea.yaml", "repo_id": "qiskit", "token_count": 89 }
250
--- features: - | Introduced a new class :class:`~qiskit.circuit.library.StatePreparation`. This class allows users to prepare a desired state in the same fashion as :class:`~qiskit.extensions.Initialize` without the reset being automatically applied. For example, to prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() The output is as:: ┌─────────────────────────────────────┐ q_0: ┤ State Preparation(0.70711,-0.70711) ├ └─────────────────────────────────────┘
qiskit/releasenotes/notes/0.20/new-state-preparation-class-f8c0617a0c988f12.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/new-state-preparation-class-f8c0617a0c988f12.yaml", "repo_id": "qiskit", "token_count": 307 }
251
--- upgrade: - | The module ``qiskit.circuit.library.probability_distributions`` has been removed and no longer exists as per the deprecation notice from qiskit-terra 0.17.0 (released Apr 1, 2021). The affected classes are ``UniformDistribution``, ``NormalDistribution``, and ``LogNormalDistribution``. They are all moved to the `qiskit-finance <https://qiskit.org/documentation/finance/getting_started.html>`__ library, into its circuit library module: ``qiskit_finance.circuit.library.probability_distributions``.
qiskit/releasenotes/notes/0.20/remove_probability_distributions-d30bd77f0f2b9570.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/remove_probability_distributions-d30bd77f0f2b9570.yaml", "repo_id": "qiskit", "token_count": 187 }
252
--- features: - | Added a new class, :class:`qiskit.transpiler.StagedPassManager`, which is a :class:`~qiskit.transpiler.PassManager` subclass that has a pipeline with defined phases to perform circuit compilation. Each phase is a :class:`~qiskit.transpiler.PassManager` object that will get executed in a fixed order. For example:: from qiskit.transpiler.passes import * from qiskit.transpiler import PassManager, StagedPassManager basis_gates = ['rx', 'ry', 'rxx'] init = PassManager([UnitarySynthesis(basis_gates, min_qubits=3), Unroll3qOrMore()]) translate = PassManager([Collect2qBlocks(), ConsolidateBlocks(basis_gates=basis_gates), UnitarySynthesis(basis_gates)]) staged_pm = StagedPassManager(stages=['init', 'translation'], init=init, translation=translate)
qiskit/releasenotes/notes/0.21/add-full-passmanager-5a377f1b71480f72.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/add-full-passmanager-5a377f1b71480f72.yaml", "repo_id": "qiskit", "token_count": 357 }
253
--- deprecations: - | The `NetworkX <https://networkx.org/>`__ converter functions for the :meth:`.DAGCircuit.to_networkx` and :meth:`~.DAGCircuit.from_networkx`, along with the :meth:`.DAGDependency.to_networkx` method have been deprecated and will be removed in a future release. Qiskit has been using `retworkx <https://qiskit.org/documentation/retworkx/>`__ as its graph library since the qiskit-terra 0.12.0 release, and since then the networkx converter functions have been lossy. They were originally added so that users could leverage functionality in NetworkX's algorithms library not present in retworkx. Since that time, retworkx has matured and offers more functionality, and the :class:`~.DAGCircuit` is tightly coupled to retworkx for its operation. Having these converter methods provides limited value moving forward and are therefore going to be removed in a future release.
qiskit/releasenotes/notes/0.21/deprecate-nx-dag-f8a8d947186222c2.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/deprecate-nx-dag-f8a8d947186222c2.yaml", "repo_id": "qiskit", "token_count": 294 }
254
--- upgrade: - | Qiskit Terra's compiled Rust extensions now have a minimum supported Rust version (MSRV) of 1.56.1. This means when building Qiskit Terra from source the oldest version of the Rust compiler supported is 1.56.1. If you are using an older version of the Rust compiler you will need to update to a newer version to continue to build Qiskit from source. This change was necessary as a number of upstream dependencies have updated their minimum supported versions too.
qiskit/releasenotes/notes/0.21/msrv-0b626e1cfb415abf.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/msrv-0b626e1cfb415abf.yaml", "repo_id": "qiskit", "token_count": 138 }
255
--- upgrade: - | For Python 3.7 `shared-memory38 <https://pypi.org/project/shared-memory38/>`__ is now a dependency. This was added as a dependency for Python 3.7 to enable leveraging the shared memory constructs in the standard library of newer versions of Python. If you're running on Python >= 3.8 there is no extra dependency required. fixes: - | Fixed an issue with :func:`~.transpile` where in some cases providing a list of basis gate strings with the ``basis_gates`` keyword argument or implicitly via a :class:`~.Target` input via the ``target`` keyword argument would not be interpreted correctly and result in a subset of the listed gates being used for each circuit. - | Fixed an issue in the :class:`~.UnitarySynthesis` transpiler pass which would result in an error when a :class:`~.Target` that didn't have any qubit restrictions on the operations (e.g. in the case of an ideal simulator target) was specified with the ``target`` keyword argument for the constructor.
qiskit/releasenotes/notes/0.21/shared-memory-dependency-1e32e1c55902216f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/shared-memory-dependency-1e32e1c55902216f.yaml", "repo_id": "qiskit", "token_count": 310 }
256
--- features: - | Added new algorithms to calculate state fidelities/overlaps for pairs of quantum circuits (that can be parametrized). Apart from the base class (:class:`~qiskit.algorithms.state_fidelities.BaseStateFidelity`) which defines the interface, there is an implementation of the compute-uncompute method that leverages instances of the :class:`~.BaseSampler` primitive: :class:`qiskit.algorithms.state_fidelities.ComputeUncompute`. For example: .. code-block:: python import numpy as np from qiskit.primitives import Sampler from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import RealAmplitudes sampler = Sampler(...) fidelity = ComputeUncompute(sampler) circuit = RealAmplitudes(2) values = np.random.random(circuit.num_parameters) shift = np.ones_like(values) * 0.01 job = fidelity.run([circuit], [circuit], [values], [values+shift]) fidelities = job.result().fidelities
qiskit/releasenotes/notes/0.22/add-fidelity-interface-primitives-dc543d079ecaa8dd.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/add-fidelity-interface-primitives-dc543d079ecaa8dd.yaml", "repo_id": "qiskit", "token_count": 367 }
257
--- fixes: - | Fixed a bug in :meth:`.QuantumCircuit.initialize` and :meth:`.QuantumCircuit.prepare_state` that caused them to not accept a single :class:`~qiskit.circuit.Qubit` as argument to initialize.
qiskit/releasenotes/notes/0.22/circuit-initialize-and-prepare-single-qubit-e25dacc8f873bc01.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/circuit-initialize-and-prepare-single-qubit-e25dacc8f873bc01.yaml", "repo_id": "qiskit", "token_count": 79 }
258
--- fixes: - | Fix a problem in the :class:`~.GateDirection` transpiler pass for the :class:`~.CZGate`. The CZ gate is symmetric, so flipping the qubit arguments is allowed to match the directed coupling map.
qiskit/releasenotes/notes/0.22/fix-flipping-cz-gate-fd08305ca12d9a79.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/fix-flipping-cz-gate-fd08305ca12d9a79.yaml", "repo_id": "qiskit", "token_count": 75 }
259
fixes: - | Fixed an issue in the output callable from the :meth:`~qiskit.algorithms.VQD.get_energy_evaluation` method of the :class:`~qiskit.algorithms.VQD` class will now correctly call the specified ``callback`` when run. Previously the callback would incorrectly not be used in this case. Fixed `#8575 <https://github.com/Qiskit/qiskit-terra/issues/8575>`__
qiskit/releasenotes/notes/0.22/make-use-of-callback-in-vqd-99e3c85f03181298.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/make-use-of-callback-in-vqd-99e3c85f03181298.yaml", "repo_id": "qiskit", "token_count": 141 }
260
--- features: - | The :meth:`.QNSPSA.get_fidelity` static method now supports an optional ``sampler`` argument which is used to provide an implementation of the :class:`~.BaseSampler` interface (such as :class:`~.Sampler`, :class:`~.BackendSampler`, or any provider implementations such as those present in ``qiskit-ibm-runtime`` and ``qiskit-aer``) to compute the fidelity of a :class:`~.QuantumCircuit`. For example:: from qiskit.primitives import Sampler from qiskit.algorithms.optimizers import QNSPSA fidelity = QNSPSA.get_fidelity(my_circuit, Sampler())
qiskit/releasenotes/notes/0.22/qnspsa-primitification-29a9dcae055bf2b4.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/qnspsa-primitification-29a9dcae055bf2b4.yaml", "repo_id": "qiskit", "token_count": 215 }
261
--- features: - | The :class:`~.SteppableOptimizer` class is added. It allows one to perfore classical optimizations step-by-step using the :meth:`~.SteppableOptimizer.step` method. These optimizers implement the "ask and tell" interface which (optionally) allows to manually compute the required function or gradient evaluations and plug them back into the optimizer. For more information about this interface see: `ask and tell interface <https://optuna.readthedocs.io/en/stable/tutorial/20_recipes/009_ask_and_tell.html>`_. A very simple use case when the user might want to do the optimization step by step is for readout: .. code-block:: python import random import numpy as np from qiskit.algorithms.optimizers import GradientDescent def objective(x): return (np.linalg.norm(x) - 1) ** 2 def grad(x): return 2 * (np.linalg.norm(x) - 1) * x / np.linalg.norm(x) initial_point = np.random.normal(0, 1, size=(100,)) optimizer = GradientDescent(maxiter=20) optimizer.start(x0=initial_point, fun=objective, jac=grad) for _ in range(maxiter): state = optimizer.state # Here you can manually read out anything from the optimizer state. optimizer.step() result = optimizer.create_result() A more complex case would be error handling. Imagine that the function you are evaluating has a random chance of failing. In this case you can catch the error and run the function again until it yields the desired result before continuing the optimization process. In this case one would use the ask and tell interface. .. code-block:: python import random import numpy as np from qiskit.algorithms.optimizers import GradientDescent def objective(x): if random.choice([True, False]): return None else: return (np.linalg.norm(x) - 1) ** 2 def grad(x): if random.choice([True, False]): return None else: return 2 * (np.linalg.norm(x) - 1) * x / np.linalg.norm(x) initial_point = np.random.normal(0, 1, size=(100,)) optimizer = GradientDescent(maxiter=20) optimizer.start(x0=initial_point, fun=objective, jac=grad) while optimizer.continue_condition(): ask_data = optimizer.ask() evaluated_gradient = None while evaluated_gradient is None: evaluated_gradient = grad(ask_data.x_center) optimizer.state.njev += 1 optimizer.state.nit += 1 cf = TellData(eval_jac=evaluated_gradient) optimizer.tell(ask_data=ask_data, tell_data=tell_data) result = optimizer.create_result() Transitioned :class:`GradientDescent` to be a subclass of :class:`.SteppableOptimizer`. fixes: - | :class:`.GradientDescent` will now correctly count the number of iterations, function evaluations and gradient evaluations. Also the documentation now correctly states that the gradient is approximated by a forward finite difference method.
qiskit/releasenotes/notes/0.22/steppable-optimizers-9d9b48ba78bd58bb.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/steppable-optimizers-9d9b48ba78bd58bb.yaml", "repo_id": "qiskit", "token_count": 1445 }
262
--- features: - | Added a depth-efficient synthesis algorithm :func:`qiskit.synthesis.linear.linear_depth_lnn.synth_cnot_depth_line_kms` for linear reversible circuits :class:`~qiskit.circuit.library.LinearFunction` over the linear nearest-neighbor architecture, following the paper <https://arxiv.org/abs/quant-ph/0701194>`__. upgrade: - | Added to the Qiskit documentation the synthesis algorithm :func:`qiskit.synthesis.linear.linear_depth_lnn.synth_cnot_count_full_pmh` for linear reversible circuits :class:`~qiskit.circuit.library.LinearFunction` for all-to-all architecture, following the paper <https://arxiv.org/abs/quant-ph/0302002>`__.
qiskit/releasenotes/notes/0.23/add-linear-synthesis-lnn-depth-5n-36c1aeda02b8bc6f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/add-linear-synthesis-lnn-depth-5n-36c1aeda02b8bc6f.yaml", "repo_id": "qiskit", "token_count": 253 }
263
--- features: - | Added the method :meth:`.QuantumCircuit.from_instructions` for constructing a quantum circuit from an iterable of instructions.
qiskit/releasenotes/notes/0.23/circuit-from-instructions-832b43bfd2bfd921.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/circuit-from-instructions-832b43bfd2bfd921.yaml", "repo_id": "qiskit", "token_count": 48 }
264
--- fixes: - | Fixed an issue with the backend primitive classes :class:`~.BackendSampler` and :class:`~.BackendEstimator` which prevented running with a :class:`~.BackendV1` instance that does not have a ``max_experiments`` field set in its :class:`~.BackendConfiguration`.
qiskit/releasenotes/notes/0.23/fix-backend-primitive-no-max-experiments-e2ca41ec61de353e.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/fix-backend-primitive-no-max-experiments-e2ca41ec61de353e.yaml", "repo_id": "qiskit", "token_count": 99 }
265
--- deprecations: - | The ``pauli_list`` kwarg of :func:`.pauli_basis` has been deprecated as :func:`.pauli_basis` now always returns a :class:`.PauliList`. fixes: - | Fixes the removal of ``pauli_list`` kwarg of :func:`.pauli_basis` which broke existing code using the ``pauli_list=True`` future compatibility on upgrade to Qiskit Terra 0.22. This kwarg has been added back to the the function with a deprecation warning instead.
qiskit/releasenotes/notes/0.23/fix-pauli-basis-dep-27c0a4506ad38d2c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/fix-pauli-basis-dep-27c0a4506ad38d2c.yaml", "repo_id": "qiskit", "token_count": 166 }
266
--- fixes: - | Fixed an issue with :func:`~.transpile` when targeting a :class:`~.Target` (either directly via the ``target`` argument or via a :class:`~.BackendV2` instance from the ``backend`` argument) that contained an ideal :class:`~.Measure` instruction (one that does not have any properties defined). Previously this would raise an exception trying to parse the target. Fixed `#8969 <https://github.com/Qiskit/qiskit-terra/issues/8969>`__
qiskit/releasenotes/notes/0.23/fix-transpile-ideal-measurement-c37e04533e196ded.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/fix-transpile-ideal-measurement-c37e04533e196ded.yaml", "repo_id": "qiskit", "token_count": 159 }
267
--- upgrade: - | The ``initial_state`` argument of the :class:`~NLocal` class should be a :class:`~.QuantumCircuit`. Passing any other type was deprecated as of Qiskit Terra 0.18.0 (July 2021) and that possibility is now removed.
qiskit/releasenotes/notes/0.23/initial_state-8e20b04fc2ec2f4b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/initial_state-8e20b04fc2ec2f4b.yaml", "repo_id": "qiskit", "token_count": 82 }
268
--- upgrade: - | The previously deprecated `NetworkX <https://networkx.org/>`_ converter methods for the class:`~.DAGCircuit` and class:`~.DAGDependency`classes: :meth:`.DAGCircuit.to_networkx`, :meth:`.DAGCircuit.from_networkx`, and :meth:`.DAGDependency.to_networkx` have been removed. These methods were originally deprecated as part of the 0.21.0 release. Qiskit has been using `rustworkx <https://qiskit.org/documentation/rustworkx/>`__ as its graph library since the qiskit-terra 0.12.0 release and since then the NetworkX converter function have been a lossy process. They were originally added so that users could leverage NetworkX's algorithms library to leverage functionality not present in :class:`~.DAGCircuit` and/or rustworkx. However, since that time both :class:`~.DAGCircuit` and rustworkx has matured and offers more functionality and the :class:`~.DAGCircuit` is tightly coupled to rustworkx for its operation and having these converter methods provided limited functionality and therefore have been removed.
qiskit/releasenotes/notes/0.23/remove-networkx-converters-0a7eccf6fa847975.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/remove-networkx-converters-0a7eccf6fa847975.yaml", "repo_id": "qiskit", "token_count": 341 }
269
--- upgrade: - | Updated the reference implementation :meth:`~.Sampler.run` to return only states with non-zero probabilities.
qiskit/releasenotes/notes/0.23/update-sampler-zero-filter-8bf0d721af4fbd17.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/update-sampler-zero-filter-8bf0d721af4fbd17.yaml", "repo_id": "qiskit", "token_count": 44 }
270
--- features: - | Added high-level-synthesis plugins for :class:`.LinearFunction` and for :class:`qiskit.quantum_info.Clifford`, extending the set of synthesis methods that can be called from :class:`~qiskit.transpiler.passes.HighLevelSynthesis` transpiler pass. For :class:`.LinearFunction` the available plugins are listed below: .. list-table:: :header-rows: 1 * - Plugin name - High-level synthesis plugin * - ``default`` - :class:`.DefaultSynthesisLinearFunction` * - ``kms`` - :class:`.KMSSynthesisLinearFunction` * - ``pmh`` - :class:`.PMHSynthesisLinearFunction` For :class:`qiskit.quantum_info.Clifford` the available plugins are listed below: .. list-table:: :header-rows: 1 * - Plugin name - High-level synthesis plugin * - ``default`` - :class:`.DefaultSynthesisClifford` * - ``ag`` - :class:`.AGSynthesisClifford` * - ``bm`` - :class:`.BMSynthesisClifford` * - ``greedy`` - :class:`.GreedySynthesisClifford` * - ``layers`` - :class:`.LayerSynthesisClifford` * - ``lnn`` - :class:`.LayerLnnSynthesisClifford` Please refer to :mod:`qiskit.synthesis` documentation for more information about each individual method. The following example illustrates some of the new plugins:: from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import LinearFunction from qiskit.quantum_info import Clifford from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig, HighLevelSynthesis # Create a quantum circuit with one linear function and one clifford qc1 = QuantumCircuit(3) qc1.cx(0, 1) qc1.swap(0, 2) lin_fun = LinearFunction(qc1) qc2 = QuantumCircuit(3) qc2.h(0) qc2.cx(0, 2) cliff = Clifford(qc2) qc = QuantumCircuit(4) qc.append(lin_fun, [0, 1, 2]) qc.append(cliff, [1, 2, 3]) # Choose synthesis methods that adhere to linear-nearest-neighbor connectivity hls_config = HLSConfig(linear_function=["kms"], clifford=["lnn"]) # Synthesize qct = HighLevelSynthesis(hls_config)(qc) print(qct.decompose())
qiskit/releasenotes/notes/0.24/add-hls-plugins-038388970ad43c55.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/add-hls-plugins-038388970ad43c55.yaml", "repo_id": "qiskit", "token_count": 1019 }
271
--- upgrade: - | The :meth:`.CouplingMap.__eq__`` method has been updated to check that the edge lists of the underlying graphs contain the same elements. Under the assumption that the underlying graphs are connected, this check additionally ensures that the graphs have the same number of nodes with the same labels. Any code using ``CouplingMap() == CouplingMap()`` to check object equality should be updated to ``CouplingMap() is CouplingMap()``.
qiskit/releasenotes/notes/0.24/coupling-map-eq-b0507b703d62a5f3.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/coupling-map-eq-b0507b703d62a5f3.yaml", "repo_id": "qiskit", "token_count": 127 }
272
--- fixes: - | Fixed a bug where :meth:`.PauliOp.adjoint` did not return a correct value for Paulis with complex coefficients, like ``PauliOp(Pauli("iX"))``. Fixed `#9433 <https://github.com/Qiskit/qiskit-terra/issues/9433>`.
qiskit/releasenotes/notes/0.24/fix-PauliOp-adjoint-a275876185df989f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/fix-PauliOp-adjoint-a275876185df989f.yaml", "repo_id": "qiskit", "token_count": 94 }
273
--- fixes: - | Fixed failure in using :func:`~qiskit.pulse.macros.measure` with :class:`.BackendV2` backends.
qiskit/releasenotes/notes/0.24/fix-macros-measure-with-backendV2-4354f00ab4f1cd3e.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/fix-macros-measure-with-backendV2-4354f00ab4f1cd3e.yaml", "repo_id": "qiskit", "token_count": 53 }
274
--- fixes: - | Fixed a bug in :func:`.generate_basic_approximations` where the inverse of the :class:`.SdgGate` was not correctly recognized as :class:`.SGate`. Fixed `#9585 <https://github.com/Qiskit/qiskit-terra/issues/9585>`__.
qiskit/releasenotes/notes/0.24/fix-sk-sdg-81ec87abe7af4a89.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/fix-sk-sdg-81ec87abe7af4a89.yaml", "repo_id": "qiskit", "token_count": 97 }
275
--- fixes: - | A bug has been fixed which had allowed broadcasting when a :class:`.PauliList` is initialized from :class:`.Pauli`\ s or labels. For instance, the code ``PauliList(["XXX", "Z"])`` now raises a ``ValueError`` rather than constructing the equivalent of ``PauliList(["XXX", "ZZZ"])``.
qiskit/releasenotes/notes/0.24/paulilist-do-not-broadcast-from-paulis-96de3832fba21b94.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/paulilist-do-not-broadcast-from-paulis-96de3832fba21b94.yaml", "repo_id": "qiskit", "token_count": 110 }
276
--- features: - | Improve the decomposition of multi-controlled Pauli-X and Pauli-Y rotations on :math:`n` controls to :math:`16n - 40` CX gates, for :math:`n \geq 4`. This improvement is based on `arXiv:2302.06377 <https://arxiv.org/abs/2302.06377>`__.
qiskit/releasenotes/notes/0.24/su2-synthesis-295ebf03d9033263.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/su2-synthesis-295ebf03d9033263.yaml", "repo_id": "qiskit", "token_count": 108 }
277
issues: - | Added support for taking absolute values of :class:`.ParameterExpression`\s. For example, the following is now possible:: from qiskit.circuit import QuantumCircuit, Parameter x = Parameter("x") circuit = QuantumCircuit(1) circuit.rx(abs(x), 0) bound = circuit.bind_parameters({x: -1})
qiskit/releasenotes/notes/0.25/add-abs-to-parameterexpression-347ffef62946b38b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/add-abs-to-parameterexpression-347ffef62946b38b.yaml", "repo_id": "qiskit", "token_count": 164 }
278
--- features: - | :meth:`.DAGCircuit.substitute_node` gained a ``propagate_condition`` keyword argument that is analogous to the same argument in :meth:`~.DAGCircuit.substitute_node_with_dag`. Setting this to ``False`` opts out of the legacy behavior of copying a condition on the ``node`` onto the new ``op`` that is replacing it. This option is ignored for general control-flow operations, which will never propagate their condition, nor accept a condition from another node. fixes: - | :meth:`.DAGCircuit.substitute_node` will no longer silently overwrite an existing condition on the given replacement ``op``. If ``propagate_condition`` is set to ``True`` (the default), a :exc:`.DAGCircuitError` will be raised instead.
qiskit/releasenotes/notes/0.25/dag-substitute-node-propagate-condition-898052b53edb1f17.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/dag-substitute-node-propagate-condition-898052b53edb1f17.yaml", "repo_id": "qiskit", "token_count": 235 }
279
--- fixes: - | When :func:`~qiskit.quantum_info.synthesis.qs_decomposition`, which does quantum Shannon decomposition, was called on trivial numeric unitaries that do not benefit from this decomposition, an unexpected error was raised. With this fix, such unitaries are detected and the equivalent circuit is returned without performing Shannon decomposition.
qiskit/releasenotes/notes/0.25/fix-1q-matrix-bug-in-quantum-shannon-decomposer-c99ce6509f03715b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/fix-1q-matrix-bug-in-quantum-shannon-decomposer-c99ce6509f03715b.yaml", "repo_id": "qiskit", "token_count": 100 }
280
--- fixes: - | Fixed plot legend error when your dataset has a zero value at first position. When one of your counts or distributions had a zero value at first position, the relative legend didn't show up. See `#10158 <https://github.com/Qiskit/qiskit-terra/issues/10158>` for more details.
qiskit/releasenotes/notes/0.25/fix-plot-legend-not-showing-up-3202bec143529e49.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/fix-plot-legend-not-showing-up-3202bec143529e49.yaml", "repo_id": "qiskit", "token_count": 92 }
281
--- fixes: - | Improve the type annotations on the :meth:`.QuantumCircuit.assign_parameters` method to reflect the change in return type depending on the ``inplace`` argument.
qiskit/releasenotes/notes/0.25/improve-quantum-circuit-assign-parameters-typing-70c9623405cbd420.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/improve-quantum-circuit-assign-parameters-typing-70c9623405cbd420.yaml", "repo_id": "qiskit", "token_count": 64 }
282
--- upgrade: - | Support for passing in lists of argument values to the :func:`~.transpile` function is removed. This functionality was deprecated as part of the 0.23.0 release and is now being removed. You are still able to pass in a list of :class:`~.QuantumCircuit` objects for the first positional argument, what has been removed is the broadcasting lists of the other arguments to each circuit in that input list. Removing this functionality was necessary to greatly reduce the overhead for parallel execution for transpiling multiple circuits at once. If you’re using this functionality currently you can call :func:`~.transpile` multiple times instead. For example if you were previously doing something like:: from qiskit.transpiler import CouplingMap from qiskit import QuantumCircuit from qiskit import transpile qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() cmaps = [CouplingMap.from_heavy_hex(d) for d in range(3, 15, 2)] results = transpile([qc] * 6, coupling_map=cmaps) instead you should now run something like:: from qiskit.transpiler import CouplingMap from qiskit import QuantumCircuit from qiskit import transpile qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() cmaps = [CouplingMap.from_heavy_hex(d) for d in range(3, 15, 2)] results = [transpile(qc, coupling_map=cm) for cm in cmap] You can also leverage :func:`~.parallel_map` or ``multiprocessing`` from the Python standard library if you want to run this in parallel.
qiskit/releasenotes/notes/0.25/remove-transpile-broadcast-1dfde28d508efa0d.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/remove-transpile-broadcast-1dfde28d508efa0d.yaml", "repo_id": "qiskit", "token_count": 623 }
283
--- features: - | A new module :mod:`qiskit.passmanager` is added. This module implements a generic pass manager and flow controllers, and provides infrastructure to manage execution of pass manager tasks. The pass manager is a base class and not aware of the input and output object types, and subclass must be created for a particular program type to optimize. The :mod:`qiskit.transpiler` module is also reorganized to rebuild the existing pass manager based off of the generic pass manager. See upgrade notes for more details. upgrade: - | One new base class for passes (:class:`.GenericPass`) and one for flow controllers (:class:`.BaseController`) are introduced in the :mod:`qiskit.passmanager` module. Because the flow controller is a collection of passes and a controller can be recursively nested into the task pipeline, new classes are designed with the idea of the composite pattern, and the interface class :class:`.passmanager.Task` is also introduced. This class defines the signature of a :meth:`.Task.execute` method. This unified design eliminates complexity of the conventional pass manager; the execution logic dispatch and task structure renormalization are no longer necessary, whom the :class:`.RunningPassManager` used to be responsible for. Existing flow controllers :class:`.FlowControllerLinear`, :class:`.ConditionalController`, and :class:`.DoWhileController` are now subclasses of the :class:`.BaseController`. Note that these controllers are no longer iterable, as they drop the implementation of :meth:`~object.__iter__` method; they are now only iterable in the context of a flow-controller execution, which threads the compilation state through after each inner task is executed. - | The :class:`.RunningPassManager` becomes largely an alias of :class:`.FlowControllerLinear`, and this class will be completely replaced with the flow controller in the feature release. This means the running pass manager becomes a stateless flow controller, and the pass manager framework consists of :class:`.BasePassManager` and :class:`.BaseController`. The pass manager is responsible for the construction of task pipeline, while the controller is responsible for the execution of associated tasks. Subclassing the :class:`.RunningPassManager` is no longer recommended. - | A new class :class:`.WorkflowStatus` is introduced to track the status of pass manager workflow. This portable object is created when the pass manager is run, and handed over to the underlying tasks. Such status was previously managed by the :class:`.RunningPassManager` with instance variables, however, now running pass manager becomes a controller object. - | The transpiler-specific (:func:`.transpile`) :class:`.transpiler.PassManager` is now a subclass of the :class:`.passmanager.BasePassManager`. There is no API break at public member level due to this class hierarchy change. - | A new exception :exc:`~qiskit.passmanager.PassManagerError` is introduced as the base class of exceptions raised during pass-manager execution. The transpiler-specific :class:`.transpile.PassManager` continues to raise :exc:`.TranspilerError`, which is now a subclass of :exc:`.PassManagerError`, for errors raised by specific tasks. A generic failure of the pass-manager machinery, typically indicating programmer error and not recoverable, will raise :exc:`.PassManagerError` for general pass managers, but :class:`.transpile.PassManager` will currently wrap this in its specific :exc:`.TranspilerError` for backwards compatibility. This wrapping will be removed in the future. - | Use of :class:`.FencedObject` in the pass manager framework is removed. These wrapper class cannot protect mutable object attribute from modification, and protection doesn't matter as long as the code is properly implemented; analysis passes should not modify an input IR, controllers should not update the property set, and so forth. Implementation of the proper code is the responsibility of pass manager developer. deprecations: - | The flow controller factory method :meth:`.FlowController.controller_factory` is deprecated along with :meth:`.FlowController.add_flow_controller` and :meth:`.FlowController.remove_flow_controller`, as we are also going to deprecate task construction with keyword arguments in the :meth:`.BasePassManager.append` method. Controllers must be explicitly instantiated and appended to the pass manager. For example, conventional syntax .. code-block:: python pm.append([task1, task2], condition=lambda x: x["value1"] > 10) must be replaced with .. code-block:: python controller = ConditionalController([task1, task2], condition=lambda x: x["value1"] > 10) pm.append(controller) The latter allows more precise control on the order of controllers especially when multiple keyword arguments are specified together, and allows for the construction of general flow controllers that may have more than one pipeline or do not take a single simple conditional function in their constructors. - | The :meth:`.FlowControllerLinear.append`, :meth:`.DoWhileController.append`, and :meth:`.ConditionalController.append` methods are all deprecated immediately. The construction of pass manager task pipeline is the role of :class:`.BasePassManager`, and individual flow controller do not need to implement method like this. For a flow controller, you should pass all the passes in one go directly to the constructor. - | The general attribute and variable name :code:`passes` is replaced with :code:`tasks` all over the :mod:`qiskit.passmanager` module. Note that a task must indicate a union of pass and controller, and the singular form `pass` conflicts with the Python keyword. In this sense, use of `tasks` is much preferable.
qiskit/releasenotes/notes/0.45/add-passmanager-module-3ae30cff52cb83f1.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.45/add-passmanager-module-3ae30cff52cb83f1.yaml", "repo_id": "qiskit", "token_count": 1627 }
284
--- deprecations: - | Deprecate duplicate gate methods on :class:`.QuantumCircuit`. The rule applied is that the method names reflect that gate names, e.g. the :class:`.CXGate` is added via :meth:`.QuantumCircuit.cx` and not :meth:`.QuantumCircuit.cnot`. The deprecations are: * :meth:`.QuantumCircuit.cnot` in favor of :meth:`.QuantumCircuit.cx` * :meth:`.QuantumCircuit.toffoli` in favor of :meth:`.QuantumCircuit.ccx` * :meth:`.QuantumCircuit.fredkin` in favor of :meth:`.QuantumCircuit.cswap` * :meth:`.QuantumCircuit.mct` in favor of :meth:`.QuantumCircuit.mcx` * :meth:`.QuantumCircuit.i` in favor of :meth:`.QuantumCircuit.id` Note that :meth:`.QuantumCircuit.i` is the only exception to the rule above, but since :meth:`.QuantumCircuit.id` more intuitively represents the identity and is used more, we chose it over its counterpart.
qiskit/releasenotes/notes/0.45/deprecate-duplicates-a871f83bbbe1c96f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.45/deprecate-duplicates-a871f83bbbe1c96f.yaml", "repo_id": "qiskit", "token_count": 342 }
285
--- fixes: - | Fix the coloring of the ``"iqx"`` and ``"iqx-dark"`` matplotlib color schemes, which previously drew the :class:`.RZGate`, :class:`.RZZGate`, (multi-)controlled :class:`.PhaseGate`\s and :class:`.iSwapGate` in the wrong color.
qiskit/releasenotes/notes/0.45/fix-iqx-colors-a744cea132896e53.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.45/fix-iqx-colors-a744cea132896e53.yaml", "repo_id": "qiskit", "token_count": 95 }
286
--- upgrade: - | Disables the use of :class:`.RemoveResetInZeroState` in the preset passmanagers. This better aligns circuits to the notion of arbitrary initial states unless explicitly set to zeros with resets.
qiskit/releasenotes/notes/0.45/keep-initial-resets-a5f75cb16c8edb57.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.45/keep-initial-resets-a5f75cb16c8edb57.yaml", "repo_id": "qiskit", "token_count": 67 }
287
upgrade: - | Removed the argument `qubit_channel_mapping` in :class:`qiskit.transpiler.passes.calibration.rzx_builder.RZXCalibrationBuilder`, which was deprecated in Qiskit 0.39 (released on Oct 2022, with qiskit-terra 0.22) - | Replaced the argument ``qobj[Qobj]`` in :meth:`qiskit.providers.aer.QasmSimulator.run()` with ``run_input[QuantumCircuit or Schedule or list]`` Here is an example to migrate your code:: # Importing necessary Qiskit libraries from qiskit import transpile, QuantumCircuit from qiskit.aer import QasmSimulator # Defining the Quantum Circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() # Transpile the circuit to optimize for the target simulator simulator = QasmSimulator() transpiled_circuit = transpile(qc, simulator) # Run the simulation job = simulator.run(transpiled_circuit, shots=1024) # Get the simulation result result = job.result() All these were deprecated since 0.22 (released on October 13, 2022) and now they are removed.
qiskit/releasenotes/notes/0.45/remove-deprecated-code-in-0.22.0-139fa09ee0cc6df9.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.45/remove-deprecated-code-in-0.22.0-139fa09ee0cc6df9.yaml", "repo_id": "qiskit", "token_count": 419 }
288
--- fixes: - | The setter for :attr:`.SparsePauliOp.paulis` will now correctly reject attempts to set the attribute with incorrectly shaped data, rather than silently allowing an invalid object to be created. See `#10384 <https://github.com/Qiskit/qiskit-terra/issues/10384>`__.
qiskit/releasenotes/notes/0.45/sparse-pauli-op-constraint-pauli-setter-52f6f89627d1937c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.45/sparse-pauli-op-constraint-pauli-setter-52f6f89627d1937c.yaml", "repo_id": "qiskit", "token_count": 96 }
289
--- upgrade: - | The jupyter cell magic ``%%qiskit_progress_bar`` from ``qiskit.tools.jupyter`` has been changed to a line magic. This was done to better reflect how the magic is used and how it works. If you were using the ``%%qiskit_progress_bar`` cell magic in an existing notebook, you will have to update this to be a line magic by changing it to be ``%qiskit_progress_bar`` instead. Everything else should behave identically.
qiskit/releasenotes/notes/0.9/jupyter-progressbar-api-change-6f60185bc71fc5f0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.9/jupyter-progressbar-api-change-6f60185bc71fc5f0.yaml", "repo_id": "qiskit", "token_count": 149 }
290
--- fixes: - | Fixed an issue in the ``text`` circuit drawer when displaying operations that were not :class:`.circuit.instruction.Instruction` class. These operations would cause the drawer to fail. Examples were :class:`.Clifford` and :class:`.AnnotatedOperation`. features_visualization: - | The ``text`` and ``mpl`` outputs for the :meth:`.QuantumCircuit.draw` and :func:`.circuit_drawer` circuit drawer functions will now display detailed information for operations of :class:`.AnnotatedOperation`. If the :attr:`.AnnotatedOperation.modifiers` contains a :class:`.ControlModifier`, the operation will be displayed the same way as controlled gates. If the :class:`.InverseModifier` or :class:`.PowerModifier` is used, these will be indicated with the base operation name. For example: .. plot:: :include-source: from qiskit.circuit import ( AnnotatedOperation, ControlModifier, PowerModifier, InverseModifier, QuantumCircuit ) from qiskit.circuit.library import SGate annotated_op = AnnotatedOperation(SGate(), [PowerModifier(3.4), ControlModifier(3), InverseModifier()]) qc = QuantumCircuit(4) qc.append(annotated_op, range(4)) qc.draw("mpl")
qiskit/releasenotes/notes/1.0/add-annotated-to-drawers-8bcc3a069dd981ad.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/add-annotated-to-drawers-8bcc3a069dd981ad.yaml", "repo_id": "qiskit", "token_count": 482 }
291
--- upgrade_circuits: - | To support a more compact in-memory representation, the :class:`.QuantumCircuit` class is now limited to supporting a maximum of ``2^32 (=4,294,967,296)`` qubits and clbits, for each of these two bit types (the limit is not combined). The number of unique sequences of indices used in :attr:`.CircuitInstruction.qubits` and :attr:`.CircuitInstruction.clbits` is also limited to ``2^32`` for instructions added to a single circuit. features_circuits: - | The :class:`.QuantumCircuit` class now internally performs interning for the ``qubits`` and ``clbits`` of the :class:`.CircuitInstruction` instances that it stores, resulting in a potentially significant reduction in memory footprint, especially for large circuits.
qiskit/releasenotes/notes/1.0/bit-interning-35da0aaa76aa7fc5.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/bit-interning-35da0aaa76aa7fc5.yaml", "repo_id": "qiskit", "token_count": 244 }
292
--- fixes: - | Fixed an issue with the :class:`.Barrier` class. When adding a :class:`.Barrier` instance to a :class:`.QuantumCircuit` with the :meth:`.QuantumCircuit.append` method, previously there was no validation that the size of the barrier matched the qargs specified.
qiskit/releasenotes/notes/1.0/fix-barrier-arg-list-check-ff69f37ede6bdf6c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/fix-barrier-arg-list-check-ff69f37ede6bdf6c.yaml", "repo_id": "qiskit", "token_count": 94 }
293
--- fixes: - | Fixed compatibility of :class:`.DynamicalDecoupling` and :class:`.PadDynamicalDecoupling` with circuits that have a parameterized global phase. Fixed `#10569 <https://github.com/Qiskit/qiskit/issues/10569>`__.
qiskit/releasenotes/notes/1.0/fix-param-global-phase-31547267f6124552.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/fix-param-global-phase-31547267f6124552.yaml", "repo_id": "qiskit", "token_count": 90 }
294
--- features_transpiler: - | Added a new function, :func:`.high_level_synthesis_plugin_names`, that can be used to get the list of installed high level synthesis plugins for a given operation name.
qiskit/releasenotes/notes/1.0/high-level-synthesis-plugin-list-beff523921c4c4eb.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/high-level-synthesis-plugin-list-beff523921c4c4eb.yaml", "repo_id": "qiskit", "token_count": 66 }
295
--- features_qasm: - | The OpenQASM 3 exporter (see :func:`~.qasm3.dump` and :func:`~.qasm3.dumps` functions in :mod:`qiskit.qasm3`) now supports the stabilized syntax of the ``switch`` statement in OpenQASM 3 by default. The pre-certification syntax of the ``switch`` statement is still available by using the :attr:`.ExperimentalFeatures.SWITCH_CASE_V1` flag in the ``experimental`` argument of the exporter. There is no feature flag required for the stabilized syntax, but if you are interfacing with other tooling that is not yet updated, you may need to pass the experimental flag. The syntax of the stabilized form is slightly different with regards to terminating ``break`` statements (no longer required nor permitted), and multiple cases are now combined into a single ``case`` line, rather than using C-style fall-through. For more detail, see `the OpenQASM 3 documentation on the switch-case construct <https://openqasm.com/language/classical.html#the-switch-statement>`__.
qiskit/releasenotes/notes/1.0/qasm3-stable-switch-61a10036d1587778.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/qasm3-stable-switch-61a10036d1587778.yaml", "repo_id": "qiskit", "token_count": 310 }
296
--- upgrade_circuits: - | Removed the ``qiskit.extensions`` module, which has been pending deprecation since the 0.45 release and has been fully deprecated in the 0.46 release. The following operations from this module are available in :mod:`qiskit.circuit.library`: * :class:`~.library.DiagonalGate`, * :class:`~.library.HamiltonianGateGate`, * :class:`~.library.Initialize`, * :class:`~.library.Isometry`, * :class:`~.library.generalized_gates.mcg_up_diag.MCGupDiag`, * :class:`~.library.UCGate`, * :class:`~.library.UCPauliRotGate`, * :class:`~.library.UCRXGate`, * :class:`~.library.UCRYGate`, * :class:`~.library.UCRZGate`, * :class:`~.library.UnitaryGate`. The following objects have been removed: * ``SingleQubitUnitary`` (instead use :class:`.library.UnitaryGate`), * ``Snapshot`` (superseded by Aer's save instructions), * ``ExtensionError``, along with the following circuit methods: * ``QuantumCircuit.snapshot``, * ``QuantumCircuit.squ``, * ``QuantumCircuit.diagonal``, * ``QuantumCircuit.hamiltonian``, * ``QuantumCircuit.isometry`` and ``QuantumCircuit.iso``, * ``QuantumCircuit.uc``, * ``QuantumCircuit.ucrx``, * ``QuantumCircuit.ucry``, * ``QuantumCircuit.ucrz``. These operations can still be performed by appending the appropriate instruction to a quantum circuit. - | Removed deprecated, duplicated :class:`.QuantumCircuit` methods. These include: * ``QuantumCircuit.cnot``, instead use :meth:`.QuantumCircuit.cx`, * ``QuantumCircuit.toffoli``, instead use :meth:`.QuantumCircuit.ccx`, * ``QuantumCircuit.fredkin``, instead use :meth:`.QuantumCircuit.cswap`, * ``QuantumCircuit.mct``, instead use :meth:`.QuantumCircuit.mcx`, * ``QuantumCircuit.i``, instead use :meth:`.QuantumCircuit.id`.
qiskit/releasenotes/notes/1.0/remove-extensions-ce520ba419c93c58.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/remove-extensions-ce520ba419c93c58.yaml", "repo_id": "qiskit", "token_count": 773 }
297
--- fixes: - | Fixed an issue in :func:`.unitary_to_gate_sequence` which caused unitary decomposition in the RR basis to emit two R gates in some cases where the matrix can be expressed as a single R gate. Previously, in those cases you would get two R gates with the same phi parameter. Now, they are combined into one.
qiskit/releasenotes/notes/1.0/rr-decomposition-synthesis-70eb88ada9305916.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.0/rr-decomposition-synthesis-70eb88ada9305916.yaml", "repo_id": "qiskit", "token_count": 102 }
298
--- features: - | The implementation :class:`~.BackendSamplerV2` of :class:`~.BaseSamplerV2` was added. This sampler supports :class:`~.BackendV1` and :class:`~.BackendV2` that allow ``memory`` option to compute bitstrings. .. code-block:: python import numpy as np from qiskit import transpile from qiskit.circuit.library import IQP from qiskit.primitives import BackendSamplerV2 from qiskit.providers.fake_provider import Fake7QPulseV1 from qiskit.quantum_info import random_hermitian backend = Fake7QPulseV1() sampler = BackendSamplerV2(backend=backend) n_qubits = 5 mat = np.real(random_hermitian(n_qubits, seed=1234)) circuit = IQP(mat) circuit.measure_all() isa_circuit = transpile(circuit, backend=backend, optimization_level=1) job = sampler.run([isa_circuit], shots=100) result = job.result() print(f"> bitstrings: {result[0].data.meas.get_bitstrings()}") print(f"> counts: {result[0].data.meas.get_counts()}") print(f"> Metadata: {result[0].metadata}")
qiskit/releasenotes/notes/1.1/add-backend-sampler-v2-5e40135781eebc7f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/1.1/add-backend-sampler-v2-5e40135781eebc7f.yaml", "repo_id": "qiskit", "token_count": 458 }
299