Example #1
0
    def check_installed() -> None:
        """Checks that PySCF is actually installed.

        Raises:
            MissingOptionalLibraryError: If PySCF is not installed.
        """
        try:
            spec = importlib.util.find_spec("pyscf")
            if spec is not None:
                return
        except Exception as ex:  # pylint: disable=broad-except
            logger.debug("PySCF check error %s", str(ex))
            raise MissingOptionalLibraryError(
                libname="PySCF",
                name="PySCFDriver",
                pip_install="pip install 'qiskit-nature[pyscf]'",
                msg="See https://pyscf.org/install.html",
            ) from ex

        raise MissingOptionalLibraryError(
            libname="PySCF",
            name="PySCFDriver",
            pip_install="pip install 'qiskit-nature[pyscf]'",
            msg="See https://pyscf.org/install.html",
        )
Example #2
0
    def __init__(
        self,
        maxiter: int = 1000,
        maxfail: int = 10,
        maxmp: int = None,
        verbose: bool = False,
    ) -> None:
        """
        Args:
            maxiter: Maximum number of function evaluations.
            maxmp: Maximum number of  model points requested for the local fit.
                 Default = 2 * number of parameters + 6 set to this value when None.
            maxfail: Maximum number of failures to improve the solution. Stops the algorithm
                    after maxfail is reached.
            verbose: Provide verbose (debugging) output.

        Raises:
            MissingOptionalLibraryError: scikit-quant or SQSnobFit not installed
        """
        if not _HAS_SKQUANT:
            raise MissingOptionalLibraryError(
                libname="scikit-quant",
                name="SNOBFIT",
                pip_install="pip install scikit-quant")
        if not _HAS_SKSNOBFIT:
            raise MissingOptionalLibraryError(
                libname="SQSnobFit",
                name="SNOBFIT",
                pip_install="pip install SQSnobFit")
        super().__init__()
        self._maxiter = maxiter
        self._maxfail = maxfail
        self._maxmp = maxmp
        self._verbose = verbose
Example #3
0
    def to_networkx(self):
        """Returns a copy of the DAGDependency in networkx format."""
        # For backwards compatibility, return networkx structure from terra 0.12
        # where DAGNodes instances are used as indexes on the networkx graph.
        warnings.warn(
            "The to_networkx() method is deprecated and will be removed in a future release.",
            DeprecationWarning,
            stacklevel=2,
        )

        try:
            import networkx as nx
        except ImportError as ex:
            raise MissingOptionalLibraryError(
                libname="Networkx",
                name="DAG dependency",
                pip_install="pip install networkx",
            ) from ex
        dag_networkx = nx.MultiDiGraph()

        for node in self.get_nodes():
            dag_networkx.add_node(node)
        for node in self.topological_nodes():
            for source_id, dest_id, edge in self.get_in_edges(node.node_id):
                dag_networkx.add_edge(self.get_node(source_id), self.get_node(dest_id), **edge)
        return dag_networkx
Example #4
0
    def __init__(self, expression: str, name: str = None) -> None:
        """
        Args:
            expression (str): The logical expression string.
            name (str): Optional. Instruction gate name. Otherwise part of
                        the expression is going to be used.

        Raises:
            MissingOptionalLibraryError: If tweedledum is not installed. Tweedledum is required.
        """
        if not HAS_TWEEDLEDUM:
            raise MissingOptionalLibraryError(
                libname="tweedledum",
                name="BooleanExpression compiler",
                pip_install="pip install tweedledum",
            )
        from tweedledum import BoolFunction

        self._tweedledum_bool_expression = BoolFunction.from_expression(
            expression)

        short_expr_for_name = (expression[:10] +
                               "...") if len(expression) > 13 else expression
        num_qubits = (self._tweedledum_bool_expression.num_outputs() +
                      self._tweedledum_bool_expression.num_inputs())
        super().__init__(name or short_expr_for_name,
                         num_qubits=num_qubits,
                         params=[])
Example #5
0
def _check_gurobipy_is_installed(name: str):
    if not _HAS_GUROBI:
        raise MissingOptionalLibraryError(
            libname="GUROBI",
            name=name,
            pip_install="pip install qiskit-optimization[gurobi]",
        )
Example #6
0
    def solve_cpx_problem(self,
                          time_limit: float = 60,
                          threads: int = None) -> str:
        """Solve the BIP problem using CPLEX.

        Args:
            time_limit:
                Time limit (seconds) given to CPLEX.

            threads:
                Number of threads to be allowed for CPLEX to use.

        Returns:
            Status string that CPLEX returned after solving the BIP problem.

        Raises:
            MissingOptionalLibraryError: If CPLEX is not installed
        """
        if not HAS_CPLEX:
            raise MissingOptionalLibraryError(
                libname="CPLEX",
                name="CplexOptimizer",
                pip_install="pip install cplex",
            )
        self.problem.set_time_limit(time_limit)
        if threads is not None:
            self.problem.context.cplex_parameters.threads = threads
        self.problem.context.cplex_parameters.randomseed = 777

        self.solution = self.problem.solve()

        status = self.problem.solve_details.status
        logger.info("BIP solution status: %s", status)
        return status
Example #7
0
def generate_latex_label(label):
    """Convert a label to a valid latex string."""
    if not HAS_PYLATEX:
        raise MissingOptionalLibraryError(
            libname="pylatexenc",
            name="the latex and latex_source circuit drawers",
            pip_install="pip install pylatexenc",
        )

    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 from_dimacs_file(cls, filename: str):
        """Create a BooleanExpression from the string in the DIMACS format.
        Args:
            filename: A file in DIMACS format.

        Returns:
            BooleanExpression: A gate for the input string

        Raises:
            MissingOptionalLibraryError: If tweedledum is not installed. Tweedledum is required.
            FileNotFoundError: If filename is not found.
        """
        if not HAS_TWEEDLEDUM:
            raise MissingOptionalLibraryError(
                libname='tweedledum',
                name='BooleanExpression compiler',
                pip_install='pip install tweedledum')
        from tweedledum import BoolFunction

        expr_obj = cls.__new__(cls)
        if not isfile(filename):
            raise FileNotFoundError('The file %s does not exists.' % filename)
        expr_obj._tweedledum_bool_expression = BoolFunction.from_dimacs_file(filename)

        num_qubits = (expr_obj._tweedledum_bool_expression.num_inputs() +
                      expr_obj._tweedledum_bool_expression.num_outputs())
        super(BooleanExpression, expr_obj).__init__(  # pylint: disable=no-value-for-parameter
            name=basename(filename), num_qubits=num_qubits, params=[])
        return expr_obj
Example #9
0
    def _mpl(graph: PyGraph, self_loop: bool, **kwargs):
        """
        Auxiliary function for drawing the lattice using matplotlib.

        Args:
            graph : graph to be drawn.
            self_loop : Draw self-loops, which are edges connecting a node to itself.
            **kwargs : Kwargs for drawing the lattice.

        Raises:
            MissingOptionalLibraryError: Requires matplotlib.
        """
        if not HAS_MATPLOTLIB:
            raise MissingOptionalLibraryError(
                libname="Matplotlib", name="_mpl", pip_install="pip install matplotlib"
            )
        from matplotlib import pyplot as plt

        if not self_loop:
            self_loops = [(i, i) for i in range(graph.num_nodes()) if graph.has_edge(i, i)]
            graph.remove_edges_from(self_loops)

        mpl_draw(
            graph=graph,
            **kwargs,
        )
        plt.draw()
    def __init__(self,
                 num_cuts: int,
                 sort_cuts: bool = True,
                 unique_cuts: bool = True,
                 seed: int = 0):
        """
        Args:
            num_cuts: Number of cuts to generate.
            sort_cuts: True if sort cuts by their values.
            unique_cuts: The solve method returns only unique cuts, thus there may be less cuts
                than ``num_cuts``.
            seed: A seed value for the random number generator.

        Raises:
            MissingOptionalLibraryError: CVXPY is not installed.
        """
        if not _HAS_CVXPY:
            raise MissingOptionalLibraryError(
                libname="CVXPY",
                name="GoemansWilliamsonOptimizer",
                pip_install="pip install 'qiskit-optimization[cvxpy]'")
        super().__init__()

        self._num_cuts = num_cuts
        self._sort_cuts = sort_cuts
        self._unique_cuts = unique_cuts
        np.random.seed(seed)
    def __init__(
            self,
            tickers: Optional[Union[str, List[str]]] = None,
            start: datetime.datetime = datetime.datetime(2016, 1, 1),
            end: datetime.datetime = datetime.datetime(2016, 1, 30),
    ) -> None:
        """
        Initializer
        Args:
            tickers: tickers
            start: start time
            end: end time
        Raises:
            MissingOptionalLibraryError: YFinance not installed
        """
        super().__init__()
        if not _HAS_YFINANCE:
            raise MissingOptionalLibraryError(
                libname="YFinance",
                name="YahooDataProvider",
                pip_install="pip install yfinance",
            )
        self._tickers = None  # type: Optional[Union[str, List[str]]]
        tickers = tickers if tickers is not None else []
        if isinstance(tickers, list):
            self._tickers = tickers
        else:
            self._tickers = tickers.replace("\n", ";").split(";")
        self._n = len(self._tickers)

        self._tickers = tickers
        self._start = start.strftime("%Y-%m-%d")
        self._end = end.strftime("%Y-%m-%d")
        self._data = []
    def __init__(self,
                 tickers: Optional[Union[str, List[str]]] = None,
                 start: datetime.datetime = datetime.datetime(2016, 1, 1),
                 end: datetime.datetime = datetime.datetime(2016, 1, 30),
                 seed: Optional[int] = None) -> None:
        """
        Initializer
        Args:
            tickers: tickers
            start: first data point
            end: last data point precedes this date
            seed: shall a seed be used?
        Raises:
            MissingOptionalLibraryError: Pandas not installed
        """
        super().__init__()
        if not _HAS_PANDAS:
            raise MissingOptionalLibraryError(libname='Pandas',
                                              name='RandomDataProvider',
                                              pip_install='pip install pandas')
        tickers = tickers if tickers is not None else ["TICKER1", "TICKER2"]
        if isinstance(tickers, list):
            self._tickers = tickers
        else:
            self._tickers = tickers.replace('\n', ';').split(";")
        self._n = len(self._tickers)

        self._start = start
        self._end = end
        self._seed = seed
Example #13
0
    def __init__(
        self,
        token: Optional[str] = None,
        tickers: Optional[Union[str, List[str]]] = None,
        start: datetime.datetime = datetime.datetime(2016, 1, 1),
        end: datetime.datetime = datetime.datetime(2016, 1, 30)
    ) -> None:
        """
        Initializer
        Args:
            token: quandl access token, which is not needed, strictly speaking
            tickers: tickers
            start: start time
            end: end time
         Raises:
            MissingOptionalLibraryError: Quandl not installed
        """
        super().__init__()
        if not _HAS_QUANDL:
            raise MissingOptionalLibraryError(libname='Quandl',
                                              name='WikipediaDataProvider',
                                              pip_install='pip install quandl')
        self._tickers = None  # type: Optional[Union[str, List[str]]]
        tickers = tickers if tickers is not None else []
        if isinstance(tickers, list):
            self._tickers = tickers
        else:
            self._tickers = tickers.replace('\n', ';').split(";")
        self._n = len(self._tickers)

        self._token = token
        self._tickers = tickers
        self._start = start.strftime('%Y-%m-%d')
        self._end = end.strftime('%Y-%m-%d')
        self._data = []
Example #14
0
    def draw(
        self,
        result: Optional[Union[OptimizationResult, np.ndarray]] = None,
        pos: Optional[Dict[int, np.ndarray]] = None,
    ) -> None:
        """Draw a graph with the result. When the result is None, draw an original graph without
        colors.

        Args:
            result: The calculated result for the problem
            pos: The positions of nodes
        Raises:
            MissingOptionalLibraryError: if matplotlib is not installed.
        """
        if not _HAS_MATPLOTLIB:
            raise MissingOptionalLibraryError(
                libname="matplotlib",
                name="GraphOptimizationApplication",
                pip_install="pip install 'qiskit-optimization[matplotlib]'",
            )

        if result is None:
            nx.draw(self._graph, pos=pos, with_labels=True)
        else:
            self._draw_result(result, pos)
Example #15
0
    def visit_FunctionDef(self, node):
        """The function definition should have type hints"""
        if HAS_TWEEDLEDUM:
            from tweedledum.classical import LogicNetwork  # pylint: disable=no-name-in-module
        else:
            raise MissingOptionalLibraryError(
                libname='tweedledum',
                name='classical function compiler',
                pip_install='pip install tweedledum')
        if node.returns is None:
            raise ClassicalFunctionParseError("return type is needed")
        scope = {
            'return': (node.returns.id, None),
            node.returns.id: ('type', None)
        }

        # Extend scope with the decorator's names
        scope.update({
            decorator.id: ('decorator', None)
            for decorator in node.decorator_list
        })

        self.scopes.append(scope)
        self._network = LogicNetwork()
        self.extend_scope(node.args)
        return super().generic_visit(node)
Example #16
0
def get_unique_backends():
    """Gets the unique backends that are available.

    Returns:
        list: Unique available backends.

    Raises:
        QiskitError: No backends available.
        MissingOptionalLibraryError: If qiskit-ibmq-provider is not installed
    """
    try:
        from qiskit.providers.ibmq import IBMQ
    except ImportError as ex:
        raise MissingOptionalLibraryError(
            libname="qiskit-ibmq-provider",
            name="get_unique_backends",
            pip_install="pip install qiskit-ibmq-provider",
        ) from ex
    backends = []
    for provider in IBMQ.providers():
        for backend in provider.backends():
            backends.append(backend)
    unique_hardware_backends = []
    unique_names = []
    for back in backends:
        if back.name() not in unique_names and not back.configuration().simulator:
            unique_hardware_backends.append(back)
            unique_names.append(back.name())
    if not unique_hardware_backends:
        raise QiskitError("No backends available.")
    return unique_hardware_backends
Example #17
0
    def _ridge(a: np.ndarray,
               c: np.ndarray,
               lambda_: float = 1.,
               lambda1: float = 1e-4,
               lambda4: float = 1e-1,
               tol_search: float = 1e-8,
               fit_intercept: bool = True,
               normalize: bool = False,
               copy_a: bool = True,
               max_iter: int = 1000,
               tol: float = 0.0001,
               solver: str = 'auto',
               random_state: Optional[int] = None) -> Tuple[float, np.ndarray]:
        """
        Ridge Regression with automatic search for a good regularization term lambda
        x_lambda = arg min{||Ax-C||^2 + lambda*||x||_2^2} (3)
        `Scikit Learn Ridge Regression
        <https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html>`
        Args:
            a: see (1) and (2)
            c: see (1) and (2)
            lambda_ : regularization parameter used if auto_search = False
            lambda1: left starting point for L-curve corner search
            lambda4: right starting point for L-curve corner search
            tol_search: termination threshold for regularization parameter search
            fit_intercept: if True calculate intercept
            normalize: deprecated if fit_intercept=False, if True normalize A for regression
            copy_a: if True A is copied, else overwritten
            max_iter: max. number of iterations if solver is CG
            tol: precision of the regression solution
            solver: solver {‘auto’, ‘svd’, ‘cholesky’, ‘lsqr’, ‘sparse_cg’, ‘sag’, ‘saga’}
            random_state: seed for the pseudo random number generator used when data is shuffled

        Returns:
           regularization coefficient, solution to the regularization inverse problem

        Raises:
            MissingOptionalLibraryError: scikit-learn not installed

        """
        try:
            from sklearn.linear_model import Ridge
        except ImportError as ex:
            raise MissingOptionalLibraryError(
                libname='scikit-learn',
                name='_ridge',
                pip_install='pip install scikit-learn') from ex

        reg = Ridge(alpha=lambda_, fit_intercept=fit_intercept, normalize=normalize, copy_X=copy_a,
                    max_iter=max_iter,
                    tol=tol, solver=solver, random_state=random_state)

        def reg_method(a, c, alpha):
            reg.set_params(alpha=alpha)
            reg.fit(a, c)
            return reg.coef_

        lambda_mc, x_mc = NaturalGradient._reg_term_search(a, c, reg_method, lambda1=lambda1,
                                                           lambda4=lambda4, tol=tol_search)
        return lambda_mc, np.transpose(x_mc)
Example #18
0
    def __init__(self, source, name=None):
        """Creates a ``ClassicalFunction`` from Python source code in ``source``.

        The code should be a single function with types.

        Args:
            source (str): Python code with type hints.
            name (str): Optional. Default: "*classicalfunction*". ClassicalFunction name.

        Raises:
            MissingOptionalLibraryError: If tweedledum is not installed.
            QiskitError: If source is not a string.
        """
        if not isinstance(source, str):
            raise QiskitError(
                'ClassicalFunction needs a source code as a string.')
        if not HAS_TWEEDLEDUM:
            raise MissingOptionalLibraryError(
                libname='tweedledum',
                name='classical function compiler',
                pip_install='pip install tweedledum')
        self._ast = ast.parse(source)
        self._network = None
        self._scopes = None
        self._args = None
        self._truth_table = None
        super().__init__(name or '*classicalfunction*',
                         num_qubits=sum([qreg.size for qreg in self.qregs]),
                         params=[])
    def __init__(self, n_features: int = 1, n_out: int = 1) -> None:
        """
        Args:
            n_features: Dimension of input data vector.
            n_out: Dimension of the discriminator's output vector.

        Raises:
            MissingOptionalLibraryError: Pytorch not installed
        """
        super().__init__()
        if not _HAS_TORCH:
            raise MissingOptionalLibraryError(
                libname='Pytorch',
                name='PyTorchDiscriminator',
                pip_install="pip install 'qiskit-meachine-learning[torch]'")

        self._n_features = n_features
        self._n_out = n_out
        # discriminator_net: torch.nn.Module or None, Discriminator network.
        # pylint: disable=import-outside-toplevel
        from ._pytorch_discriminator_net import DiscriminatorNet
        self._discriminator = DiscriminatorNet(self._n_features, self._n_out)
        # optimizer: torch.optim.Optimizer or None, Optimizer initialized w.r.t
        # discriminator network parameters.
        self._optimizer = optim.Adam(self._discriminator.parameters(), lr=1e-5, amsgrad=True)

        self._ret = {}  # type: Dict[str, Any]
    def __init__(self, max_evals: int = 1000) -> None:  # pylint: disable=unused-argument
        """
        Args:
            max_evals: Maximum allowed number of function evaluations.

        Raises:
            MissingOptionalLibraryError: NLopt library not installed.
        """
        if not _HAS_NLOPT:
            raise MissingOptionalLibraryError(
                libname='nlopt',
                name='NLoptOptimizer',
                msg='See https://qiskit.org/documentation/apidoc/'
                'qiskit.aqua.components.optimizers.nlopts.html'
                ' for installation information')

        super().__init__()
        for k, v in list(locals().items()):
            if k in self._OPTIONS:
                self._options[k] = v

        self._optimizer_names = {
            NLoptOptimizerType.GN_CRS2_LM: nlopt.GN_CRS2_LM,
            NLoptOptimizerType.GN_DIRECT_L_RAND: nlopt.GN_DIRECT_L_RAND,
            NLoptOptimizerType.GN_DIRECT_L: nlopt.GN_DIRECT_L,
            NLoptOptimizerType.GN_ESCH: nlopt.GN_ESCH,
            NLoptOptimizerType.GN_ISRES: nlopt.GN_ISRES,
        }
Example #21
0
def qasm_widget(circuit: QuantumCircuit) -> wid.VBox:
    """Generate a QASM widget with header for a quantum circuit.

    Args:
        circuit: Input quantum circuit.

    Returns:
        Output widget.

    Raises:
        MissingOptionalLibraryError: If pygments is not installed
    """
    if not HAS_PYGMENTS:
        raise MissingOptionalLibraryError(
            libname="pygments>2.4",
            name="qasm_widget",
            pip_install="pip install pygments",
        )
    qasm_code = circuit.qasm()
    code = pygments.highlight(qasm_code, OpenQASMLexer(), HtmlFormatter())

    html_style = HtmlFormatter(
        style=QasmHTMLStyle).get_style_defs(".highlight")

    code_style = ("""
    <style>
     .highlight
                {
                    font-family: monospace;
                    font-size: 14px;
                    line-height: 1.7em;
                }
     .highlight .err { color: #000000; background-color: #FFFFFF }
    %s
    </style>
    """ % html_style)

    out = wid.HTML(
        code_style + code,
        layout=wid.Layout(max_height="500px",
                          height="auto",
                          overflow="scroll scroll"),
    )

    out_label = wid.HTML(
        f"<p style='{head_style}'>OpenQASM</p>",
        layout=wid.Layout(margin="0px 0px 10px 0px"),
    )

    qasm = wid.VBox(
        children=[out_label, out],
        layout=wid.Layout(height="auto",
                          max_height="500px",
                          width="60%",
                          margin="0px 0px 0px 20px"),
    )

    qasm._code_length = len(qasm_code.split("\n"))
    return qasm
Example #22
0
def plot_bloch_multivector(state, title="", figsize=None, *, rho=None, reverse_bits=False):
    """Plot the Bloch sphere.

    Plot a sphere, axes, the Bloch vector, and its projections onto each axis.

    Args:
        state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
        title (str): a string that represents the plot title
        figsize (tuple): Has no effect, here for compatibility only.
        reverse_bits (bool): If True, plots qubits following Qiskit's convention [Default:False].

    Returns:
        matplotlib.Figure:
            A matplotlib figure instance.

    Raises:
        MissingOptionalLibraryError: Requires matplotlib.
        VisualizationError: if input is not a valid N-qubit state.

    Example:
        .. jupyter-execute::

            from qiskit import QuantumCircuit
            from qiskit.quantum_info import Statevector
            from qiskit.visualization import plot_bloch_multivector
            %matplotlib inline

            qc = QuantumCircuit(2)
            qc.h(0)
            qc.cx(0, 1)

            state = Statevector.from_instruction(qc)
            plot_bloch_multivector(state, title="New Bloch Multivector", reverse_bits=False)
    """
    if not HAS_MATPLOTLIB:
        raise MissingOptionalLibraryError(
            libname="Matplotlib",
            name="plot_bloch_multivector",
            pip_install="pip install matplotlib",
        )
    from matplotlib import get_backend
    from matplotlib import pyplot as plt

    # Data
    bloch_data = (
        _bloch_multivector_data(state)[::-1] if reverse_bits else _bloch_multivector_data(state)
    )
    num = len(bloch_data)
    width, height = plt.figaspect(1 / num)
    fig = plt.figure(figsize=(width, height))
    for i in range(num):
        pos = num - 1 - i if reverse_bits else i
        ax = fig.add_subplot(1, num, i + 1, projection="3d")
        plot_bloch_vector(bloch_data[i], "qubit " + str(pos), ax=ax, figsize=figsize)
    fig.suptitle(title, fontsize=16)
    if get_backend() in ["module://ipykernel.pylab.backend_inline", "nbAgg"]:
        plt.close(fig)
    return fig
Example #23
0
def plot_bloch_vector(bloch, title="", ax=None, figsize=None, coord_type="cartesian"):
    """Plot the Bloch sphere.

    Plot a sphere, axes, the Bloch vector, and its projections onto each axis.

    Args:
        bloch (list[double]): array of three elements where [<x>, <y>, <z>] (Cartesian)
            or [<r>, <theta>, <phi>] (spherical in radians)
            <theta> is inclination angle from +z direction
            <phi> is azimuth from +x direction
        title (str): a string that represents the plot title
        ax (matplotlib.axes.Axes): An Axes to use for rendering the bloch
            sphere
        figsize (tuple): Figure size in inches. Has no effect is passing ``ax``.
        coord_type (str): a string that specifies coordinate type for bloch
            (Cartesian or spherical), default is Cartesian

    Returns:
        Figure: A matplotlib figure instance if ``ax = None``.

    Raises:
        MissingOptionalLibraryError: Requires matplotlib.

    Example:
        .. jupyter-execute::

           from qiskit.visualization import plot_bloch_vector
           %matplotlib inline

           plot_bloch_vector([0,1,0], title="New Bloch Sphere")
    """
    if not HAS_MATPLOTLIB:
        raise MissingOptionalLibraryError(
            libname="Matplotlib",
            name="plot_bloch_vector",
            pip_install="pip install matplotlib",
        )
    from qiskit.visualization.bloch import Bloch
    from matplotlib import get_backend
    from matplotlib import pyplot as plt

    if figsize is None:
        figsize = (5, 5)
    B = Bloch(axes=ax)
    if coord_type == "spherical":
        r, theta, phi = bloch[0], bloch[1], bloch[2]
        bloch[0] = r * np.sin(theta) * np.cos(phi)
        bloch[1] = r * np.sin(theta) * np.sin(phi)
        bloch[2] = r * np.cos(theta)
    B.add_vectors(bloch)
    B.render(title=title)
    if ax is None:
        fig = B.fig
        fig.set_size_inches(figsize[0], figsize[1])
        if get_backend() in ["module://ipykernel.pylab.backend_inline", "nbAgg"]:
            plt.close(fig)
        return fig
    return None
    def __init__(
        self,
        coupling_map,
        qubit_subset=None,
        objective="depth",
        backend_prop=None,
        time_limit=30,
        threads=None,
        max_swaps_inbetween_layers=None,
    ):
        """BIPMapping initializer.

        Args:
            coupling_map (CouplingMap): Directed graph represented a coupling map.
            qubit_subset (list[int]): Sublist of physical qubits to be used in the mapping.
                If None, all qubits in the coupling_map will be considered.
            objective (str): Type of objective function to be minimized:

                * ``'gate_error'``: Approximate gate error of the circuit, which is given as the sum of
                    negative logarithm of 2q-gate fidelities in the circuit. It takes into account only
                    the 2q-gate (CNOT) errors reported in ``backend_prop`` and ignores the other errors
                    in such as 1q-gates, SPAMs and idle times.
                * ``'depth'``: [Default] Depth (number of 2q-gate layers) of the circuit.
                * ``'balanced'``: Weighted sum of ``'gate_error'`` and ``'depth'``

            backend_prop (BackendProperties): Backend properties object containing 2q-gate gate errors,
                which are required in computing certain types of objective function
                such as ``'gate_error'`` or ``'balanced'``.
            time_limit (float): Time limit for solving BIP in seconds
            threads (int): Number of threads to be allowed for CPLEX to solve BIP
            max_swaps_inbetween_layers (int):
                Number of swaps allowed in between layers. If None, automatically set.
                Large value could decrease the probability to build infeasible BIP problem but also
                could reduce the chance of finding a feasible solution within the ``time_limit``.

        Raises:
            MissingOptionalLibraryError: if cplex or docplex are not installed.
            TranspilerError: if invalid options are specified.
        """
        if not HAS_DOCPLEX or not HAS_CPLEX:
            raise MissingOptionalLibraryError(
                libname="bip-mapper",
                name="BIP-based mapping pass",
                pip_install="pip install 'qiskit-terra[bip-mapper]'",
                msg="This may not be possible for all Python versions and OSes",
            )
        if backend_prop is None and objective in ("gate_error", "balanced"):
            raise TranspilerError(f"'backend_prop' is required for '{objective}' objective")
        super().__init__()
        self.coupling_map = coupling_map
        self.qubit_subset = qubit_subset
        if self.coupling_map is not None and self.qubit_subset is None:
            self.qubit_subset = list(range(self.coupling_map.size()))
        self.objective = objective
        self.backend_prop = backend_prop
        self.time_limit = time_limit
        self.threads = threads
        self.max_swaps_inbetween_layers = max_swaps_inbetween_layers
Example #25
0
    def check_installed() -> None:
        """
        Checks if PSI4 is installed and available

        Raises:
            MissingOptionalLibraryError: if not installed.
        """
        if PSI4_APP is None:
            raise MissingOptionalLibraryError(libname="PSI4", name="PSI4Driver")
Example #26
0
 def latex(self):
     """Return the corresponding math mode latex string."""
     try:
         from pylatexenc.latexencode import utf8tolatex
     except ImportError as ex:
         raise MissingOptionalLibraryError("pylatexenc",
                                           "latex-from-qasm exporter",
                                           "pip install pylatexenc") from ex
     return utf8tolatex(self.sym())
    def _replace_pauli_sums(cls, operator):
        try:
            from qiskit.providers.aer.library import SaveExpectationValue
        except ImportError as ex:
            raise MissingOptionalLibraryError(
                libname="qiskit-aer",
                name="AerPauliExpectation",
                pip_install="pip install qiskit-aer",
            ) from ex
        # The 'expval_measurement' label on the save instruction is special - the
        # CircuitSampler will look for it to know that the circuit is a Expectation
        # measurement, and not simply a
        # circuit to replace with a DictStateFn
        if operator.__class__ == ListOp:
            return operator.traverse(cls._replace_pauli_sums)

        if isinstance(operator, PauliSumOp):
            save_instruction = SaveExpectationValue(operator.primitive,
                                                    "expval_measurement")
            return CircuitStateFn(save_instruction,
                                  coeff=operator.coeff,
                                  is_measurement=True,
                                  from_operator=True)

        # Change to Pauli representation if necessary
        if {"Pauli"} != operator.primitive_strings():
            logger.warning(
                "Measured Observable is not composed of only Paulis, converting to "
                "Pauli representation, which can be expensive.")
            # Setting massive=False because this conversion is implicit. User can perform this
            # action on the Observable with massive=True explicitly if they so choose.
            operator = operator.to_pauli_op(massive=False)

        if isinstance(operator, SummedOp):
            sparse_pauli = reduce(add,
                                  (meas.coeff * SparsePauliOp(meas.primitive)
                                   for meas in operator.oplist))
            save_instruction = SaveExpectationValue(sparse_pauli,
                                                    "expval_measurement")
            return CircuitStateFn(save_instruction,
                                  coeff=operator.coeff,
                                  is_measurement=True,
                                  from_operator=True)

        if isinstance(operator, PauliOp):
            sparse_pauli = operator.coeff * SparsePauliOp(operator.primitive)
            save_instruction = SaveExpectationValue(sparse_pauli,
                                                    "expval_measurement")
            return CircuitStateFn(save_instruction,
                                  is_measurement=True,
                                  from_operator=True)

        raise TypeError(
            f"Conversion of OperatorStateFn of {operator.__class__.__name__} is not defined."
        )
Example #28
0
 def __init__(self):
     if not HAS_TWEEDLEDUM:
         raise MissingOptionalLibraryError(
             libname='tweedledum',
             name='classical function compiler',
             pip_install='pip install tweedledum')
     self.scopes = []
     self.args = []
     self._network = None
     self.name = None
     super().__init__()
Example #29
0
    def __getattr__(self, attr):
        if not self.aer:
            try:
                from qiskit.providers import aer

                self.aer = aer.Aer
            except ImportError as ex:
                raise MissingOptionalLibraryError(
                    "qiskit-aer", "Aer provider", "pip install qiskit-aer"
                ) from ex
        return getattr(self.aer, attr)
Example #30
0
    def __getattr__(self, attr):
        if not self.ibmq:
            try:
                from qiskit.providers import ibmq

                self.ibmq = ibmq.IBMQ
            except ImportError as ex:
                raise MissingOptionalLibraryError(
                    "qiskit-ibmq-provider", "IBMQ provider", "pip install qiskit-ibmq-provider"
                ) from ex
        return getattr(self.ibmq, attr)