diff --git a/docs/advanced_use_of_ibm_q_devices.rst b/docs/advanced_use_of_ibm_q_devices.rst index a12f8c6fac57..8eae9958d0b7 100644 --- a/docs/advanced_use_of_ibm_q_devices.rst +++ b/docs/advanced_use_of_ibm_q_devices.rst @@ -3,7 +3,9 @@ Advanced Use of IBM Q Devices ============================= -In Qiskit we have an interface for backends and jobs that will be useful for running circuits and extending to third-party backends. In this section, we will review the core components of Qiskit’s base backend framework, using the IBM Q provider as an example. +In Qiskit we have an interface for backends and jobs that will be useful for running circuits and +extending to third-party backends. In this section, we will review the core components of +Qiskit’s base backend framework, using the IBM Q provider as an example. The interface has three parts: the provider, the backend, and the job: diff --git a/docs/aer/overview.rst b/docs/aer/overview.rst index cdfe3cf1152e..2ecfc2793e59 100644 --- a/docs/aer/overview.rst +++ b/docs/aer/overview.rst @@ -4,7 +4,10 @@ Overview A high performance simulator framework for quantum circuits -Qiskit Aer provides a high performance simulator framework for the Qiskit software stack. It contains optimized C++ simulator backends for executing circuits compiled in Qiskit Terra, and tools for constructing highly configurable noise models for performing realistic noisy simulations of the errors that occur during execution on real devices. +Qiskit Aer provides a high performance simulator framework for the Qiskit software stack. It +contains optimized C++ simulator backends for executing circuits compiled in Qiskit Terra, and +tools for constructing highly configurable noise models for performing realistic noisy simulations +of the errors that occur during execution on real devices. *This project uses the* |emphasized hyperlink|_. diff --git a/docs/aqua/ai/qiskit_ai.rst b/docs/aqua/ai/qiskit_ai.rst index a573c5e3d9a9..66d92e440a41 100644 --- a/docs/aqua/ai/qiskit_ai.rst +++ b/docs/aqua/ai/qiskit_ai.rst @@ -72,15 +72,16 @@ Research and developers interested in :ref:`aqua-extending` with new AI-specific capabilities can take advantage of the modular architecture of Aqua and easily extend Aqua with more algorithms and algorithm components, such as new :ref:`oracles` for the :ref:`grover` algorithm, -:ref:`optimizers` and :ref:`variational-forms` for :ref:`vqe`, :ref:`qaoa`, and :ref:`svm-variational`, -:ref:`iqfts` for :ref:`qpe`, :ref:`initial-states` for :ref:`variational-forms`, -as well as :ref:`feature-maps` and :ref:`multiclass-extensions` for Support Vector Machine +:ref:`optimizers` and :ref:`variational-forms` for :ref:`vqe`, :ref:`qaoa`, and +:ref:`svm-variational`, :ref:`iqfts` for :ref:`qpe`, :ref:`initial-states` for +:ref:`variational-forms`, as well as :ref:`feature-maps` and +:ref:`multiclass-extensions` for Support Vector Machine (SVM) algorithms, such as :ref:`svm-variational` and :ref:`svm-q-kernel`. -------- Examples --------- +-------- The ``artificial_intelligence`` folder of the `Aqua Tutorials GitHub Repository `__ contains numerous diff --git a/docs/aqua/algorithms.rst b/docs/aqua/algorithms.rst index ca165b471b45..cc32b371c147 100644 --- a/docs/aqua/algorithms.rst +++ b/docs/aqua/algorithms.rst @@ -272,14 +272,15 @@ Additionally, VQE can be configured with the following parameters: Quantum Approximate Optimization Algorithm (QAOA) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -`QAOA `__ is a well-known algorithm for finding approximate solutions to -combinatorial-optimization problems. -The QAOA implementation in Aqua directly uses `VQE <#variational-quantum-eigensolver-vqe>`__ for its general hybrid optimization structure. +`QAOA `__ is a well-known algorithm for finding approximate +solutions to combinatorial-optimization problems. +The QAOA implementation in Aqua directly uses `VQE <#variational-quantum-eigensolver-vqe>`__ for +its general hybrid optimization structure. However, unlike VQE, which can be configured with arbitrary variational forms, -QAOA uses its own fine-tuned variational form, which comprises :math:`p` parameterized global :math:`x` rotations and -:math:`p` different parameterizations of the problem hamiltonian. -As a result, unlike VQE, QAOA does not need to have a variational form specified as an input parameter, -and is configured mainly by a single integer parameter, ``p``, +QAOA uses its own fine-tuned variational form, which comprises :math:`p` parameterized global +:math:`x` rotations and :math:`p` different parameterizations of the problem hamiltonian. +As a result, unlike VQE, QAOA does not need to have a variational form specified as an input +parameter, and is configured mainly by a single integer parameter, ``p``, which dictates the depth of the variational form, and thus affects the approximation quality. An initial state from Aqua's :ref:`initial-states` library may be supplied as well. @@ -404,8 +405,8 @@ Quantum Phase Estimation (QPE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ QPE (also sometimes abbreviated -as PEA, for *Phase Estimation Algorithm*), takes two quantum registers, *control* and *target*, where the -control consists of several qubits initially put in uniform +as PEA, for *Phase Estimation Algorithm*), takes two quantum registers, *control* and *target*, +where the control consists of several qubits initially put in uniform superposition, and the target a set of qubits prepared in an eigenstate (or, oftentimes, a guess of the eigenstate) of the unitary operator of a quantum system. QPE then evolves the target under the control using @@ -440,7 +441,8 @@ configuration, QPE also exposes the following parameter settings: expansion_mode = "trotter" | "suzuki" - Two ``str`` values are permitted: ``"trotter"`` (Lloyd's method) or ``"suzuki"`` (for Trotter-Suzuki expansion), + Two ``str`` values are permitted: ``"trotter"`` (Lloyd's method) or ``"suzuki"`` + (for Trotter-Suzuki expansion), with ``"trotter"`` being the default one. - The expansion order: @@ -449,7 +451,8 @@ configuration, QPE also exposes the following parameter settings: expansion_order = 1 | 2 | ... - This parameter sets the Trotter-Suzuki expansion order. A positive ``int`` value is expected. The default value is ``2``. + This parameter sets the Trotter-Suzuki expansion order. A positive ``int`` value is expected. + The default value is ``2``. - The number of ancillae: @@ -457,8 +460,8 @@ configuration, QPE also exposes the following parameter settings: num_ancillae = 1 | 2 | ... - This parameter sets the number of ancillary qubits to be used by QPE. A positive ``int`` value is expected. - The default value is ``1``. + This parameter sets the number of ancillary qubits to be used by QPE. A positive ``int`` + value is expected. The default value is ``1``. .. topic:: Declarative Name @@ -477,7 +480,8 @@ Iterative Quantum Phase Estimation (IQPE) IQPE, as its name suggests, iteratively computes the phase so as to require fewer qubits. -It takes in the same set of parameters as `QPE <#quantum-phase-estimation-qpe>`__, except for the number of +It takes in the same set of parameters as `QPE <#quantum-phase-estimation-qpe>`__, except +for the number of ancillary qubits ``num_ancillae``, which is replaced by ``num_iterations`` (a positive ``int``, also defaulted to ``1``), and for the fact that an Inverse Quantum Fourier Transform (IQFT) is not used for IQPE. @@ -507,9 +511,11 @@ applied to a particular operator :math:`A`. :math:`A` is assumed to operate on :math:`n + 1` qubits (plus possible ancillary qubits) where the :math:`n` qubits represent the uncertainty (in the form of a random distribution from the :ref:`random-distributions` library) -and the last qubit, called the *objective qubit*, is used to represent the normalized objective value as its amplitude. +and the last qubit, called the *objective qubit*, is used to represent the normalized objective +value as its amplitude. In other words, -:math:`A` is constructed such that the probability of measuring a '1' in the objective qubit is equal to the +:math:`A` is constructed such that the probability of measuring a '1' in the objective qubit is +equal to the value of interest. .. seealso:: @@ -537,7 +543,8 @@ expects the following inputs: a_factory - A ``CircuitFactory`` object that represents the uncertainty problem, i.e., the :math:`A` operator mentioned above. + A ``CircuitFactory`` object that represents the uncertainty problem, i.e., the :math:`A` + operator mentioned above. - The optional problem unitary: @@ -683,8 +690,9 @@ The algorithm determines whether the given function function maps all inputs to 0 or 1, and a balanced function maps half of its inputs to 0 and the other half to 1. Any of the oracles provided by Aqua can be used with the Deutsch-Jozsa algorithm, -as long as the boolean function implemented by the oracle indeed satisfies the constraint of being either constant or balanced. -Above said, a :ref:`truth-table-oracle` instance might be easier to construct to meet the constraint, but a :ref:`logic-expr-oracle` can certainly also be used. +as long as the boolean function implemented by the oracle indeed satisfies the constraint of being +either constant or balanced. Above said, a :ref:`truth-table-oracle` instance might be easier to +construct to meet the constraint, but a :ref:`logic-expr-oracle` can certainly also be used. .. topic:: Declarative Name @@ -733,7 +741,8 @@ if :math:`y=x \oplus s` for all :math:`x \in \{0,1\}^n`. Thus, if 1-to-1 (or, permutation) function. Otherwise, if :math:`s \neq 0\ldots 0`, then :math:`f_s` is a 2-to-1 function. Of Aqua's included oracles, -:ref:`truth-table-oracle` should be the easiest to use to create one that can be used with the Simon algorith. +:ref:`truth-table-oracle` should be the easiest to use to create one that can be used with the +Simon algorith. .. topic:: Declarative Name @@ -827,7 +836,8 @@ QSVM Variational can be configured with the following parameters: An integer value greater than or equal to ``3`` is expected. The default is ``3``. -- A Boolean indicating whether or not to print additional information when the algorithm is running: +- A Boolean indicating whether or not to print additional information when the algorithm is + running: .. code:: python @@ -851,7 +861,8 @@ HHL algorithm for solving linear systems (HHL) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The *HHL algorithm* (after the author's surnames Harrow-Hassidim-Lloyd) is a -quantum algorithm to solve systems of linear equations :math:`A\overrightarrow{x}=\overrightarrow{b}`. +quantum algorithm to solve systems of linear equations +:math:`A\overrightarrow{x}=\overrightarrow{b}`. Using the Quantum Phase Estimation algorithm (:ref:`QPE`), the linear system is transformed into diagonal form in which the matrix :math:`A` is easily invertible. The inversion is achieved by rotating an ancillary qubit by an angle @@ -911,15 +922,18 @@ algorithms. Exact Eigensolver ^^^^^^^^^^^^^^^^^ -Exact Eigensolver computes up to the first :math:`k` eigenvalues of a complex square matrix of dimension +Exact Eigensolver computes up to the first :math:`k` eigenvalues of a complex square matrix of +dimension :math:`n \times n`, with :math:`k \leq n`. -It can be configured with an ``int`` parameter ``k`` indicating the number of eigenvalues to compute: +It can be configured with an ``int`` parameter ``k`` indicating the number of eigenvalues to +compute: .. code:: python k = 1 | 2 | ... | n -Specifically, the value of this parameter must be an ``int`` value ``k`` in the range :math:`[1,n]`. The default is ``1``. +Specifically, the value of this parameter must be an ``int`` value ``k`` in the range +:math:`[1,n]`. The default is ``1``. .. topic:: Declarative Name @@ -959,11 +973,14 @@ CPLEX Ising can be configured with the following parameters: thread = 0 | 1 | 2 | ... - A non-negative ``int`` value is expected. Setting ``thread`` to ``0`` lets CPLEX decide the number of threads to allocate, but this may + A non-negative ``int`` value is expected. Setting ``thread`` to ``0`` lets CPLEX decide the + number of threads to allocate, but this may not be ideal for small problems. Any value - greater than ``0`` specifically sets the thread count. The default value is ``1``, which is ideal for small problems. + greater than ``0`` specifically sets the thread count. The default value is ``1``, which is + ideal for small problems. -- Decides what CPLEX reports to the screen and records in a log during mixed integer optimization (MIP). +- Decides what CPLEX reports to the screen and records in a log during mixed integer + optimization (MIP). .. code:: python @@ -983,6 +1000,7 @@ CPLEX Ising can be configured with the following parameters: In Aqua, CPLEX supports the ``ising`` problem. .. _avm-rbf-kernel: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Support Vector Machine Radial Basis Function Kernel (SVM Classical) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/aqua/chemistry/qiskit_chemistry.rst b/docs/aqua/chemistry/qiskit_chemistry.rst index 8742690f4c8c..67fc9fa2d34a 100644 --- a/docs/aqua/chemistry/qiskit_chemistry.rst +++ b/docs/aqua/chemistry/qiskit_chemistry.rst @@ -5,8 +5,8 @@ Qiskit Chemistry **************** Qiskit Chemistry is the only end-to-end quantum software stack that allows for mapping high-level -classical chemistry computational software problems all the way down to a quantum machine (a simulator or a -real quantum device). +classical chemistry computational software problems all the way down to a quantum machine (a +simulator or a real quantum device). .. toctree:: :maxdepth: 3 diff --git a/docs/aqua/chemistry/qiskit_chemistry_drivers.rst b/docs/aqua/chemistry/qiskit_chemistry_drivers.rst index 23866e47c3ec..16b17ea102b2 100644 --- a/docs/aqua/chemistry/qiskit_chemistry_drivers.rst +++ b/docs/aqua/chemistry/qiskit_chemistry_drivers.rst @@ -1,470 +1,492 @@ -.. _drivers: - -======= -Drivers -======= - -Qiskit Chemistry requires a computational chemistry program or library, known as *driver*, to be installed on the -system for the electronic-structure computation. When launched via the Qiskit Chemistry -:ref:`qiskit-chemistry-command-line`, -:ref:`qiskit-chemistry-gui`, or :ref:`qiskit-chemistry-programmable-interface`, -Qiskit Chemistry expects a driver to be specified, and a -molecular configuration to be passed in the format compatible with that driver. -Qiskit Chemistry uses the driver not only as a frontend input language, to allow the user to configure -a chemistry problem in a language that an experienced chemist is already familiar with, but also -to compute some intermediate data, which will be later on used to form the input to one of the -:ref:`algorithms`. Such intermediate date -includes the following: - -1. One- and two-body integrals in Molecular Orbital (MO) basis -2. Dipole integrals -3. Molecular orbital coefficients -4. :ref:`hartree-fock` energy -5. Nuclear repulsion energy - -Once extracted, the structure of this intermediate data is independent of the -driver that was used to compute it. The only thing that could still depend on the driver -is the level of accuracy of such data; most likely, -a more elaborate driver will produce more accurate data. -Qiskit Chemistry offers the option to serialize this data in a binary format known as -`Hierarchical Data Format 5 (HDF5) `__. -This is done to allow chemists to reuse the same input data in the future -and to enable researchers to exchange -input data with each other --- which is especially useful to researchers who may not have particular -computational chemistry drivers installed on their computers. - -In order for a driver to be usable by Qiskit Chemistry, an interface to that driver -must be built in Qiskit Chemistry. Qiskit Chemistry offers the ``BaseDriver`` -Application Programming Interface (API) to support interfacing new drivers. - -Currently, Qiskit Chemistry comes with interfaces prebuilt -for the following four computational chemistry software drivers: - -1. :ref:`gaussian-16`, a commercial chemistry program -2. :ref:`psi4`, an open-source chemistry program built on Python -3. :ref:`pyscf`, an open-source Python chemistry program -4. :ref:`pyquante`, a pure Python cross-platform open-source chemistry program - -.. topic:: The HDF5 Driver - - A fifth driver, called HDF5, comes prebuilt in Qiskit Chemistry. This is, in fact, the only driver - that does not require the installation or configuration of any external computational chemistry software, - since it is already part of Qiskit Chemistry. - The HDF5 driver allows for chemistry input, in the form of an HDF5 file as specified above, - to be passed into the computation. - -.. topic:: Extending Qiskit Chemistry with Support for New Drivers - - The driver support in Qiskit Chemistry was designed to make the drivers pluggable and discoverable. - In order for Qiskit Chemistry to - be able to interface a driver library, the ``BaseDriver`` base class must be implemented in order - to provide the interfacing code, or *wrapper*. As part of this process, the required - `JavaScript Object Notation (JSON) `__ schema for the driver interface must - be provided in a file named ``configuration.json``. The interfacing code in the driver wrapper - is responsible for constructing and populating a ``QMolecule`` instance with the electronic - structure data listed above. Driver wrappers implementing the ``BaseDriver`` class and the - associated ``configuration.json`` schema file are organized in subfolders of the ``drivers`` folder - for automatic discovery and dynamic lookup. Consulting the existing driver interface - implementations may be helpful in accomplishing the task of extending . - -The remainder of this section describes how to install and configure the drivers currently supported -by Qiskit Chemistry. - -.. _gaussian-16: - ------------- -Gaussian™ 16 ------------- - -`Gaussian™ 16 `__ is a commercial program for computational chemistry. -The corresponding driver wrapper in Qiskit Chemistry accesses electronic structure information from Gaussian™ 16 -via the Gaussian-supplied open-source `interfacing code `__. - -In the ``qiskit_chemistry/drivers/gaussiand/gauopen`` folder of the -`Qiskit Chemistry GitHub repository `__, -the Python part of the above interfacing code, as needed by Qiskit Chemistry, -has been made available. It is licensed under a -`Gaussian Open-Source Public License -`__. - -Part of this interfacing code --- specifically, the Fortran file ``qcmatrixio.F`` --- requires compilation to a Python native extension. However, -Qiskit Chemistry comes with pre-built binaries for most common platforms. If there is no pre-built binary -matching your platform, then it will be necessary to compile this file as per the instructions below. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Compiling the Fortran Interfacing Code -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If no prebuilt native extension binary, as supplied with Qiskit Chemistry, works for your platform, then -to use the Gaussian™ 16 driver on your machine, the Fortran file ``qcmatrixio.F`` must be compiled into object code that can -be used by Python. This is accomplished using the -`Fortran to Python Interface Generator (F2PY) `__, -which is part of the `NumPy `__ Python library. -Specifically, on your command prompt window, change directory to the ``qiskit_chemistry/drivers/gaussiand/gauopen`` -directory inside the Qiskit Chemistry installation directory, and while in the Python environment -created for Aqua and Qiskit Chemistry, invoke ``f2py`` on ``qcmatrixio.F`` as explained below. - - -^^^^^^^^^^^^^^^^^^^^^ -Apple macOS and Linux -^^^^^^^^^^^^^^^^^^^^^ - -The full syntax of the ``f2py`` command on macOS and Linux is as follows: - -.. code:: sh - - f2py -c -m qcmatrixio qcmatrixio.F - -This command will generate a file with name prefix ``qcmatrixio`` and extension ``so``, for example -``qcmatrixio.cpython-36m-x86_64-linux-gnu.so``. -In order for the command above to work and such file to be generated, you will need a supported Fortran compiler installed. -On macOS, you may have to download the `GNU Compiler Collection (GCC) `__ -and, in particular, the `GFortran Compiler `__ source and compile it first -if you do not a suitable Fortran compiler installed -On Linux you may be able to download and install a supported Fortran compiler via your distribution's installer. - -.. topic:: Special Notes for macOS X - - If your account is using the bash shell on a macOS X machine, you can edit the ``.bash_profile`` file - in your home directory and add the following lines: - - - .. code:: sh - - export GAUSS_SCRDIR=~/.gaussian - export g16root=/Applications - alias enable_gaussian='. $g16root/g16/bsd/g16.profile' - - The above assumes that the application Gaussian™ 16 was placed in the ``/Applications`` folder and that - ``~/.gaussian`` is the full path to - the selected scratch folder, where Gaussian™ 16 stores its temporary files. - - Now, before Qiskit Chemistry can properly interface Gaussian™ 16, you will have to run the ``enable_gaussian`` command - defined above. This, however, may generate the following error: - - .. code:: sh - - bash: ulimit: open files: cannot modify limit: Invalid argument - - While this error is not harmful, you might want to suppress it, which can be done by entering the following sequence - of commands on the command line: - - .. code:: sh - - echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf - echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf - sudo sysctl -w kern.maxfiles=65536 - sudo sysctl -w kern.maxfilesperproc=65536 - ulimit -n 65536 65536 - - as well as finally adding the following line to the ``.bash_profile`` file in your account's home directory: - - .. code:: sh - - ulimit -n 65536 65536 - - At the end of this configuration, the ``.bash_profile`` in your account's home directory should have a section in it - like in the following script snippet: - - .. code:: sh - - # Gaussian 16 - export GAUSS_SCRDIR=~/.gaussian - export g16root=/Applications - alias enable_gaussian='. $g16root/g16/bsd/g16.profile' - ulimit -n 65536 65536 - - -^^^^^^^^^^^^^^^^^ -Microsoft Windows -^^^^^^^^^^^^^^^^^ - -The following steps can be used with the Intel Fortran compiler on the Microsoft Windows platform: - -1. Set up the environment by adding the following line to ``ifortvars.bat``: - - .. code:: sh - - ifortvars -arch intel64 - -2. Issue the following command from within the ``gauopen`` directory: - - .. code:: sh - - f2py -c --fcompiler=intelvem -m qcmatrixio qcmatrixio.F - - Upon successful execution, the ``f2py`` command above will generate a file with name prefix ``qcmatrixio`` and - extension ``so``, for example ``qcmatrixio.cp36-win_amd64.pyd``. However, in order for the ``f2py`` command above - to work, ``#ifdef`` may need to be manually edited if it is not recognized or supported during the processing of the ``f2py`` command - above. For example, with ``f2py`` from Intel Visual Fortran Compiler with Microsoft Visual Studio, the following code snippet - originally shows two occurrences of the line ``Parameter (Len12D=8,Len4D=8)``, as shown next: - - .. code:: - - #ifdef USE_I8 - Parameter (Len12D=8,Len4D=8) - #else - Parameter (Len12D=4,Len4D=4) - #endif - - This may need to be simplified by deleting the first three lines and the last line, leaving just the fourth line, as follows: - - .. code:: - - Parameter (Len12D=4,Len4D=4) - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Verifying Path and Environment Setup -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You should also make sure the Gaussian™ 16 ``g16`` executable can be run from a command line. -This requires verifying that the ``g16`` executable is reachable via the system environment path, and appropriate -exports, such as ``GAUSS_EXEDIR``, have been configured as per -`Gaussian installation instructions `__. - -~~~~~~~~~~~~~~~~~~ -Input File Example -~~~~~~~~~~~~~~~~~~ - -To use Gaussian™ 16 to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, -set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to ``GAUSSIAN`` and -then create a ``gaussian`` section in the input file as per the example below, -which shows the configuration of a molecule of -hydrogen, :math:`H_2`. Here, the molecule, basis set and other options are specified according -to the Gaussian™ 16 control file, so the syntax specified by Gaussian™ 16 should be followed: - -.. code:: - - &gaussian - # rhf/sto-3g scf(conventional) - - h2 molecule - - 0 1 - H 0.0 0.0 0.0 - H 0.0 0.0 0.74 - &end - -Experienced chemists who already have existing Gaussian™ 16 control files can simply paste the contents of those files -into the ``gaussian`` section of the input file. This configuration can also be easily achieved using the -Qiskit Chemistry :ref:`qiskit-chemistry-gui`. - -.. _psi4: - ----- -PSI4 ----- -`PSI4 `__ is an open-source program for computational chemistry. -In order for Qiskit Chemistry to interface PSI4, accept PSI4 input files and execute PSI4 to extract -the electronic structure information necessary for the computation of the input to the quantum algorithm, -PSI4 must be `installed `__ and discoverable on the system where -Qiskit Chemistry is also installed. -Therefore, once PSI4 has been installed, the ``psi4`` executable must be reachable via the system environment path. -For example, on macOS, this can be achieved by adding the following section to the ``.bash_profile`` file in the -user's home directory: - -.. code:: sh - - # PSI4 - alias enable_psi4='export PATH=/Users/username/psi4conda/bin:$PATH' - -where ``username`` should be replaced with the user's account name. -In order for Qiskit Chemistry to discover PSI4 at run time, it is then necessary to execute the ``enable_psi4`` command -before launching Qiskit Chemistry. - -To use PSI4 to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, -set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to ``PSI4`` and -then create a ``psi4`` section in the input file as per the example below, which shows the configuration of a molecule of -hydrogen, :math:`H_2`. Here, the molecule, basis set and other options are specified according -to the PSI4 control file, so the syntax specified by PSI4 should be followed: - -.. code:: python - - &psi4 - molecule h2 { - 0 1 - H 0.0 0.0 0.0 - H 0.0 0.0 0.74 - } - - set { - basis sto-3g - scf_type pk - } - &end - -Experienced chemists who already have existing PSI4 control files can simply paste the contents of those files -into the ``psi4`` section of the input file. This configuration can also be easily achieved using the -Qiskit Chemistry :ref:`qiskit-chemistry-gui`. - -.. _pyscf: - ------ -PySCF ------ -`PySCF `__ is an open-source library for computational chemistry. -In order for Qiskit Chemistry to interface PySCF, accept PySCF input files and execute PySCF to extract -the electronic structure information necessary for the computation of the input to the quantum algorithm, -PySCF must be installed. According to the `installation instructions `__, -the preferred installation method for PySCF is via the pip package management system. Doing so while in the Python -virtual environment where Qiskit Chemistry is also installed will automatically make PySCF dynamically discoverable -by Qiskit Chemistry at run time. - -To use PySCF to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, -set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to ``PYSCF`` and -then create a ``pyscf`` section in the input file as per the example below, which shows the configuration of a molecule of -hydrogen, :math:`H_2`. Here, the molecule, basis set and other options are specified as key/value pairs, according -to the syntax expected by PySCF. In PySCF, these are the arguments as passed to the ``pyscf.gto.Mole`` class - -The ``atom`` field can be in xyz format, as per the example below. Here each atom is identified by its symbol along -with its position in the x, y, z coordinate space. Atoms are separated by the semicolon symbol. - -The ``atom`` field can also be in `ZMatrix `__ format. Here again -atoms are separate by semicolon. This is an example for H2O (water): "H; O 1 1.08; H 2 1.08 1 107.5". Dummy atom(s) -using symbol 'X' may be added to allow or facilitate conversion to xyz coordinates, as used internally for processing, -and are removed from the molecule following the conversion. - -.. code:: python - - &pyscf - atom=H .0 .0 .0; H .0 .0 0.74 - unit=Angstrom - charge=0 - spin=0 - basis=sto3g - &end - -Experienced chemists who already have existing PySCF control files can simply paste the contents of those files -into the ``pyscf`` section of the input file. This configuration can also be easily achieved using the -Qiskit Chemistry :ref:`qiskit-chemistry-gui`. - -.. _pyquante: - --------- -PyQuante --------- -`PyQuante `__ is an open-source library for computational chemistry. -Qiskit Chemistry specifically requires PyQuante V2, also known as PyQuante2. -In order for Qiskit Chemistry to interface PyQuante, accept PyQuante input files and execute PyQuante to extract -the electronic structure information necessary for the computation of the input to the quantum algorithm, -PyQuante2 must be installed and discoverable on the system where -Qiskit Chemistry is also installed. Installing PyQuante2 according to the -`installation instructions `__ while -in the Python virtual environment where Qiskit Chemistry has also been installed will automatically -make PyQuante2 dynamically discovered by Qiskit Chemistry at run time. - -The Qiskit Chemistry PyQuante2 driver wrapper contains two methods, in ``transform.py``, taken from from -`Pyquante V1 `__, which is `licensed `__ -under a `modified BSD license `__. - -.. note:: - Like all the other drivers currently interfaced by Qiskit Chemistry, - PyQuante2 provides enough intermediate data for Qiskit Chemistry to compute a molecule's ground - state molecular energy. However, unlike the other drivers, the data computed by PyQuante is not sufficient for - Qiskit Chemistry to compute a molecule's dipole moment. Therefore, PyQuante is currently - the only driver interfaced by Qiskit Chemistry that does not allow for the computation of a molecule's - dipole moment. - -To use PyQuante to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, -set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to ``PYQUANTE`` and -then create a ``pyquante`` section in the input file as per the example below, which shows the configuration of a molecule of -hydrogen, :math:`H_2`. Here, the molecule, basis set and other options are specified according -to the PyQuante control file, so the syntax specified by PyQuante should be followed. -Specifically, a molecule is configured as a list of atoms. Each atom's chemical symbol is followed by the atom's :math:`x, y, z` -geometrical coordinates separated by a blank space. Atom configurations are separated by semicolons. - -The molecule in the ``atoms`` field can also be in `ZMatrix `__ format. -Here again atoms are separated by semicolons; within an atom the symbol and positional information separated by spaces. -This is an example for H2O (water): "H; O 1 1.08; H 2 1.08 1 107.5". Dummy atom(s) -using symbol 'X' may be added to allow or facilitate conversion to xyz coordinates, as used internally for processing, -and are removed from the molecule following the conversion. - -.. code:: python - - &pyquante - atoms=H .0 .0 .0; H .0 .0 0.74 - units=Angstrom - charge=0 - multiplicity=1 - basis=sto3g - &end - -Experienced chemists who already have existing PyQuante control files can simply paste the contents of those files -into the ``pyquante`` section of the input file. This configuration can also be easily achieved using the -Qiskit Chemistry :ref:`qiskit-chemistry-gui`. - -.. _hdf5: - ----- -HDF5 ----- - -Qiskit Chemistry uses a molecular input file written on top of one of the classical computational software drivers -that it interfaces. Qiskit Chemistry executes a driver classically, -only to the extent necessary to compute some intermediate data which, combined with the molecular configuration, -can later be used to form the input to one of the -Aqua :ref:`quantum-algorithms`. - -As mentioned above, the intermediate data extracted from the classical computational software consists of the following: - -1. One- and two-body integrals in Molecular Orbital (MO) basis -2. Dipole integrals -3. Molecular orbital coefficients -4. Hartree-Fock energy -5. Nuclear repulsion energy - -Once extracted, the structure of this intermediate data is independent of the classical driver -that was used to compute it. -However, the level of accuracy of such data does depend on the computational chemistry software; -more elaborate software packages are more likely to produce more accurate data. - -Qiskit Chemistry offers the option to serialize this data in a binary format known as -`Hierarchical Data Format 5 (HDF5) `__. -This is done for future reuse and exchange of input data among researchers who may not have a particular computational -chemistry driver installed on their computers, or may have a different version of that driver. -HDF5 is configured as a prebuilt driver in Aqua because it allows for chemistry input to be passed into the -computation. In fact, HDF5 is the only driver that does not require any installation other -the installation of Qiskit Chemistry itself. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Generation of an HDF5 Input File -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The most intuitive way to generate an HDF5 input file is by using the Qiskit Chemistry -:ref:`qiskit-chemistry-gui`. -Through the GUI, you can load an existing :ref:`qiskit-chemistry-input-file` from the ``chemistry`` folder -of the `Qiskit Tutorials GitHub repository `__ -(which must have been installed on your file system via a ``git clone`` command) -by selecting **Open...** from the **File** menu. Alternatively, you can create and then potentially customize -a brand new :ref:`qiskit-chemistry-input-file` by choosing **New** from the **File** menu. -Once you have configured the chemistry experiment in one of the existing classical drivers -(:ref:`gaussian-16`, :ref:`psi4`, :ref:`pyscf` or :ref:`pyquante`), -you can specify the name of the file where you want the HDF5 file to be serialized. This can be done -by assigning a value to the ``hdf5_output`` field of the ``driver`` section. -Upon completing its execution, Qiskit Chemistry displays the following message: - -.. code:: sh - - HDF5 file saved '/Users/username/Documents/temp/molecule.hdf5' - -assuming that ``molecule.hdf5`` and ``/Users/username/Documents/temp`` are the file name -and directory path you chose, respectively. - -Using the GUI is the most intuitive option to generate the HDF5 file corresponding to a given experiment. The -same result can be obtained by assigning a value to the ``hdf5_output`` field of the ``driver`` section of -an :ref:`qiskit-chemistry-input-file` and then invoking the Qiskit Chemistry -:ref:`qiskit-chemistry-command-line` tool with the name of that file as the input parameter. - -Using an HDF5 File as the Input to an Experiment -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -If you later want the HDF5 file to be deserialized and its contents used as the input for a chemistry experiment, -you can select ``HDF5`` as the driver in an :ref:`qiskit-chemistry-input-file`. Doing so will -require the ``hdf5`` section in the input file to be configured by assigning a valid fully qualified -file name to the ``hdf5_input`` field, as shown: - -.. code:: python - - &hdf5 - hdf5_input=molecule.hdf5 - &end - +.. _drivers: + +======= +Drivers +======= + +Qiskit Chemistry requires a computational chemistry program or library, known as *driver*, to be +installed on the system for the electronic-structure computation. When launched via the Qiskit +Chemistry :ref:`qiskit-chemistry-command-line`, +:ref:`qiskit-chemistry-gui`, or :ref:`qiskit-chemistry-programmable-interface`, +Qiskit Chemistry expects a driver to be specified, and a +molecular configuration to be passed in the format compatible with that driver. +Qiskit Chemistry uses the driver not only as a frontend input language, to allow the user to +configure a chemistry problem in a language that an experienced chemist is already familiar with, +but also to compute some intermediate data, which will be later on used to form the input to one +of the :ref:`algorithms`. Such intermediate date +includes the following: + +1. One- and two-body integrals in Molecular Orbital (MO) basis +2. Dipole integrals +3. Molecular orbital coefficients +4. :ref:`hartree-fock` energy +5. Nuclear repulsion energy + +Once extracted, the structure of this intermediate data is independent of the +driver that was used to compute it. The only thing that could still depend on the driver +is the level of accuracy of such data; most likely, +a more elaborate driver will produce more accurate data. +Qiskit Chemistry offers the option to serialize this data in a binary format known as +`Hierarchical Data Format 5 (HDF5) `__. +This is done to allow chemists to reuse the same input data in the future +and to enable researchers to exchange +input data with each other --- which is especially useful to researchers who may not have +particular computational chemistry drivers installed on their computers. + +In order for a driver to be usable by Qiskit Chemistry, an interface to that driver +must be built in Qiskit Chemistry. Qiskit Chemistry offers the ``BaseDriver`` +Application Programming Interface (API) to support interfacing new drivers. + +Currently, Qiskit Chemistry comes with interfaces prebuilt +for the following four computational chemistry software drivers: + +1. :ref:`gaussian-16`, a commercial chemistry program +2. :ref:`psi4`, an open-source chemistry program built on Python +3. :ref:`pyscf`, an open-source Python chemistry program +4. :ref:`pyquante`, a pure Python cross-platform open-source chemistry program + +.. topic:: The HDF5 Driver + + A fifth driver, called HDF5, comes prebuilt in Qiskit Chemistry. This is, in fact, the only + driver that does not require the installation or configuration of any external computational + chemistry software, since it is already part of Qiskit Chemistry. The HDF5 driver allows for + chemistry input, in the form of an HDF5 file as specified above, to be passed into the + computation. + +.. topic:: Extending Qiskit Chemistry with Support for New Drivers + + The driver support in Qiskit Chemistry was designed to make the drivers pluggable and + discoverable. In order for Qiskit Chemistry to be able to interface a driver library, the + ``BaseDriver`` base class must be implemented in order to provide the interfacing code, or + *wrapper*. As part of this process, the required + `JavaScript Object Notation (JSON) `__ schema for the driver interface must + be provided in a file named ``configuration.json``. The interfacing code in the driver wrapper + is responsible for constructing and populating a ``QMolecule`` instance with the electronic + structure data listed above. Driver wrappers implementing the ``BaseDriver`` class and the + associated ``configuration.json`` schema file are organized in subfolders of the ``drivers`` + folder for automatic discovery and dynamic lookup. Consulting the existing driver interface + implementations may be helpful in accomplishing the task of extending . + +The remainder of this section describes how to install and configure the drivers currently supported +by Qiskit Chemistry. + +.. _gaussian-16: + +------------ +Gaussian™ 16 +------------ + +`Gaussian™ 16 `__ is a commercial program for computational chemistry. +The corresponding driver wrapper in Qiskit Chemistry accesses electronic structure information +from Gaussian™ 16 via the Gaussian-supplied open-source +`interfacing code `__. + +In the ``qiskit_chemistry/drivers/gaussiand/gauopen`` folder of the +`Qiskit Chemistry GitHub repository `__, +the Python part of the above interfacing code, as needed by Qiskit Chemistry, +has been made available. It is licensed under a +`Gaussian Open-Source Public License +`__. + +Part of this interfacing code --- specifically, the Fortran file ``qcmatrixio.F`` --- requires +compilation to a Python native extension. However, Qiskit Chemistry comes with pre-built binaries +for most common platforms. If there is no pre-built binary matching your platform, then it will be +necessary to compile this file as per the instructions below. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Compiling the Fortran Interfacing Code +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If no prebuilt native extension binary, as supplied with Qiskit Chemistry, works for your +platform, then to use the Gaussian™ 16 driver on your machine, the Fortran file ``qcmatrixio.F`` +must be compiled into object code that can be used by Python. This is accomplished using the +`Fortran to Python Interface Generator (F2PY) `__, +which is part of the `NumPy `__ Python library. +Specifically, on your command prompt window, change directory to the +``qiskit_chemistry/drivers/gaussiand/gauopen`` directory inside the Qiskit Chemistry +installation directory, and while in the Python environment created for Aqua and Qiskit Chemistry, +invoke ``f2py`` on ``qcmatrixio.F`` as explained below. + + +^^^^^^^^^^^^^^^^^^^^^ +Apple macOS and Linux +^^^^^^^^^^^^^^^^^^^^^ + +The full syntax of the ``f2py`` command on macOS and Linux is as follows: + +.. code:: sh + + f2py -c -m qcmatrixio qcmatrixio.F + +This command will generate a file with name prefix ``qcmatrixio`` and extension ``so``, for example +``qcmatrixio.cpython-36m-x86_64-linux-gnu.so``. +In order for the command above to work and such file to be generated, you will need a supported +Fortran compiler installed. On macOS, you may have to download the +`GNU Compiler Collection (GCC) `__ and, in particular, the +`GFortran Compiler `__ source and compile it first +if you do not a suitable Fortran compiler installed +On Linux you may be able to download and install a supported Fortran compiler via your +distribution's installer. + +.. topic:: Special Notes for macOS X + + If your account is using the bash shell on a macOS X machine, you can edit the + ``.bash_profile`` file in your home directory and add the following lines: + + + .. code:: sh + + export GAUSS_SCRDIR=~/.gaussian + export g16root=/Applications + alias enable_gaussian='. $g16root/g16/bsd/g16.profile' + + The above assumes that the application Gaussian™ 16 was placed in the ``/Applications`` folder + and that ``~/.gaussian`` is the full path to + the selected scratch folder, where Gaussian™ 16 stores its temporary files. + + Now, before Qiskit Chemistry can properly interface Gaussian™ 16, you will have to run the + ``enable_gaussian`` command defined above. This, however, may generate the following error: + + .. code:: sh + + bash: ulimit: open files: cannot modify limit: Invalid argument + + While this error is not harmful, you might want to suppress it, which can be done by entering + the following sequence of commands on the command line: + + .. code:: sh + + echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf + echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf + sudo sysctl -w kern.maxfiles=65536 + sudo sysctl -w kern.maxfilesperproc=65536 + ulimit -n 65536 65536 + + as well as finally adding the following line to the ``.bash_profile`` file in your account's + home directory: + + .. code:: sh + + ulimit -n 65536 65536 + + At the end of this configuration, the ``.bash_profile`` in your account's home directory + should have a section in it like in the following script snippet: + + .. code:: sh + + # Gaussian 16 + export GAUSS_SCRDIR=~/.gaussian + export g16root=/Applications + alias enable_gaussian='. $g16root/g16/bsd/g16.profile' + ulimit -n 65536 65536 + + +^^^^^^^^^^^^^^^^^ +Microsoft Windows +^^^^^^^^^^^^^^^^^ + +The following steps can be used with the Intel Fortran compiler on the Microsoft Windows platform: + +1. Set up the environment by adding the following line to ``ifortvars.bat``: + + .. code:: sh + + ifortvars -arch intel64 + +2. Issue the following command from within the ``gauopen`` directory: + + .. code:: sh + + f2py -c --fcompiler=intelvem -m qcmatrixio qcmatrixio.F + + Upon successful execution, the ``f2py`` command above will generate a file with name prefix + ``qcmatrixio`` and extension ``so``, for example ``qcmatrixio.cp36-win_amd64.pyd``. However, + in order for the ``f2py`` command above to work, ``#ifdef`` may need to be manually edited if it + is not recognized or supported during the processing of the ``f2py`` command above. For + example, with ``f2py`` from Intel Visual Fortran Compiler with Microsoft Visual Studio, the + following code snippet originally shows two occurrences of the line + ``Parameter (Len12D=8,Len4D=8)``, as shown next: + + .. code:: + + #ifdef USE_I8 + Parameter (Len12D=8,Len4D=8) + #else + Parameter (Len12D=4,Len4D=4) + #endif + + This may need to be simplified by deleting the first three lines and the last line, leaving just the fourth line, as follows: + + .. code:: + + Parameter (Len12D=4,Len4D=4) + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Verifying Path and Environment Setup +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You should also make sure the Gaussian™ 16 ``g16`` executable can be run from a command line. +This requires verifying that the ``g16`` executable is reachable via the system environment path, +and appropriate exports, such as ``GAUSS_EXEDIR``, have been configured as per +`Gaussian installation instructions `__. + +~~~~~~~~~~~~~~~~~~ +Input File Example +~~~~~~~~~~~~~~~~~~ + +To use Gaussian™ 16 to configure a molecule on which to do a chemistry experiment with +Qiskit Chemistry, set the ``name`` field in the ``driver`` section of the +:ref:`qiskit-chemistry-input-file` to ``GAUSSIAN`` and then create a ``gaussian`` section in the +input file as per the example below, which shows the configuration of a molecule of +hydrogen, :math:`H_2`. Here, the molecule, basis set and other options are specified according +to the Gaussian™ 16 control file, so the syntax specified by Gaussian™ 16 should be followed: + +.. code:: + + &gaussian + # rhf/sto-3g scf(conventional) + + h2 molecule + + 0 1 + H 0.0 0.0 0.0 + H 0.0 0.0 0.74 + &end + +Experienced chemists who already have existing Gaussian™ 16 control files can simply paste the +contents of those files into the ``gaussian`` section of the input file. This configuration can +also be easily achieved using the Qiskit Chemistry :ref:`qiskit-chemistry-gui`. + +.. _psi4: + +---- +PSI4 +---- +`PSI4 `__ is an open-source program for computational chemistry. +In order for Qiskit Chemistry to interface PSI4, accept PSI4 input files and execute PSI4 to extract +the electronic structure information necessary for the computation of the input to the quantum +algorithm, PSI4 must be `installed `__ and discoverable on +the system where Qiskit Chemistry is also installed. +Therefore, once PSI4 has been installed, the ``psi4`` executable must be reachable via the system +environment path. For example, on macOS, this can be achieved by adding the following section to +the ``.bash_profile`` file in the user's home directory: + +.. code:: sh + + # PSI4 + alias enable_psi4='export PATH=/Users/username/psi4conda/bin:$PATH' + +where ``username`` should be replaced with the user's account name. +In order for Qiskit Chemistry to discover PSI4 at run time, it is then necessary to execute the +``enable_psi4`` command before launching Qiskit Chemistry. + +To use PSI4 to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, +set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to +``PSI4`` and then create a ``psi4`` section in the input file as per the example below, which shows +the configuration of a molecule of hydrogen, :math:`H_2`. Here, the molecule, basis set and other +options are specified according to the PSI4 control file, so the syntax specified by PSI4 should be +followed: + +.. code:: python + + &psi4 + molecule h2 { + 0 1 + H 0.0 0.0 0.0 + H 0.0 0.0 0.74 + } + + set { + basis sto-3g + scf_type pk + } + &end + +Experienced chemists who already have existing PSI4 control files can simply paste the contents of +those files into the ``psi4`` section of the input file. This configuration can also be easily +achieved using the Qiskit Chemistry :ref:`qiskit-chemistry-gui`. + +.. _pyscf: + +----- +PySCF +----- +`PySCF `__ is an open-source library for computational chemistry. +In order for Qiskit Chemistry to interface PySCF, accept PySCF input files and execute PySCF to +extract the electronic structure information necessary for the computation of the input to the +quantum algorithm, PySCF must be installed. According to the +`installation instructions `__, +the preferred installation method for PySCF is via the pip package management system. Doing so +while in the Python virtual environment where Qiskit Chemistry is also installed will automatically +make PySCF dynamically discoverable by Qiskit Chemistry at run time. + +To use PySCF to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, +set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to +``PYSCF`` and then create a ``pyscf`` section in the input file as per the example below, which +shows the configuration of a molecule of hydrogen, :math:`H_2`. Here, the molecule, basis set and +other options are specified as key/value pairs, according to the syntax expected by PySCF. In PySCF, +these are the arguments as passed to the ``pyscf.gto.Mole`` class. + +The ``atom`` field can be in xyz format, as per the example below. Here each atom is identified by +its symbol along with its position in the x, y, z coordinate space. Atoms are separated by the +semicolon symbol. + +The ``atom`` field can also be in `ZMatrix `__ +format. Here again atoms are separate by semicolon. This is an example for H2O (water): +"H; O 1 1.08; H 2 1.08 1 107.5". Dummy atom(s) using symbol 'X' may be added to allow or facilitate +conversion to xyz coordinates, as used internally for processing, and are removed from the molecule +following the conversion. + +.. code:: python + + &pyscf + atom=H .0 .0 .0; H .0 .0 0.74 + unit=Angstrom + charge=0 + spin=0 + basis=sto3g + &end + +Experienced chemists who already have existing PySCF control files can simply paste the contents of +those files into the ``pyscf`` section of the input file. This configuration can also be easily +achieved using the Qiskit Chemistry :ref:`qiskit-chemistry-gui`. + +.. _pyquante: + +-------- +PyQuante +-------- +`PyQuante `__ is an open-source library for computational +chemistry. Qiskit Chemistry specifically requires PyQuante V2, also known as PyQuante2. +In order for Qiskit Chemistry to interface PyQuante, accept PyQuante input files and execute +PyQuante to extract the electronic structure information necessary for the computation of the input +to the quantum algorithm, PyQuante2 must be installed and discoverable on the system where +Qiskit Chemistry is also installed. Installing PyQuante2 according to the +`installation instructions `__ while +in the Python virtual environment where Qiskit Chemistry has also been installed will automatically +make PyQuante2 dynamically discovered by Qiskit Chemistry at run time. + +The Qiskit Chemistry PyQuante2 driver wrapper contains two methods, in ``transform.py``, taken from +from `Pyquante V1 `__, which is +`licensed `__ +under a `modified BSD license `__. + +.. note:: + Like all the other drivers currently interfaced by Qiskit Chemistry, + PyQuante2 provides enough intermediate data for Qiskit Chemistry to compute a molecule's ground + state molecular energy. However, unlike the other drivers, the data computed by PyQuante is not sufficient for + Qiskit Chemistry to compute a molecule's dipole moment. Therefore, PyQuante is currently + the only driver interfaced by Qiskit Chemistry that does not allow for the computation of a molecule's + dipole moment. + +To use PyQuante to configure a molecule on which to do a chemistry experiment with Qiskit Chemistry, +set the ``name`` field in the ``driver`` section of the :ref:`qiskit-chemistry-input-file` to +``PYQUANTE`` and then create a ``pyquante`` section in the input file as per the example below, +which shows the configuration of a molecule of +hydrogen, :math:`H_2`. Here, the molecule, basis set and other options are specified according +to the PyQuante control file, so the syntax specified by PyQuante should be followed. +Specifically, a molecule is configured as a list of atoms. Each atom's chemical symbol is followed +by the atom's :math:`x, y, z` +geometrical coordinates separated by a blank space. Atom configurations are separated by +semicolons. + +The molecule in the ``atoms`` field can also be in +`ZMatrix `__ format. +Here again atoms are separated by semicolons; within an atom the symbol and positional information +separated by spaces. This is an example for H2O (water): "H; O 1 1.08; H 2 1.08 1 107.5". Dummy +atom(s) using symbol 'X' may be added to allow or facilitate conversion to xyz coordinates, as used +internally for processing, and are removed from the molecule following the conversion. + +.. code:: python + + &pyquante + atoms=H .0 .0 .0; H .0 .0 0.74 + units=Angstrom + charge=0 + multiplicity=1 + basis=sto3g + &end + +Experienced chemists who already have existing PyQuante control files can simply paste the contents +of those files into the ``pyquante`` section of the input file. This configuration can also be +easily achieved using the Qiskit Chemistry :ref:`qiskit-chemistry-gui`. + +.. _hdf5: + +---- +HDF5 +---- + +Qiskit Chemistry uses a molecular input file written on top of one of the classical computational +software drivers that it interfaces. Qiskit Chemistry executes a driver classically, +only to the extent necessary to compute some intermediate data which, combined with the molecular +configuration, can later be used to form the input to one of the +Aqua :ref:`quantum-algorithms`. + +As mentioned above, the intermediate data extracted from the classical computational software +consists of the following: + +1. One- and two-body integrals in Molecular Orbital (MO) basis +2. Dipole integrals +3. Molecular orbital coefficients +4. Hartree-Fock energy +5. Nuclear repulsion energy + +Once extracted, the structure of this intermediate data is independent of the classical driver +that was used to compute it. +However, the level of accuracy of such data does depend on the computational chemistry software; +more elaborate software packages are more likely to produce more accurate data. + +Qiskit Chemistry offers the option to serialize this data in a binary format known as +`Hierarchical Data Format 5 (HDF5) `__. +This is done for future reuse and exchange of input data among researchers who may not have a +particular computational +chemistry driver installed on their computers, or may have a different version of that driver. +HDF5 is configured as a prebuilt driver in Aqua because it allows for chemistry input to be passed +into the computation. In fact, HDF5 is the only driver that does not require any installation +other the installation of Qiskit Chemistry itself. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Generation of an HDF5 Input File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The most intuitive way to generate an HDF5 input file is by using the Qiskit Chemistry +:ref:`qiskit-chemistry-gui`. +Through the GUI, you can load an existing :ref:`qiskit-chemistry-input-file` from the ``chemistry`` +folder of the `Qiskit Tutorials GitHub repository `__ +(which must have been installed on your file system via a ``git clone`` command) +by selecting **Open...** from the **File** menu. Alternatively, you can create and then potentially +customize a brand new :ref:`qiskit-chemistry-input-file` by choosing **New** from the **File** menu. +Once you have configured the chemistry experiment in one of the existing classical drivers +(:ref:`gaussian-16`, :ref:`psi4`, :ref:`pyscf` or :ref:`pyquante`), +you can specify the name of the file where you want the HDF5 file to be serialized. This can be +done by assigning a value to the ``hdf5_output`` field of the ``driver`` section. +Upon completing its execution, Qiskit Chemistry displays the following message: + +.. code:: sh + + HDF5 file saved '/Users/username/Documents/temp/molecule.hdf5' + +assuming that ``molecule.hdf5`` and ``/Users/username/Documents/temp`` are the file name +and directory path you chose, respectively. + +Using the GUI is the most intuitive option to generate the HDF5 file corresponding to a given +experiment. The same result can be obtained by assigning a value to the ``hdf5_output`` field of +the ``driver`` section of an :ref:`qiskit-chemistry-input-file` and then invoking the Qiskit +Chemistry :ref:`qiskit-chemistry-command-line` tool with the name of that file as the input +parameter. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Using an HDF5 File as the Input to an Experiment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If you later want the HDF5 file to be deserialized and its contents used as the input for a +chemistry experiment, you can select ``HDF5`` as the driver in an +:ref:`qiskit-chemistry-input-file`. Doing so will require the ``hdf5`` section in the input +file to be configured by assigning a valid fully qualified file name to the ``hdf5_input`` +field, as shown: + +.. code:: python + + &hdf5 + hdf5_input=molecule.hdf5 + &end diff --git a/docs/aqua/chemistry/qiskit_chemistry_execution.rst b/docs/aqua/chemistry/qiskit_chemistry_execution.rst index b58d1a4781e3..7e6b341672eb 100644 --- a/docs/aqua/chemistry/qiskit_chemistry_execution.rst +++ b/docs/aqua/chemistry/qiskit_chemistry_execution.rst @@ -174,7 +174,7 @@ nothing preventing a user from accessing the Qiskit Chemistry APIs and programming an experiment step by step, Qiskit Chemistry lets you build a Python dictionary from an :ref:`qiskit-chemistry-input-file`. This can be achieved via the :ref:`qiskit-chemistry-gui` -by loading (or creating from scratch) the input file representing the +by loading (or creating from scratch) the input file representing the configuration of the desired experiment, and by then selecting **Export Dictionary** from the **File** menu. Assuming that the programmer assigns the exported dictionary to variable ``qiskit_chemistry_dict``, then the @@ -214,7 +214,7 @@ classical algorithm. A comparison with the :ref:`Hartree-Fock` energy is also o qiskit_chemistry_qpe_dict = { 'driver': {'name': 'PYSCF'}, 'PYSCF': { - 'atom': molecule, + 'atom': molecule, 'basis': 'sto3g' }, 'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'}, @@ -252,9 +252,9 @@ classical algorithm. A comparison with the :ref:`Hartree-Fock` energy is also o print('The Hartree-Fock ground-state energy is {}.'.format(result_ees['hf_energy'])) More complex examples include -`plotting the dissociation curve +`plotting the dissociation curve `__ -or `comparing results obtained via different algorithms +or `comparing results obtained via different algorithms `__. ^^^^^^^^^^^^^^^^^ @@ -367,7 +367,7 @@ Here is another example showing again how to configure the same LiH molecule as this time using the :ref:`psi4` driver. Here, ``PSI4`` is named as the driver to be used and the ``psi4`` section contains the molecule and basis set (or sets) directly in a form that PSI4 understands. The -language in which the molecular configuration is input is +language in which the molecular configuration is input is the input-file language for PSI4, and thus should be familiar to existing users of PSI4, who may have already collected such an input file from previous experiments and whose only job at this point would be to copy and paste @@ -438,7 +438,7 @@ the algorithm. The following parameters may be set: from the Hartree Fock reference state. For trial wave functions in Aqua, such as :ref:`uccsd`, the p/h Hamiltonian can improve the speed of convergence of the - :ref:`vqe` algorithm in the calculation of the electronic ground state properties. + :ref:`vqe` algorithm in the calculation of the electronic ground state properties. More information on the particle-hole formalism can be found in `arXiv:1805.04340 `__. @@ -466,7 +466,7 @@ the algorithm. The following parameters may be set: without loss of precision by setting the ``two_qubit_reduction`` parameter to ``True``, as explained next. 3. ``bravyi_kitaev`` corresponds to the :ref:`bravyi-kitaev` transformation, - also known as *binary-tree-based qubit mapping*. + also known as *binary-tree-based qubit mapping*. - A Boolean flag specifying whether or not to apply the precision-preserving two-qubit reduction optimization: @@ -486,7 +486,7 @@ the algorithm. The following parameters may be set: - The maximum number of workers used when forming the input to the Aqua quantum algorithm: - .. code:: python + .. code:: python max_workers = 1 | 2 | ... @@ -498,7 +498,7 @@ the algorithm. The following parameters may be set: - A Boolean value indicating whether or not to freeze the core orbitals in the computation: - .. code:: python + .. code:: python freeze_core : bool @@ -524,7 +524,7 @@ the algorithm. The following parameters may be set: to be removed from the subsequent computation. The list should be indices of the orbitals from ``0`` to ``n - 1``, where the electronic structure has ``n`` orbitals. - + For ease of referring to the higher orbitals, the list also supports negative values with ``-1`` being the highest unoccupied orbital, ``-2`` the next one down, and so on. @@ -598,7 +598,7 @@ In the ``algorithm`` section, algorithms are disambiguated using the declarative names by which Aqua recognizes them, based on the JSON schema each algorithm must provide according to the Aqua ``QuantumAlgorithm`` API, -as explained in the documentation on both +as explained in the documentation on both quantum and classical reference algorithms. The declarative name is specified as the ``name`` parameter in the ``algorithm`` section. The default value for the ``name`` parameter is ``VQE``, corresponding @@ -652,7 +652,7 @@ is selected along with the :ref:`l-bfgs-b` optimizer and the Aqua allows for configuring the *backend*, which is the quantum machine on which a quantum experiment will be run. -This configuration requires specifying +This configuration requires specifying the `Qiskit Terra `__ quantum computational provider and backend to be used for computation, which is done by assigning a ``str`` value to the ``"provider"`` and ``"name"`` parameters of the ``"backend"`` section: @@ -662,30 +662,32 @@ the ``"provider"`` and ``"name"`` parameters of the ``"backend"`` section: "provider" : string "name" : string -The value of the ``"provider"`` parameter indicates the full name of a class derived from ``"BaseProvider"`` -or global variable pointing to a instance of this class. +The value of the ``"provider"`` parameter indicates the full name of a class derived from +``"BaseProvider"`` or global variable pointing to a instance of this class. The value of the ``"name"`` parameter indicates either a real-hardware quantum computer or a quantum simulator accessed from the provider. Terra comes with two predefined providers: ``"qiskit.BasicAer"`` and ``"qiskit.IBMQ"``. By installing ``"qiskit-aer"``, the ``"qiskit.Aer"`` provider gets included too. -Each provider has its own set of simulators and ``"qiskit.IBMQ"`` gives access to real-hardware quantum -computer or simulators in the cloud. +Each provider has its own set of simulators and ``"qiskit.IBMQ"`` gives access to real-hardware +quantum computer or simulators in the cloud. For the ``"qiskit.IBMQ"`` provider, you need to configure it with a token and possibly url proxies. The Chemistry GUI greatly simplifies it via a user friendly interface, accessible through the **Preferences...** menu item. -Otherwise you need to configure programmatically using Qiskit Terra ` apis. +Otherwise you need to configure programmatically using Qiskit Terra ` +apis. .. topic:: Backend Configuration --- Quantum vs. Classical Algorithms: - Although Aqua is mostly a library of :ref:`quantum-algorithms`, - it also includes a number of :ref:`classical-reference-algorithms`, - which can be selected to generate reference values - and compare and contrast results in quantum research experimentation. - Since a classical algorithm runs on a classical computer, - no backend should be configured when a classical algorithm - is selected in the ``algorithm`` section. - Accordingly, the Qiskit Chemistry :ref:`qiskit-chemistry-gui` will automatically - disable the ``backend`` configuration section - whenever a non-quantum algorithm is selected. + + Although Aqua is mostly a library of :ref:`quantum-algorithms`, + it also includes a number of :ref:`classical-reference-algorithms`, + which can be selected to generate reference values + and compare and contrast results in quantum research experimentation. + Since a classical algorithm runs on a classical computer, + no backend should be configured when a classical algorithm + is selected in the ``algorithm`` section. + Accordingly, the Qiskit Chemistry :ref:`qiskit-chemistry-gui` will automatically + disable the ``backend`` configuration section + whenever a non-quantum algorithm is selected. Configuring the backend to use by an algorithm in the :ref:`quantum-algorithms` library requires setting the following parameters too: @@ -697,12 +699,12 @@ requires setting the following parameters too: shots : int This parameter applies, in particular to the local QASM simulator and any real quantum device. - The default value is ``1024``. - + The default value is ``1024``. + - A ``bool`` value indicating whether or not the circuit should undergo optimization: .. code:: python - + skip_transpiler : bool The default value is ``False``. If ``skip_transpiler`` is set to ``True``, then @@ -783,13 +785,13 @@ in chemistry include energy and excited states. Generating Repeatable Experiments ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Aspects of the computation may include use of random numbers. For instance, +Aspects of the computation may include use of random numbers. For instance, :ref:`vqe` -is coded to use a random initial point if the variational form chosen from the +is coded to use a random initial point if the variational form chosen from the :ref:`variational-forms` library does not supply any preference based on the initial state and if the -user does not explicitly supply an initial point. +user does not explicitly supply an initial point. In this case, each run of VQE, for what would otherwise be a constant problem, can produce a different result, causing non-determinism and the inability to replicate the same result across different runs with @@ -863,15 +865,15 @@ complicated settings: auto_substitutions : bool -When this parameter is set to ``True``, which is the default, the values of parameters +When this parameter is set to ``True``, which is the default, the values of parameters ``num_particles`` and ``num_orbitals`` are automatically computed by Qiskit Chemistry for sections ``initial_state`` and ``variational_form`` when ``UCCSD`` and ``Hartree-Fock`` are selected, respectively. As such, -the configuration of these two parameters is disabled; the user will not be required, or even allowed, -to assign values to +the configuration of these two parameters is disabled; the user will not be required, or even +allowed, to assign values to these two parameters. This is also reflected in the :ref:`qiskit-chemistry-gui`, where -these two parameters will be grayed out and uneditable when ``auto_substitutions`` is set to ``True``. -Furthermore, Qiskit Chemistry automatically sets +these two parameters will be grayed out and uneditable when ``auto_substitutions`` is set to +``True``. Furthermore, Qiskit Chemistry automatically sets parameters ``qubit_mapping`` and ``two_qubit_reduction`` in sections ``initial_state`` and ``variational_form`` when ``UCCSD`` and ``Hartree-Fock`` are selected, respectively. Specifically, Qiskit Chemistry sets ``qubit_mapping`` and ``two_qubit_reduction`` @@ -880,8 +882,8 @@ of the input file in order to enforce parameter-value matching across these thre sections. As a result, the user will only have to configure ``qubit_mapping`` and ``two_qubit_reduction`` in the ``operator`` section; the configuration of these two parameters in sections ``initial_state`` and ``variational_form`` is disabled, -as reflected also in the :ref:`qiskit-chemistry-gui`, where the values of these two parameters are only -editable in the ``operator`` section, while the parameters themselves are grayed out in the +as reflected also in the :ref:`qiskit-chemistry-gui`, where the values of these two parameters are +only editable in the ``operator`` section, while the parameters themselves are grayed out in the ``initial_state`` and ``variational_form`` sections. On the other hand, if ``auto_substitutions`` is set to ``False``, diff --git a/docs/aqua/chemistry/qiskit_chemistry_extending.rst b/docs/aqua/chemistry/qiskit_chemistry_extending.rst index 13b6047d875a..b90ce1e8d68f 100644 --- a/docs/aqua/chemistry/qiskit_chemistry_extending.rst +++ b/docs/aqua/chemistry/qiskit_chemistry_extending.rst @@ -1,22 +1,22 @@ .. _qiskit-chemistry-extending: -============================== +================================ Contributing to Qiskit Chemistry -============================== +================================ -Qiskit Chemistry, just like the Aqua library it is built upon, has a modular and extensible architecture. +Qiskit Chemistry, just like the Aqua library it is built upon, has a modular and extensible +architecture. -Instead of just *accessing* Qiskit Chemistry as a library of quantum algorithms and tools to experiment with quantum -computing for chemistry, a user may decide to *contribute* to Qiskit Chemistry by -providing new components. -These can be programmatically added to Qiskit Chemistry, -which was designed as an extensible, pluggable -framework. Once added, new components are automatically discovered. +Instead of just *accessing* Qiskit Chemistry as a library of quantum algorithms and tools to +experiment with quantum computing for chemistry, a user may decide to *contribute* to Qiskit +Chemistry by providing new components. These can be programmatically added to Qiskit Chemistry, +which was designed as an extensible, pluggable framework. Once added, new components are +automatically discovered. .. topic:: Contribution Guidelines - Any user who would like to contribute to Aqua or Qiskit Chemistry should follow the Aqua `contribution - guidelines `__. + Any user who would like to contribute to Aqua or Qiskit Chemistry should follow the Aqua + `contribution guidelines `__. --------------------------------- Dynamically Discovered Components @@ -27,33 +27,33 @@ by providing new components, which will be automatically discovered and loaded b Each component should derive from the corresponding base class, as explained below. There are two ways for a component to be dynamically discovered and loaded by Qiskit Chemistry at run time: -1. The class implementing the component should be placed in the appropriate folder in the file system, - as explained in `Section "Extension Points" <#extension-points>`__ below for each different component type. - This is the easiest approach. Researchers - and developers extending Qiskit Chemistry are more likely to have installed Qiskit Chemistry by cloning the - `Qiskit Chemistry GitHub repository `__ as opposed to using - the pip package manager system. Therefore, the folders indicated below can be easily located in the file system. - -2. Alternatively, a developer extending Qiskit Chemistry with a new component can simply create a dedicated - repository with its own versioning. This repository must be locally installable with the package that was - created. It simply consists of customizing the - ``setup.py`` fadding the entry points for ``qiskit.chemistry.drivers`` and or - ``qiskit.chemistry.operators`` as shown below. - The format is: ``anyname = full_package:class_name``. Each class must be included separately. - When someone installs the package, the extensions will be automatically registered: +1. The class implementing the component should be placed in the appropriate folder in the file + system, as explained in `Section "Extension Points" <#extension-points>`__ below for each + different component type. This is the easiest approach. Researchers and developers extending + Qiskit Chemistry are more likely to have installed Qiskit Chemistry by cloning the + `Qiskit Chemistry GitHub repository `__ as opposed + to using the pip package manager system. Therefore, the folders indicated below can be easily + located in the file system. + +2. Alternatively, a developer extending Qiskit Chemistry with a new component can simply create a + dedicated repository with its own versioning. This repository must be locally installable with + the package that was created. It simply consists of customizing the ``setup.py`` fadding the + entry points for ``qiskit.chemistry.drivers`` and or ``qiskit.chemistry.operators`` as shown + below. The format is: ``anyname = full_package:class_name``. Each class must be included + separately. When someone installs the package, the extensions will be automatically registered: .. code:: python import setuptools long_description = """New Package for Qiskit Chemistry Component""" - + requirements = [ "qiskit-chemistry>=0.4.2", "qiskit-terra>=0.7.0,<0.8", "numpy>=1.13" ] - + setuptools.setup( name = 'qiskit_chemistry_custom_component_package', version = "0.1.0", # this should match __init__.__version__ @@ -108,15 +108,15 @@ Qiskit Chemistry exposes two extension points: Chemistry Drivers ^^^^^^^^^^^^^^^^^ -The driver support in Qiskit Chemistry was designed to make the :ref:`drivers` pluggable and discoverable. -In order for Qiskit Chemistry to -be able to interface a driver library, the ``BaseDriver`` base class must be implemented so to -provide the interfacing code, or *wrapper*. As part of this process, the required -`JavaScript Object Notation (JSON) `__ schema for the driver interface must -be supplied in a CONFIGURATION static property in the class. The interfacing code in the driver wrapper -is responsible for constructing and populating a ``QMolecule`` instance with the electronic -structure data listed above. Driver wrappers implementing the ``BaseDriver`` class are organized -in subfolders of the ``drivers`` folder for automatic discovery and dynamic lookup. +The driver support in Qiskit Chemistry was designed to make the :ref:`drivers` pluggable and +discoverable. In order for Qiskit Chemistry to be able to interface a driver library, the +``BaseDriver`` base class must be implemented so to provide the interfacing code, or *wrapper*. +As part of this process, the required `JavaScript Object Notation (JSON) `_ +schema for the driver interface must be supplied in a CONFIGURATION static property in the class. +The interfacing code in the driver wrapper is responsible for constructing and populating a +``QMolecule`` instance with the electronic structure data listed above. Driver wrappers +implementing the ``BaseDriver`` class are organized in subfolders of the ``drivers`` folder for +automatic discovery and dynamic lookup. .. _chemistry-operators: @@ -125,19 +125,20 @@ Chemistry Operators ^^^^^^^^^^^^^^^^^^^ Chemistry operators convert the electronic structure information obtained from the -drivers to qubit-operator forms, suitable to be processed by the Aqua :ref:`quantum-algorithms`. New chemistry operators -can be plugged in by extending the ``ChemistryOperator`` interface and providing the required -`JavaScript Object Notation (JSON) <>`__ schema in a CONFIGURATION static property in the class. -Chemistry operator implementations are collected in the ``core`` folder -for automatic discovery and dynamic lookup. +drivers to qubit-operator forms, suitable to be processed by the Aqua :ref:`quantum-algorithms`. +New chemistry operators can be plugged in by extending the ``ChemistryOperator`` interface and +providing the required `JavaScript Object Notation (JSON) `_ schema in a +CONFIGURATION static property in the class. Chemistry operator implementations are collected in +the ``core`` folder for automatic discovery and dynamic lookup. ---------- Unit Tests ---------- -Contributing new software components to Qiskit Chemistry requires writing new unit tests for those components, -and executing all the existing unit tests to make sure that no bugs were inadvertently injected. +Contributing new software components to Qiskit Chemistry requires writing new unit tests for those +components, and executing all the existing unit tests to make sure that no bugs were inadvertently +injected. ^^^^^^^^^^^^^^^^^^ Writing Unit Tests @@ -170,8 +171,8 @@ The command for help is as follows: python -m unittest -h -`Other running options `__ are available -to users for consultation. +`Other running options `_ +are available to users for consultation. In order to see unit test log messages, researchers and developers contributing to Aqua will need to set the ``LOG_LEVEL`` environment variable to ``DEBUG`` mode: diff --git a/docs/aqua/chemistry/qiskit_chemistry_installation.rst b/docs/aqua/chemistry/qiskit_chemistry_installation.rst index a77552dfc859..3c667384deb2 100644 --- a/docs/aqua/chemistry/qiskit_chemistry_installation.rst +++ b/docs/aqua/chemistry/qiskit_chemistry_installation.rst @@ -24,19 +24,20 @@ comes with all of these dependencies pre-installed. Code Installation ----------------- -We encourage you to install Qiskit Chemistry via the `pip `__ package management system: +We encourage you to install Qiskit Chemistry via the `pip `__ +package management system: .. code:: sh pip install qiskit-chemistry -pip will handle all dependencies automatically (including the dependencies on Aqua and Qiskit Core). and you will always -install the latest (and well-tested) release version. +pip will handle all dependencies automatically (including the dependencies on Aqua and +Qiskit Core). and you will always install the latest (and well-tested) release version. If your intention is not so much to access Qiskit Chemistry -as a tool to perform chemistry computations on a quantum machine, but rather to extend Qiskit Chemistry -with new research contributions --- such as new algorithms, algorithm components, input-translation operators or drivers --- -then it is advisable to clone both the +as a tool to perform chemistry computations on a quantum machine, but rather to extend Qiskit +Chemistry with new research contributions --- such as new algorithms, algorithm components, +input-translation operators or drivers --- then it is advisable to clone both the `Qiskit Chemistry `__ and `Aqua `__ Git repositories in order to have easier access to the source code of the various components. @@ -52,27 +53,30 @@ Jupyter Notebooks and input files for Qiskit Chemistry are included as part of t Installation of Chemistry Drivers --------------------------------- -To run chemistry experiments on various molecules, you will also need to install one of the supported -classical computational chemistry programs, or *drivers*, -interfaced by Qiskit Chemistry. +To run chemistry experiments on various molecules, you will also need to install one of the +supported classical computational chemistry programs, or *drivers*, interfaced by Qiskit Chemistry. Currently, Qiskit Chemistry comes with built-in interfaces for four drivers: 1. `Gaussian™ 16 `__, a commercial chemistry program 2. `PSI4 `__, an open-source chemistry program built on Python 3. `PySCF `__, an open-source Python chemistry program -4. `PyQuante `__, a pure cross-platform open-source Python chemistry program +4. `PyQuante `__, a pure cross-platform open-source Python + chemistry program While the logic to -interface these drivers is supplied as part of the Qiskit Chemistry installation, the dependent chemistry programs -need to be installed separately. This can be done by following the instructions provided in Section ":ref:`drivers`". -Supporting additional drivers in Qiskit Chemistry can be easily achieved by extending the ``BaseDriver`` interface. - -Even without installing any of the drivers above, it is still possible to run chemistry experiments by passing -to the inout-translation layer a Hierarchical Data Format 5 (HDF5) binary file serializing the intermediate data -previously generated by one of the supported chemistry drivers. This offers researchers the opportunity to share -chemistry input files and replicate each other's results. Given its support to take an HDF5 files as the input to initiate a chemistry experiment, +interface these drivers is supplied as part of the Qiskit Chemistry installation, the dependent +chemistry programs need to be installed separately. This can be done by following the +instructions provided in Section ":ref:`drivers`". Supporting additional drivers in Qiskit +Chemistry can be easily achieved by extending the ``BaseDriver`` interface. + +Even without installing any of the drivers above, it is still possible to run chemistry experiments +by passing to the inout-translation layer a Hierarchical Data Format 5 (HDF5) binary file +serializing the intermediate data previously generated by one of the supported chemistry drivers. +This offers researchers the opportunity to share chemistry input files and replicate each other's +results. Given its support to take an HDF5 files as the input to initiate a chemistry experiment, Qiskit Chemistry lists HDF5 as an additional driver --- in fact, the only built-in driver coming with Qiskit Chemistry. - + A few sample HDF5 files are provided as input files in the ``chemistry`` folder of the -`Qiskit Tutorials `__ repository. +`Qiskit Tutorials `__ +repository. diff --git a/docs/aqua/chemistry/qiskit_chemistry_overview.rst b/docs/aqua/chemistry/qiskit_chemistry_overview.rst index fbf0214f1357..c5b5a8613b91 100644 --- a/docs/aqua/chemistry/qiskit_chemistry_overview.rst +++ b/docs/aqua/chemistry/qiskit_chemistry_overview.rst @@ -1,320 +1,322 @@ -.. _aqua-chemistry-overview: - -======== -Overview -======== - -Qiskit Chemistry is a set of tools and algorithms that enable experimenting with chemistry problems -via quantum computing. Qiskit Chemistry translates chemistry-specific problems into inputs for an algorithm from the Aqua :ref:`quantum-algorithms` library, -which in turn uses `Qiskit Terra `__ for the actual quantum computation. - -Qiskit Chemistry allows users with different levels of experience to execute chemistry experiments and -contribute to the quantum computing chemistry software stack. -Users with pure chemistry background can continue to configure chemistry -problems according to their favorite computational chemistry software packages, called *drivers*. -These users do not need to learn the -details of quantum computing; Qiskit Chemistry translates any chemistry program configuration entered by -those users in one of their favorite drivers into quantum-specific input. -For these to work, the following simple requirements must be met: - -- The driver chosen by the user should be installed on the same system in which - Qiskit Chemistry is also installed. -- The appropriate software license for that driver must be in place. -- An interface to that driver must be built in Qiskit Chemistry as a ``BaseDriver`` extension - point. - -Currently, Qiskit Chemistry comes with interfaces prebuilt -for the following four computational chemistry software drivers: - -1. :ref:`gaussian-16`, a commercial chemistry program -2. :ref:`psi4`, an open-source chemistry program built on Python -3. :ref:`pyscf`, an open-source Python chemistry program -4. :ref:`pyquante`, a pure Python cross-platform open-source chemistry program - -Additional chemistry drivers can easily be added via the ``BaseDriver`` extension point. Once an interface -for a driver installed in the system has been implemented, that driver will be automatically loaded at run time -and made available in Qiskit Quantum Chemistry for running experiments. - -Once Qiskit Chemistry has been installed, a user can execute chemistry experiments -on a quantum machine by using either the :ref:`qiskit-chemistry-gui` or -:ref:`qiskit-chemistry-command-line` supplied tools, or the :ref:`qiskit-chemistry-programmable-interface`. -Either option enforces schema-based configuration correctness. - -.. topic:: Contributing to Qiskit Chemistry - - Instead of just *accessing* Qiskit Chemistry as a tool to experiment with chemistry problems - on a quantum machine, a user may decide to *contribute* to Qiskit Chemistry by - providing new algorithms, algorithm components, input translators, and driver interfaces. - Algorithms and supporting components may be programmatically added to - :ref:`aqua-library`, which was designed as an extensible, pluggable - framework in order to address the needs of research and developers interested in - :ref:`aqua-extending`. - Qiskit Chemistry utilizes a similar framework for drivers and the core computation - performed at the input-translation layer. - - If you would like to contribute to Qiskit Chemistry, please follow the - Qiskit Chemistry `contribution - guidelines `__. - - ----------------------------- -Modularity and Extensibility ----------------------------- - -Qiskit Chemistry is built on top of :ref:`aqua-library`. Just like Aqua, -it is specifically designed to be extensible at each level of the software stack. -This allows different users with different levels of expertise and different scientific interests -to contribute to, and extend, the Qiskit Chemistry software stack at different levels. In addition to the extension -points offered by the underlying Aqua library, Qiskit Chemistry allows a user to plug in new algorithms -and new operators for translating classical inputs into inputs for quantum algorithms. - -~~~~~~~~~~~~~~~~ -Input Generation -~~~~~~~~~~~~~~~~ - -At the application level, Aqua allows for classical computational -software to be used as the quantum application front end. This module is extensible; -new computational software can be easily plugged in. Behind the scenes, Aqua lets that -software perform some initial computations classically. The results of those computations are then -combined with the problem -configuration and translated into input for one or more quantum algorithms, which invoke -the Qiskit code Application Programming Interfaces (APIs) to build, compile and execute quantum circuits. - -The following code is the configuration file, written in Gaussian™ 16, of a molecule of hydrogen, -whose two hydrogen atoms are -placed at a distance of :math:`0.735` Å: - -.. code:: - - # rhf/STO-3G scf(conventional) - - h2 molecule - - 0 1 - H 0.0 0.0 -0.3675 - H 0.0 0.0 0.3675 - -Qiskit Chemistry uses this molecular configuration as an input to the computational -chemistry software --- in the case above, Gaussian 16. The computational chemistry software -package is executed classically --- not to compute the ground-state energy, -dipole moment, or excited states of the given molecule, since these expensive computations -are delegated to the underlying quantum machine, but only to the extent necessary to compute -some intermediate data which, -combined with the molecular configuration above, can later be used to form the input to the -quantum algorithm in Aqua. The information that needs to be extracted from the -computational chemistry software is configured when building the interface between -to the computational software package from within Aqua. - -The intermediate data extracted from the classical computational software consists -of the following: - -1. One- and two-body integrals in Molecular Orbital (MO) basis -2. Dipole integrals -3. Molecular orbital coefficients -4. :ref:`hartree-fock` energy -5. Nuclear repulsion energy - -Once extracted, the structure of this intermediate data is independent of the -computational chemistry software that was used to compute it. However, -the level of accuracy of such data does depend on the computational chemistry software; -more elaborate software packages are more likely to produce more accurate data. - -Qiskit Chemistry offers the option to serialize this data in a binary format known as -`Hierarchical Data Format 5 (HDF5) `__. -This is done to enable future reuse of previously computed -input data. This feature also enables researchers to exchange -input data among each other --- which turns out to be particularly useful to researchers who may not have -particular computational chemistry drivers -installed on their computers. HDF5 is configured as a prebuilt driver in -Qiskit Chemistry because it allows for chemistry input to be passed into the -computation. - -~~~~~~~~~~~~~~~~~ -Input Translation -~~~~~~~~~~~~~~~~~ - -The problem configuration and the additional intermediate data -obtained from the classical execution of one of computational chemistry drivers are -combined and then transformed to form the input to the quantum system. This phase, known as *translation*, -is also extensible. Practitioners interested in providing more efficient -translation operators may do so by extending this layer of the Aqua software -stack with their own implementation of the ``ChemistryOperator`` class. - -In the reference implementation provided by Qiskit Chemistry, the translation phase -takes the input generated by the classical execution of the computational chemistry driver -and generates first a fermionic operator, and from this a qubit operator, which becomes -the input to one of the quantum algorithms in Aqua. - --------------- -Novel Features --------------- - -Qiskit Chemistry present some unique advantages -in terms of usability, functionality, and configuration-correctness enforcement. - -~~~~~~~~~~~~~~~ -User Experience -~~~~~~~~~~~~~~~ - -Allowing classical computational chemistry software at the front end has its own important advantages. -In fact, at the top of the Qiskit Chemistry software stack are chemists -who are most likely very familiar with existing -computational chemistry software. These practitioners may be interested -in experimenting with the benefits of quantum computing in terms of performance, accuracy -and reduction of computational complexity, but at the same time they might be -unwilling to learn about the underlying quantum infrastructure. Ideally, -such practitioners would like to use a computational chemistry driver they are -used to as a front end to the quantum computing system, without having to learn a new quantum programming -language of new APIs. It is also -likely that such practitioners may have collected, over time, numerous -chemistry problem configurations, corresponding to various experiments. -Qiskit Chemistry is designed to accept those -configuration files with no modifications, and -without requiring a chemist to -have to learn a quantum programming language. This approach has a clear advantage in terms -of usability. - -~~~~~~~~~~~~~ -Functionality -~~~~~~~~~~~~~ - -If Qiskit Chemistry had been designed to interpose a quantum programming language -or new APIs between the user and the classical computational chemistry software drivers, -it would not have been able to -fully exploit all the features of those drivers unless all such features -had been exposed by the higher programming-language or API. In other words, in order to drive -the classical execution of any interfaced computational chemistry driver -to perform the most precise computation of the intermediate data needed to form -the quantum input, the advanced features of that driver would have had to be configurable through Aqua -Chemistry. The ability of Aqua to directly interface classical computational software allows that software -to compute the intermediate data needed to form the quantum input at its highest level of precision. - -To better illustrate this point, consider the ability of popular computational chemistry :ref:`drivers`, such as -:ref:`gaussian-16`, :ref:`psi4` and :ref:`pyscf` --- all interfaced by Qiskit Chemistry --- to accept the configuration of -a molecule where different atoms are represented in different basis sets, as opposed to having to necessarily impose -one single basis set for all the atoms. As an example, the following code snippet, written in the PSI4 language, -individually configures the basis sets for the atoms of a molecule of benzene, -whose chemical formula is :math:`C_6H_6`, indicating the fact that the molecule comprises six atoms of carbon -and six of hydrogen: - -.. code:: - - basis { - assign DZ - assign C 3-21G - assign H1 STO-3G - assign C1 STO-3G - } - -Here, the chemist has chosen to use basis DZ for all atoms via the first assignment. The second assignment overwrites -such statement for all six carbon atoms, which will be represented via the 3-21G basis set. The third statement -assigns basis set STO-3G to one particular hydrogen atom --- the one with index 1 --- while all the other five hydrogen -atoms keep basis set DZ. Finally, the last statement assigns basis set STO-3G to the one carbon atom with index -1, leaving the remaining five carbon atoms with basis set 3-21G as per the second assignment. - -Qiskit Chemistry would have no problem supporting this fine-grained basis set specification, since -it allows the computational chemistry drivers to be the front end to the system, with no additional -layer on top of them. Conversely, other systems that have chosen to interpose a new programming language -or new APIs in front of the computational drivers currently do not support the assignment -of different basis sets to different atoms in the same molecules. In order to support -such advanced, fine-grained configurations, those systems will have to support the APIs for the different -basis sets to be specified, and map them to all of the underlying drivers. - -Fine-grained basis-set specification is only one example of the functionality of -the computational chemistry drivers directly exposed by Qiskit Chemistry. Another --- perhaps even more -important --- example has to do with the :ref:`hartree-fock` wave function, -which is computed by the underlying driver and allows for the computation of the one- -and two-body MO integrals, which in turn are used to determine -the full Configuration Interaction (CI) wave function and the :ref:`uccsd` -wave function, among other things. Computational chemistry software drivers -expose configuration parameters to make the computation of the -Hartree-Fock wave function converge, should the default parameter values fail. -Qiskit Chemistry has no problem supporting such advanced configuration parameters, -which would be passed directly into the configuration file as an input to the underlying driver. Conversely, -solutions that have chosen to interpose a new programming language or new APIs between the user and -the underlying drivers currently do not support customizing the parameters for facilitating -the convergence of the computation of the Hartree-Fock wave function. In order for these alternative -solutions to allow for this type of customization, the parameters would have to be exposed through the -programming language or the APIs. As a result, such alternative solutions -may not be able to get the integrals -that need to be used in the full CI or UCCSD calculations. - -Let us consider yet another example illustrating why a direct use of the classical computational chemistry -software is superior to the choice of interposing a new programming language or API between the user -and the driver. It has been `demonstrated `__ -that taking into account a molecule's spatial symmetries -can be used to reduce the number of qubits necessary to model that molecule and compute its energy -properties. Computational chemistry software packages allow for configuring spatial symmetries -in their input files. Thus, Qiskit Chemistry can immediately take direct advantage of such feature -exposed by the underlying computational software packages and obtain from those packages -intermediate data that is already optimized with respect to the symmetries configured by the user. -As a result, energy computations performed by Qiskit Chemistry require fewer qubits when -a spatial symmetries are present in a molecule. -Conversely, other solutions that interpose a new programming language or APIs fail to expose -this configuration feature to their users unless an ad-hoc symmetry API is constructed, which must then be mapped -to all the underlying software packages interfaced by those solutions. To make things more complicated, -for any new software package that is interfaced by those solutions, that symmetry API will have to be -programmatically mapped to the package's symmetry configuration feature. - -In essence, interposing a new language or new APIs between the user and the underlying -classical drivers severely limits the functionality of the whole system, unless the new -language or APIs interfacing the drivers match the union of all the configuration parameters -of all the possible computational drivers that are currently supported by the system, or -that will be supported in the future. - -~~~~~~~~~~~~~~~~~~~~~~~~~ -Configuration Correctness -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Qiskit Chemistry offers another unique feature. Given that Qiskit Chemistry -allows traditional software to be executed on a quantum system, -configuring a chemistry experiment definitely requires setting up a hybrid -configuration, which involves configuring both chemistry- and quantum-specific -parameters. The chances of introducing configuration -errors, making typos, or selecting incompatible configuration parameters -are very high, especially for people who are expert in chemistry -but new to the realm of quantum computing. - -For example, the number of qubits necessary to compute the ground-state energy or a molecule -depends on the number of spin orbitals of that molecule. The total number of qubits may -be reduced by applying various optimization techniques, such as the novel parity-map-based -precision-preserving two-qubit reduction. Further reductions may be achieved with various -approximations, such as the freezing of the core and the virtual-orbital removal. The number -of qubits to allocate to solve a particular problem should be computed by the system and not -exposed as a configuration parameter. Letting the user configure the number of qubits can -easily lead to a configuration parameter mismatch. - -Another scenario in which a user could misconfigure a problem would involve the -user associating algorithm components (such as optimizers and trial functions -for quantum variational algorithms) to algorithms that do not support such components. - -To address such issues, in -Aqua the problem-specific configuration information and the -quantum-specific configuration information are verified for correctness both at configuration time and at run time, -so that the combination of classical and quantum inputs is -resilient to configuration errors. Very importantly, configuration -correctness is dynamically enforced even for components that are -dynamically discovered and loaded. - -.. include:: ../../aqua/CONTRIBUTORS.rst - -------- -License -------- - -This project uses the `Apache License Version 2.0 software -license `__. - -Some code supplied by Qiskit Chemistry for interfacing -to external chemistry :ref:`drivers` has additional licensing: - -- The :ref:`gaussian-16` - driver - contains work licensed under the `Gaussian Open-Source Public - License `__. - -- The :ref:`pyquante` - driver - contains work licensed under the `modified BSD - license `__. - +.. _aqua-chemistry-overview: + +======== +Overview +======== + +Qiskit Chemistry is a set of tools and algorithms that enable experimenting with chemistry problems +via quantum computing. Qiskit Chemistry translates chemistry-specific problems +into inputs for an algorithm from the Aqua :ref:`quantum-algorithms` library, +which in turn uses `Qiskit Terra `__ for the actual +quantum computation. + +Qiskit Chemistry allows users with different levels of experience to execute +chemistry experiments and contribute to the quantum computing chemistry +software stack. Users with pure chemistry background can continue to configure +chemistry problems according to their favorite computational chemistry software +packages, called *drivers*. These users do not need to learn the details of +quantum computing; Qiskit Chemistry translates any chemistry program +configuration entered by those users in one of their favorite drivers into +quantum-specific input. For these to work, the following simple requirements +must be met: + +- The driver chosen by the user should be installed on the same system in which + Qiskit Chemistry is also installed. +- The appropriate software license for that driver must be in place. +- An interface to that driver must be built in Qiskit Chemistry as a ``BaseDriver`` extension + point. + +Currently, Qiskit Chemistry comes with interfaces prebuilt +for the following four computational chemistry software drivers: + +1. :ref:`gaussian-16`, a commercial chemistry program +2. :ref:`psi4`, an open-source chemistry program built on Python +3. :ref:`pyscf`, an open-source Python chemistry program +4. :ref:`pyquante`, a pure Python cross-platform open-source chemistry program + +Additional chemistry drivers can easily be added via the ``BaseDriver`` +extension point. Once an interface for a driver installed in the system has +been implemented, that driver will be automatically loaded at run time +and made available in Qiskit Quantum Chemistry for running experiments. + +Once Qiskit Chemistry has been installed, a user can execute chemistry +experiments on a quantum machine by using either the +:ref:`qiskit-chemistry-gui` or :ref:`qiskit-chemistry-command-line` supplied +tools, or the :ref:`qiskit-chemistry-programmable-interface`. Either option +enforces schema-based configuration correctness. + +.. topic:: Contributing to Qiskit Chemistry + + Instead of just *accessing* Qiskit Chemistry as a tool to experiment with chemistry problems + on a quantum machine, a user may decide to *contribute* to Qiskit Chemistry by + providing new algorithms, algorithm components, input translators, and driver interfaces. + Algorithms and supporting components may be programmatically added to + :ref:`aqua-library`, which was designed as an extensible, pluggable + framework in order to address the needs of research and developers interested in + :ref:`aqua-extending`. + Qiskit Chemistry utilizes a similar framework for drivers and the core computation + performed at the input-translation layer. + + If you would like to contribute to Qiskit Chemistry, please follow the + Qiskit Chemistry `contribution + guidelines `__. + + +---------------------------- +Modularity and Extensibility +---------------------------- + +Qiskit Chemistry is built on top of :ref:`aqua-library`. Just like Aqua, +it is specifically designed to be extensible at each level of the software stack. +This allows different users with different levels of expertise and different scientific +interests to contribute to, and extend, the Qiskit Chemistry software stack at different levels. +In addition to the extension points offered by the underlying Aqua library, Qiskit Chemistry +allows a user to plug in new algorithms and new operators for translating classical inputs +into inputs for quantum algorithms. + +~~~~~~~~~~~~~~~~ +Input Generation +~~~~~~~~~~~~~~~~ + +At the application level, Aqua allows for classical computational +software to be used as the quantum application front end. This module is extensible; +new computational software can be easily plugged in. Behind the scenes, Aqua lets that +software perform some initial computations classically. The results of those computations are +then combined with the problem configuration and translated into input for one or more quantum +algorithms, which invoke the Qiskit code Application Programming Interfaces (APIs) to build, +compile and execute quantum circuits. + +The following code is the configuration file, written in Gaussian™ 16, of a molecule of +hydrogen, whose two hydrogen atoms are placed at a distance of :math:`0.735` Å: + +.. code:: + + # rhf/STO-3G scf(conventional) + + h2 molecule + + 0 1 + H 0.0 0.0 -0.3675 + H 0.0 0.0 0.3675 + +Qiskit Chemistry uses this molecular configuration as an input to the computational +chemistry software --- in the case above, Gaussian 16. The computational chemistry software +package is executed classically --- not to compute the ground-state energy, +dipole moment, or excited states of the given molecule, since these expensive computations +are delegated to the underlying quantum machine, but only to the extent necessary to compute +some intermediate data which, +combined with the molecular configuration above, can later be used to form the input to the +quantum algorithm in Aqua. The information that needs to be extracted from the +computational chemistry software is configured when building the interface between +to the computational software package from within Aqua. + +The intermediate data extracted from the classical computational software consists +of the following: + +1. One- and two-body integrals in Molecular Orbital (MO) basis +2. Dipole integrals +3. Molecular orbital coefficients +4. :ref:`hartree-fock` energy +5. Nuclear repulsion energy + +Once extracted, the structure of this intermediate data is independent of the +computational chemistry software that was used to compute it. However, +the level of accuracy of such data does depend on the computational chemistry software; +more elaborate software packages are more likely to produce more accurate data. + +Qiskit Chemistry offers the option to serialize this data in a binary format known as +`Hierarchical Data Format 5 (HDF5) `__. +This is done to enable future reuse of previously computed +input data. This feature also enables researchers to exchange +input data among each other --- which turns out to be particularly useful to researchers who may +not have particular computational chemistry drivers installed on their computers. HDF5 is +configured as a prebuilt driver in Qiskit Chemistry because it allows for chemistry input to +be passed into the computation. + +~~~~~~~~~~~~~~~~~ +Input Translation +~~~~~~~~~~~~~~~~~ + +The problem configuration and the additional intermediate data +obtained from the classical execution of one of computational chemistry drivers are +combined and then transformed to form the input to the quantum system. This phase, known as +*translation*, is also extensible. Practitioners interested in providing more efficient +translation operators may do so by extending this layer of the Aqua software +stack with their own implementation of the ``ChemistryOperator`` class. + +In the reference implementation provided by Qiskit Chemistry, the translation phase +takes the input generated by the classical execution of the computational chemistry driver +and generates first a fermionic operator, and from this a qubit operator, which becomes +the input to one of the quantum algorithms in Aqua. + +-------------- +Novel Features +-------------- + +Qiskit Chemistry present some unique advantages +in terms of usability, functionality, and configuration-correctness enforcement. + +~~~~~~~~~~~~~~~ +User Experience +~~~~~~~~~~~~~~~ + +Allowing classical computational chemistry software at the front end has its own important +advantages. In fact, at the top of the Qiskit Chemistry software stack are chemists +who are most likely very familiar with existing computational chemistry software. These +practitioners may be interested in experimenting with the benefits of quantum computing +in terms of performance, accuracy and reduction of computational complexity, but at the +same time they might be unwilling to learn about the underlying quantum infrastructure. +Ideally, such practitioners would like to use a computational chemistry driver they are +used to as a front end to the quantum computing system, without having to learn a new quantum +programming language of new APIs. It is also likely that such practitioners may have collected, +over time, numerous chemistry problem configurations, corresponding to various experiments. +Qiskit Chemistry is designed to accept those configuration files with no modifications, and +without requiring a chemist to have to learn a quantum programming language. This approach has +a clear advantage in terms of usability. + +~~~~~~~~~~~~~ +Functionality +~~~~~~~~~~~~~ + +If Qiskit Chemistry had been designed to interpose a quantum programming language +or new APIs between the user and the classical computational chemistry software drivers, +it would not have been able to +fully exploit all the features of those drivers unless all such features +had been exposed by the higher programming-language or API. In other words, in order to drive +the classical execution of any interfaced computational chemistry driver +to perform the most precise computation of the intermediate data needed to form +the quantum input, the advanced features of that driver would have had to be configurable through +Aqua Chemistry. The ability of Aqua to directly interface classical computational software +allows that software to compute the intermediate data needed to form the quantum input at its +highest level of precision. + +To better illustrate this point, consider the ability of popular computational chemistry +:ref:`drivers`, such as :ref:`gaussian-16`, :ref:`psi4` and :ref:`pyscf` --- all interfaced by +Qiskit Chemistry --- to accept the configuration of a molecule where different atoms are +represented in different basis sets, as opposed to having to necessarily impose one single basis +set for all the atoms. As an example, the following code snippet, written in the PSI4 language, +individually configures the basis sets for the atoms of a molecule of benzene, whose chemical +formula is :math:`C_6H_6`, indicating the fact that the molecule comprises six atoms of carbon +and six of hydrogen: + +.. code:: + + basis { + assign DZ + assign C 3-21G + assign H1 STO-3G + assign C1 STO-3G + } + +Here, the chemist has chosen to use basis DZ for all atoms via the first assignment. The second +assignment overwrites such statement for all six carbon atoms, which will be represented via the +3-21G basis set. The third statement assigns basis set STO-3G to one particular hydrogen atom --- +the one with index 1 --- while all the other five hydrogen atoms keep basis set DZ. Finally, the +last statement assigns basis set STO-3G to the one carbon atom with index 1, leaving the remaining +five carbon atoms with basis set 3-21G as per the second assignment. + +Qiskit Chemistry would have no problem supporting this fine-grained basis set specification, since +it allows the computational chemistry drivers to be the front end to the system, with no additional +layer on top of them. Conversely, other systems that have chosen to interpose a new programming +language or new APIs in front of the computational drivers currently do not support the assignment +of different basis sets to different atoms in the same molecules. In order to support +such advanced, fine-grained configurations, those systems will have to support the APIs for the +different basis sets to be specified, and map them to all of the underlying drivers. + +Fine-grained basis-set specification is only one example of the functionality of +the computational chemistry drivers directly exposed by Qiskit Chemistry. Another --- perhaps +even more important --- example has to do with the :ref:`hartree-fock` wave function, +which is computed by the underlying driver and allows for the computation of the one- +and two-body MO integrals, which in turn are used to determine +the full Configuration Interaction (CI) wave function and the :ref:`uccsd` +wave function, among other things. Computational chemistry software drivers +expose configuration parameters to make the computation of the +Hartree-Fock wave function converge, should the default parameter values fail. +Qiskit Chemistry has no problem supporting such advanced configuration parameters, +which would be passed directly into the configuration file as an input to the underlying driver. +Conversely, solutions that have chosen to interpose a new programming language or new APIs between +the user and the underlying drivers currently do not support customizing the parameters for +facilitating the convergence of the computation of the Hartree-Fock wave function. In order for +these alternative solutions to allow for this type of customization, the parameters would have to +be exposed through the programming language or the APIs. As a result, such alternative solutions +may not be able to get the integrals that need to be used in the full CI or UCCSD calculations. + +Let us consider yet another example illustrating why a direct use of the classical computational +chemistry software is superior to the choice of interposing a new programming language or API +between the user and the driver. It has been `demonstrated `__ +that taking into account a molecule's spatial symmetries +can be used to reduce the number of qubits necessary to model that molecule and compute its energy +properties. Computational chemistry software packages allow for configuring spatial symmetries +in their input files. Thus, Qiskit Chemistry can immediately take direct advantage of such feature +exposed by the underlying computational software packages and obtain from those packages +intermediate data that is already optimized with respect to the symmetries configured by the user. +As a result, energy computations performed by Qiskit Chemistry require fewer qubits when +a spatial symmetries are present in a molecule. +Conversely, other solutions that interpose a new programming language or APIs fail to expose +this configuration feature to their users unless an ad-hoc symmetry API is constructed, which must +then be mapped to all the underlying software packages interfaced by those solutions. To make +things more complicated, for any new software package that is interfaced by those solutions, that +symmetry API will have to be programmatically mapped to the package's symmetry +configuration feature. + +In essence, interposing a new language or new APIs between the user and the underlying +classical drivers severely limits the functionality of the whole system, unless the new +language or APIs interfacing the drivers match the union of all the configuration parameters +of all the possible computational drivers that are currently supported by the system, or +that will be supported in the future. + +~~~~~~~~~~~~~~~~~~~~~~~~~ +Configuration Correctness +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Qiskit Chemistry offers another unique feature. Given that Qiskit Chemistry +allows traditional software to be executed on a quantum system, +configuring a chemistry experiment definitely requires setting up a hybrid +configuration, which involves configuring both chemistry- and quantum-specific +parameters. The chances of introducing configuration +errors, making typos, or selecting incompatible configuration parameters +are very high, especially for people who are expert in chemistry +but new to the realm of quantum computing. + +For example, the number of qubits necessary to compute the ground-state energy or a molecule +depends on the number of spin orbitals of that molecule. The total number of qubits may +be reduced by applying various optimization techniques, such as the novel parity-map-based +precision-preserving two-qubit reduction. Further reductions may be achieved with various +approximations, such as the freezing of the core and the virtual-orbital removal. The number +of qubits to allocate to solve a particular problem should be computed by the system and not +exposed as a configuration parameter. Letting the user configure the number of qubits can +easily lead to a configuration parameter mismatch. + +Another scenario in which a user could misconfigure a problem would involve the +user associating algorithm components (such as optimizers and trial functions +for quantum variational algorithms) to algorithms that do not support such components. + +To address such issues, in +Aqua the problem-specific configuration information and the +quantum-specific configuration information are verified for correctness both at configuration +time and at run time, so that the combination of classical and quantum inputs is +resilient to configuration errors. Very importantly, configuration +correctness is dynamically enforced even for components that are +dynamically discovered and loaded. + + +------- +License +------- + +This project uses the `Apache License Version 2.0 software +license `__. + +Some code supplied by Qiskit Chemistry for interfacing +to external chemistry :ref:`drivers` has additional licensing: + +- The :ref:`gaussian-16` + driver + contains work licensed under the `Gaussian Open-Source Public + License `__. + +- The :ref:`pyquante` + driver + contains work licensed under the `modified BSD + license `__. + diff --git a/docs/aqua/chemistry/qiskit_chemistry_translators.rst b/docs/aqua/chemistry/qiskit_chemistry_translators.rst index ec9d95ba13ba..a6db69d6f425 100644 --- a/docs/aqua/chemistry/qiskit_chemistry_translators.rst +++ b/docs/aqua/chemistry/qiskit_chemistry_translators.rst @@ -57,4 +57,4 @@ Bravyi-Kitaev Superfast ----------------------- Bravyi Kitaev Superfast (BKSF) algorithm `` is a mapping from fermionic operators to qubit operators. BKSF algorithm defines an abstract model where the fermionic modes are mapped to vertices of an interaction graph. The edges of the graph correspond to the interaction between the modes. The graph can be constructed from the Hamiltonian. The simulation is done by putting qubits on the edges of the graph. Each fermionic operator costs :math:`\mathcal{O}(d)` qubit operations, where :math:`d` is the degree of the interaction graph. Nonetheless, the number of qubits required are more than the number of fermionic modes. -The BKSF was proposed by Kanav Setia and James D. Whitfield. \ No newline at end of file +The BKSF was proposed by Kanav Setia and James D. Whitfield. diff --git a/docs/aqua/chemistry/release_history.rst b/docs/aqua/chemistry/release_history.rst index 0330c4fe9b3d..c44031f8205b 100644 --- a/docs/aqua/chemistry/release_history.rst +++ b/docs/aqua/chemistry/release_history.rst @@ -28,13 +28,16 @@ we have added the following new features : - Compatibility with Aqua 0.4 - Compatibility with Terra 0.7 - Compatibility with Aer 0.1 -- Programmatic APIs for algorithms and components -- each component can now be instantiated and initialized via a single (non-empty) constructot call -- ``QuantumInstance`` API for algorithm/backend decoupling -- ``QuantumInstance`` encapsulates a backend and its settings +- Programmatic APIs for algorithms and components -- each component can now be instantiated and + initialized via a single (non-empty) constructot call ``QuantumInstance`` API for + algorithm/backend decoupling -- ``QuantumInstance`` encapsulates a backend and its settings - Updated documentation and Jupyter Notebooks illustrating the new programmatic APIs -- ``HartreeFock`` component of pluggable type ``InitialState` moved from Qiskit Aqua to Qiskit Chemistry - registers itself at installation time as Aqua algorithmic components for use at run time -- ``UCCSD`` component of pluggable type ``VariationalForm`` moved from Qiskit Aqua to Qiskit Chemistry - registers itself at installation time as Aqua algorithmic components for use at run time +- ``HartreeFock`` component of pluggable type ``InitialState`` moved from Qiskit Aqua to Qiskit + Chemistry registers itself at installation time as Aqua algorithmic components for use at run + time +- ``UCCSD`` component of pluggable type ``VariationalForm`` moved from Qiskit Aqua to Qiskit + Chemistry registers itself at installation time as Aqua algorithmic components for use at run + time - Z-matrix support for the PySCF & PyQuante classical computational chemistry drivers -------------------------------------------------- diff --git a/docs/aqua/eigs.rst b/docs/aqua/eigs.rst index fe5aadeb3868..f36fcc26b6e2 100644 --- a/docs/aqua/eigs.rst +++ b/docs/aqua/eigs.rst @@ -9,9 +9,8 @@ Aqua bundles methods to find Eigenvalues of a given matrix, such as standalone algorithm, the members of the library are to be used in a larger algorithm such as :ref:`HHL`. The following methods are available -- :ref:`eigsqpe_component`: Given a matrix and a linear combination of its -eigenstates, *QPE* prepares the Eigenvalues on a specified output register. - + * :ref:`eigsqpe_component`: Given a matrix and a linear combination of its + eigenstates, *QPE* prepares the Eigenvalues on a specified output register. .. topic:: Extending the Eigs Library diff --git a/docs/aqua/execution.rst b/docs/aqua/execution.rst index f035376b86bd..a6e99cc3c539 100644 --- a/docs/aqua/execution.rst +++ b/docs/aqua/execution.rst @@ -156,11 +156,11 @@ This technique can be used, for example, to compare the results of two different Documentation UI ^^^^^^^^^^^^^^^^ -Aqua is a modular and extensible software framework, supporting two types of endusers: those who want -to simply use Aqua as a tool to execute experiments, and those interested in extending Aqua -with new components. Users in either of these categories may find it useful to access the Aqua documentation UI, -which shows all the -pluggable components along with the schemas for their parameters. +Aqua is a modular and extensible software framework, supporting two types of endusers: +those who want to simply use Aqua as a tool to execute experiments, and those interested in +extending Aqua with new components. Users in either of these categories may find it useful +to access the Aqua documentation UI, which shows all the pluggable components along with +the schemas for their parameters. If installed via ``pip install``, Aqua comes with the following command-line tool @@ -206,7 +206,7 @@ of a domain-specific application. For example, the Aqua Chemistry `command-line tool :ref:`aqua-chemistry-command-line` -and :ref:`aqua-chemistry-gui` +and :ref:`aqua-chemistry-gui` both allow for automatically serializing the input to the quantum algorithm as a JSON :ref:`input-file-for-direct-algorithm-invocation`. Serializing the input to the quantum algorithm is useful in many scenarios @@ -220,10 +220,10 @@ because the contents of one of such JSON files are domain- and problem-independe or the problem that the user was trying to solve. - People performing research on quantum algorithms may be interested in having access to a number of such JSON files in order to test and refine the design and - implementation of an algorithm, irrespective of the domain in which those JSON files were generated - or the problem that the user was trying to solve. -- Repeating a domain-specific experiment in which the values of the input parameters remain the same, - and the only difference is in the configuration of the quantum algorithm and its + implementation of an algorithm, irrespective of the domain in which those JSON files were + generated or the problem that the user was trying to solve. +- Repeating a domain-specific experiment in which the values of the input parameters remain + the same, and the only difference is in the configuration of the quantum algorithm and its supporting components becomes much more efficient because the user can choose to restart any new experiment directly at the algorithm level, thereby bypassing the data extraction from the driver, and the translation of that data into input to a @@ -263,14 +263,15 @@ New problems, disambiguated by their ``"name"`` parameter, can be programmatically added to Aqua via the ``AlgorithmInput`` Application Programming Interface (API), and each quantum or classical -Aqua algorithm should programmatically list the problems it is suitable for in its JSON schema, embedded into +Aqua algorithm should programmatically list the problems it is suitable for +in its JSON schema, embedded into the class implementing the ``QuantumAlgorithm`` interface. -Aspects of the computation may include use of random numbers. For instance, the +Aspects of the computation may include use of random numbers. For instance, the :ref:`vqe` is coded to use a random initial point if the variational form does not supply any preference based on the initial state and if the -user does not explicitly supply an initial point. +user does not explicitly supply an initial point. In this case, each run of VQE, for what would otherwise be a constant problem, can produce a different result, causing non-determinism and the inability to replicate the same result across different runs with @@ -377,7 +378,7 @@ optimizer and the :ref:`ryrz` variational form: Aqua allows for configuring the *backend*, which is the quantum machine on which a quantum experiment will be run. -This configuration requires specifying +This configuration requires specifying the `Qiskit Terra `__ quantum computational provider and backend to be used for computation, which is done by assigning a ``str`` value to the ``"provider"`` and ``"name"`` parameters of the ``"backend"`` section: @@ -387,14 +388,14 @@ the ``"provider"`` and ``"name"`` parameters of the ``"backend"`` section: "provider" : string "name" : string -The value of the ``"provider"`` parameter indicates the full name of a class derived from ``"BaseProvider"`` -or global variable pointing to a instance of this class. +The value of the ``"provider"`` parameter indicates the full name of a class derived from +``"BaseProvider"`` or global variable pointing to a instance of this class. The value of the ``"name"`` parameter indicates either a real-hardware quantum computer or a quantum simulator accessed from the provider. Terra comes with two predefined providers: ``"qiskit.BasicAer"`` and ``"qiskit.IBMQ"``. By installing ``"qiskit-aer"``, the ``"qiskit.Aer"`` provider gets included too. -Each provider has its own set of simulators and ``"qiskit.IBMQ"`` gives access to real-hardware quantum -computer or simulators in the cloud. +Each provider has its own set of simulators and ``"qiskit.IBMQ"`` gives access to real-hardware +quantum computer or simulators in the cloud. For the ``"qiskit.IBMQ"`` provider, you need to configure it with a token and possibly url proxies. The Aqua `GUI <#aqua-gui>` greatly simplifies it via a user friendly interface, accessible through the **Preferences...** menu item. @@ -413,7 +414,7 @@ Otherwise you need to configure programmatically using Qiskit Terra `__ will automatically disable the ``"backend"`` configuration section - whenever a non-quantum algorithm is selected. + whenever a non-quantum algorithm is selected. Configuring the backend to use by a quantum algorithm requires setting the following parameters too: @@ -425,12 +426,12 @@ requires setting the following parameters too: "shots" : int This parameter applies, in particular to the local QASM simulator and any real quantum device. - The default value is ``1024``. - + The default value is ``1024``. + - A ``bool`` value indicating whether or not the circuit should undergo optimization: .. code:: python - + "skip_transpiler" : bool The default value is ``False``. If ``"skip_transpiler"`` is set to ``True``, then diff --git a/docs/aqua/extending.rst b/docs/aqua/extending.rst index 594872237d2f..361df5afb304 100644 --- a/docs/aqua/extending.rst +++ b/docs/aqua/extending.rst @@ -1,6 +1,5 @@ .. _aqua-extending: -==================== Contributing to Aqua ==================== @@ -22,38 +21,39 @@ by providing new components, which will be automatically discovered and loaded b .. _aqua-dynamically-discovered-components: ---------------------------------- Dynamically Discovered Components --------------------------------- Each component should derive from the corresponding base class, as explained below. There are two ways for a component to be dynamically discovered and loaded by Aqua at run time: -1. The class implementing the component should be placed in the appropriate folder in the file system, - as explained in `Section "Aqua Extension Points" <#aqua-extension-points>`__ below for each different component type. - This is the easiest approach. Researchers - and developers extending Aqua are more likely to have installed Aqua by cloning the +1. The class implementing the component should be placed in the appropriate folder in the file + system, as explained in `Section "Aqua Extension Points" <#aqua-extension-points>`__ below for + each different component type. This is the easiest approach. Researchers and developers + extending Aqua are more likely to have installed Aqua by cloning the `Aqua repository `__ as opposed to using the pip package - manager system. Therefore, the folders indicated below can be easily located in the file system. + manager system. Therefore, the folders indicated below can be easily located in the file + system. 2. Alternatively, a developer extending Aqua with a new component can simply create a dedicated - repository with its own versioning. This repository must be locally installable with the package that was - created. It simply consists of customizing the ``setup.py`` adding the entry points for ``qiskit.aqua.pluggables`` as shown below. - The format is: ``anyname = full_package:class_name``. Each class must be included separately. - When someone installs the package, the extensions will be automatically registered: + repository with its own versioning. This repository must be locally installable with the + package that was created. It simply consists of customizing the ``setup.py`` adding the entry + points for ``qiskit.aqua.pluggables`` as shown below. The format is: + ``anyname = full_package:class_name``. Each class must be included separately. When someone + installs the package, the extensions will be automatically registered: .. code:: python import setuptools long_description = """New Package for Aqua Component""" - + requirements = [ "qiskit-aqua>=0.4.1", "qiskit-terra>=0.7.0,<0.8", "numpy>=1.13" ] - + setuptools.setup( name = 'aqua_custom_component_package', version = "0.1.0", # this should match __init__.__version__ @@ -94,7 +94,6 @@ ways for a component to be dynamically discovered and loaded by Aqua at run time All the classes implementing the algorithms and the supporting components listed below should embed a configuration dictionary including ``name``, ``description`` and ``input_schema`` properties. ---------------------- Aqua Extension Points --------------------- @@ -103,86 +102,80 @@ interested in quantum algorithms can contribute to Aqua. .. _extending-algorithms: -~~~~~~~~~~ Algorithms -~~~~~~~~~~ +^^^^^^^^^^ New :ref:`quantum-algorithms` may be developed according to the specific API provided by Aqua. -By simply adding the code of an algorithm to the collection of existing algorithms, that new algorithm -will be immediately recognized via dynamic lookup, and made available for use within the framework of Aqua. -To develop and deploy any new algorithm, the new algorithm class should derive from the ``QuantumAlgorithm`` class. -Along with all of its supporting modules, the new algorithm class should be installed under a suitable folder in the -``qiskit_aqua\algorithms`` directory, just like the existing algorithms, unless the dynamic-discovery approach has been -chosen, in which case the algorithm can register itself as an Aqua algorithm irrespective of its installation +By simply adding the code of an algorithm to the collection of existing algorithms, that new +algorithm will be immediately recognized via dynamic lookup, and made available for use within the +framework of Aqua. To develop and deploy any new algorithm, the new algorithm class should derive +from the ``QuantumAlgorithm`` class. Along with all of its supporting modules, the new algorithm +class should be installed under a suitable folder in the ``qiskit_aqua\algorithms`` directory, +just like the existing algorithms, unless the dynamic-discovery approach has been chosen, in which +case the algorithm can register itself as an Aqua algorithm irrespective of its installation folder in the file system. .. _extending-optimizers: -~~~~~~~~~~ Optimizers -~~~~~~~~~~ +^^^^^^^^^^ -New `optimizers <#optimizers>`__ for quantum variational algorithms -should and derive from -the ``Optimizer`` class. They should also be installed in the ``qiskit_aqua/components/optimizers`` folder -of the ``aqua`` repository clone, -unless the dynamic-discovery approach has been -chosen, in which case a new optimizer can register itself as an Aqua optimizer irrespective of its installation -folder in the file system. +New `optimizers <#optimizers>`__ for quantum variational algorithms should and derive from +the ``Optimizer`` class. They should also be installed in the +``qiskit_aqua/components/optimizers`` folder of the ``aqua`` repository clone, unless the +dynamic-discovery approach has been chosen, in which case a new optimizer can register itself as +an Aqua optimizer irrespective of its installation folder in the file system. .. _extending-variational-forms: -~~~~~~~~~~~~~~~~~ Variational Forms -~~~~~~~~~~~~~~~~~ +^^^^^^^^^^^^^^^^^ `Trial wave functions <#variational_forms>`__ for quantum variational algorithms, such as `VQE <#variational-quantum-eigensolver-vqe>`__ must derive from the ``VariationalForm`` class. They should also be installed under the ``qiskit_aqua/components/variational_forms`` folder unless the dynamic-discovery approach has been -chosen, in which case a new trial wave function can register itself as an Aqua variational form irrespective of its installation -folder in the file system. +chosen, in which case a new trial wave function can register itself as an Aqua variational +form irrespective of its installation folder in the file system. .. _extending-oracles: -~~~~~~~ Oracles -~~~~~~~ +^^^^^^^ -`Oracles <#oracles>`__, for use with algorithms such as `Grover's search <#quantum-grover-search>`__, +`Oracles <#oracles>`__, for use with algorithms such as +`Grover's search <#quantum-grover-search>`__, should derive from the ``Oracle`` class. They should also go under the ``qiskit_aqua/components/oracles`` folder, unless the dynamic-discovery approach has been -chosen, in which case a new oracle can register itself as an Aqua oracle irrespective of its installation -folder in the file system. +chosen, in which case a new oracle can register itself as an Aqua oracle irrespective of its +installation folder in the file system. .. _extending-iqfts: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Inverse Quantum Fourier Transforms (IQFTs) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -`IQFTs <#iqfts>`__, for use for example for `QPE <#quantum-phase-estimation-qpe>`__, must derive from the ``IQFT`` class. -They should also be installed under the ``qiskit_aqua/components/iqfts`` folder, -unless the dynamic-discovery approach has been -chosen, in which case a new IQFT can register itself as an Aqua IQFT irrespective of its installation -folder in the file system. +`IQFTs <#iqfts>`__, for use for example for `QPE <#quantum-phase-estimation-qpe>`__, must derive +from the ``IQFT`` class. They should also be installed under the ``qiskit_aqua/components/iqfts`` +folder, unless the dynamic-discovery approach has been chosen, in which case a new IQFT can +register itself as an Aqua IQFT irrespective of its installation folder in the file system. .. _extending-initial-states: -~~~~~~~~~~~~~~ Initial States -~~~~~~~~~~~~~~ +^^^^^^^^^^^^^^ -`Initial states <#initial_states>`__, for algorithms such as `VQE <#variational-quantum-eigensolver-vqe>`__, +`Initial states <#initial_states>`__, for algorithms such as +`VQE <#variational-quantum-eigensolver-vqe>`__, `QPE <#quantum-phase-estimation-qpe>`__ -and `IQPE <#iterative-quantum-phase-estimation-iqpe>`__, must derive from the ``InitialState`` class. -They should also be installed under the ``qiskit_aqua/components/initial_states`` folder, +and `IQPE <#iterative-quantum-phase-estimation-iqpe>`__, must derive from the ``InitialState`` +class. They should also be installed under the ``qiskit_aqua/components/initial_states`` folder, unless the dynamic-discovery approach has been -chosen, in which case a new initial state can register itself as an Aqua initial state irrespective of its installation +chosen, in which case a new initial state can register itself as an Aqua initial state irrespective +of its installation folder in the file system. ---------------------- Aqua Documentation UI --------------------- Researchers and developers interested in extending Aqua with new @@ -190,14 +183,12 @@ algorithms and computational components can access the :ref:`aqua-doc-ui`, which offers a quick and succinct overview of all the extensible components along with their configuration schemas. ---------------- Aqua Unit Tests --------------- Contributing new software components to Aqua requires writing new unit tests for those components, and executing all the existing unit tests to make sure that no bugs were inadvertently injected. -^^^^^^^^^^^^^^^^^^^^^^^ Writing Aqua Unit Tests ^^^^^^^^^^^^^^^^^^^^^^^ @@ -207,7 +198,6 @@ rather, they should use ``self.log.debug``. If they use assertions, these should be from the ``unittest`` package, such as ``self.AssertTrue``, ``self.assertRaises``, etc. -^^^^^^^^^^^^^^^^^^^^^^^^^ Executing Aqua Unit Tests ^^^^^^^^^^^^^^^^^^^^^^^^^ To run all unit tests, execute the following command: diff --git a/docs/aqua/feature_maps.rst b/docs/aqua/feature_maps.rst index 5e561b4c2cee..cb6e46973a54 100644 --- a/docs/aqua/feature_maps.rst +++ b/docs/aqua/feature_maps.rst @@ -74,7 +74,7 @@ The First Order Expansion feature map transform data :math:`\vec{x} \in \mathbb{ according to the following equation, and then concatenates the same circuit :math:`d` times, where :math:`d` is the depth of the circuit: - :math:`U_{\Phi(\vec{x})} = \exp\left(i \sum_{S \subseteq [n]} \phi_S(\vec{x}) \prod_{i \in S} Z_i\right)` + :math:`U_{\Phi(\vec{x})}=\exp\left(i\sum_{S\subseteq[n]}\phi_S(\vec{x})\prod_{i\inS}Z_i\right)` where :math:`S \in \{ 0, 1, ..., n-1 \}, \phi_{i}(\vec{x}) = x_i`. @@ -108,9 +108,10 @@ The Second Order Expansion feature map transform data :math:`\vec{x} \in \mathbb according to the following equation, and then duplicate the same circuit with depth :math:`d` times, where :math:`d` is the depth of the circuit: - :math:`U_{\Phi(\vec{x})} = \exp\left(i \sum_{S \subseteq [n]} \phi_S(\vec{x}) \prod_{i \in S} Z_i\right)` +:math:`U_{\Phi(\vec{x})}=\exp\left(i\sum_{S\subseteq [n]}\phi_S(\vec{x}) \prod_{i \in S} Z_i\right)` -where :math:`S \in \{0, 1, ..., n-1, (0, 1), (0, 2), ..., (n-2, n-1)\}, \phi_{i}(\vec{x}) = x_i, \phi_{(i,j)}(\vec{x}) = (\pi - x_i) * (\pi - x_j)`. +where :math:`S \in \{0, 1, ..., n-1, (0, 1), (0, 2), ..., (n-2, n-1)\}, +\phi_{i}(\vec{x}) = x_i, \phi_{(i,j)}(\vec{x}) = (\pi - x_i) * (\pi - x_j)`. The following allows a specific form to be configured in the @@ -206,9 +207,12 @@ The Pauli Z Expansion feature map transform data :math:`\vec{x} \in \mathbb{R}^n according to the following equation, and then duplicate the same circuit with depth :math:`d` times, where :math:`d` is the depth of the circuit: - :math:`U_{\Phi(\vec{x})} = \exp\left(i \sum_{S \subseteq [n]} \phi_S(\vec{x}) \prod_{i \in S} Z_i\right)` +:math:`U_{\Phi(\vec{x})}=\exp\left(i \sum_{S\subseteq[n]}\phi_S(\vec{x})\prod_{i\inS}Z_i\right)` -where :math:`S \in \{\binom{n}{k}\ combinations,\ k = 1,... n\}, \phi_S(\vec{x}) = x_i` if :math:`k=1`, otherwise :math:`\phi_S(\vec{x}) = \prod_S(\pi - x_j)`, where :math:`j \in S`. Please refer to :ref:`firstorderexpansion` and :ref:`secondorderexpansion` for the cases of :math:`k=1` and :math:`k=2`, respectively. +where :math:`S \in \{\binom{n}{k}\ combinations,\ k = 1,... n\}, \phi_S(\vec{x}) = x_i` if +:math:`k=1`, otherwise :math:`\phi_S(\vec{x}) = \prod_S(\pi - x_j)`, where :math:`j \in S`. Please +refer to :ref:`firstorderexpansion` and :ref:`secondorderexpansion` for the cases of :math:`k=1` +and :math:`k=2`, respectively. The following allows a specific form to be configured in the @@ -238,11 +242,10 @@ is set to ``PauliZExpansion``: entanglement = "full" | "linear" - Only two ``str`` values are supported: ``"full"`` and ``"linear"``, corresponding to the *full* (or *all-to-all*) and - *linear* (or *next-neighbor coupling*) entangler maps, respectively. With full entanglement, each qubit is entangled with - all the - others; with linear entanglement, qubit :math:`i` is entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , - q - 2\}`, + Only two ``str`` values are supported: ``"full"`` and ``"linear"``, corresponding to the *full* + (or *all-to-all*) and *linear* (or *next-neighbor coupling*) entangler maps, respectively. With + full entanglement, each qubit is entangled with all the others; with linear entanglement, qubit + :math:`i` is entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , q - 2\}`, where :math:`q` is the total number of qubits. - A dictionary of lists of non-negative ``int`` values specifying the entangler map: @@ -311,9 +314,13 @@ The Pauli Expansion feature map transform data :math:`\vec{x} \in \mathbb{R}^n` according to the following equation, and then duplicate the same circuit with depth :math:`d` times, where :math:`d` is the depth of the circuit: - :math:`U_{\Phi(\vec{x})} = \exp\left(i \sum_{S \subseteq [n]} \phi_S(\vec{x}) \prod_{i \in S} P_i\right)` +:math:`U_{\Phi(\vec{x})}=\exp\left(i\sum_{S\subseteq [n]} \phi_S(\vec{x})\prod_{i\in S} P_i\right)` -where :math:`S \in \{\binom{n}{k}\ combinations,\ k = 1,... n \}, \phi_S(\vec{x}) = x_i` if :math:`k=1`, otherwise :math:`\phi_S(\vec{x}) = \prod_S(\pi - x_j)`, where :math:`j \in S`, and :math:`P_i \in \{ I, X, Y, Z \}` Please refer to :ref:`firstorderexpansion` and :ref:`secondorderexpansion` for the cases of :math:`k = 1` and :math:`P_0 = Z` and :math:`k = 2` and :math:`P_0 = Z\ and\ P_1 P_0 = ZZ`, respectively. +where :math:`S \in \{\binom{n}{k}\ combinations,\ k = 1,... n \}, \phi_S(\vec{x}) = x_i` if +:math:`k=1`, otherwise :math:`\phi_S(\vec{x}) = \prod_S(\pi - x_j)`, where :math:`j \in S`, and +:math:`P_i \in \{ I, X, Y, Z \}` Please refer to :ref:`firstorderexpansion` and +:ref:`secondorderexpansion` for the cases of :math:`k = 1` and :math:`P_0 = Z` and :math:`k = 2` +and :math:`P_0 = Z\ and\ P_1 P_0 = ZZ`, respectively. The following allows a specific form to be configured in the ``feature_map`` section of the Aqua diff --git a/docs/aqua/finance/qiskit_finance.rst b/docs/aqua/finance/qiskit_finance.rst index 1c05c4cb7533..8225765273ba 100644 --- a/docs/aqua/finance/qiskit_finance.rst +++ b/docs/aqua/finance/qiskit_finance.rst @@ -34,15 +34,16 @@ Research and developers interested in :ref:`aqua-extending` with new finance-spe capabilities can take advantage of the modular architecture of Aqua and easily extend Aqua with more algorithms and algorithm components, such as new :ref:`oracles` for the :ref:`grover` algorithm, -:ref:`optimizers` and :ref:`variational-forms` for :ref:`vqe`, :ref:`qaoa`, and :ref:`svm-variational`, -:ref:`iqfts` for :ref:`qpe`, :ref:`initial-states` for :ref:`variational-forms`, -as well as :ref:`feature-maps` and :ref:`multiclass-extensions` for Support Vector Machine -(SVM) algorithms, such as :ref:`svm-variational` and :ref:`svm-q-kernel`. +:ref:`optimizers` and :ref:`variational-forms` for :ref:`vqe`, :ref:`qaoa`, and +:ref:`svm-variational`, :ref:`iqfts` for :ref:`qpe`, :ref:`initial-states` for +:ref:`variational-forms`, as well as :ref:`feature-maps` and :ref:`multiclass-extensions` +for Support Vector Machine (SVM) algorithms, such as :ref:`svm-variational` and +:ref:`svm-q-kernel`. -------- Examples --------- +-------- The ``finance`` folder of the `Aqua Tutorials GitHub Repository `__ contains diff --git a/docs/aqua/index.rst b/docs/aqua/index.rst index aa95f60d4883..213b68a9bfb5 100644 --- a/docs/aqua/index.rst +++ b/docs/aqua/index.rst @@ -12,15 +12,15 @@ created :ref:`aqua-library` that can be invoked directly or via domain-specific applications: :ref:`aqua-chemistry`, :ref:`aqua-ai`, :ref:`aqua-optimization` and :ref:`aqua-finance`. -Finally, :ref:`aqua-tutorials` is a companion library of notebooks, input files and sample code made available in the form of a -`GitHub repository `__. +Finally, :ref:`aqua-tutorials` is a companion library of notebooks, input files and sample code +made available in the form of a `GitHub repository `__. This part of the documentation will first cover Aqua as a library of quantum applications, and then the domain-specific applications of Aqua: Chemistry, AI and Optimization. .. toctree:: :maxdepth: 2 - + Aqua: A Library of Quantum Algorithms Qiskit Chemistry Qiskit AI diff --git a/docs/aqua/initial_states.rst b/docs/aqua/initial_states.rst index c30063656d6d..837345506d7b 100644 --- a/docs/aqua/initial_states.rst +++ b/docs/aqua/initial_states.rst @@ -4,18 +4,18 @@ Initial States ============== -An *initial state* in Aqua is an object that defines a starting state for one of the :ref:`variational-forms` -and a trial state to be evolved by the :ref:`qpe` algorithm. +An *initial state* in Aqua is an object that defines a starting state for one of the +:ref:`variational-forms` and a trial state to be evolved by the :ref:`qpe` algorithm. An initial state allows the user to define a state, either declaratively or programmatically, and -then provides a circuit that can take the starting point of all zero qubits to the defined state. +then provides a circuit that can take the starting point of all zero qubits to the defined state. .. topic:: Extending the Initial States Library Consistent with its unique design, Aqua has a modular and extensible architecture. Algorithms and their supporting objects, such as initial states for variational forms and :ref:`qpe`, are pluggable modules in Aqua. - New initial states are typically installed in the ``qiskit_aqua/utils/initial_states`` folder and derive from - the ``InitialState`` class. Aqua also allows for + New initial states are typically installed in the ``qiskit_aqua/utils/initial_states`` folder + and derive from the ``InitialState`` class. Aqua also allows for :ref:`aqua-dynamically-discovered-components`: new components can register themselves as Aqua extensions and be dynamically discovered at run time independent of their location in the file system. @@ -32,10 +32,10 @@ Aqua supplies the following three initial states: ---- Zero ---- -This initial state is suitable for those situations in which the all-zeroes state is the desired starting state. -This is the case for a *vacuum state* in physics or chemistry. The zero initial state has no parameters and is, therefore, -not configurable. Configuring the use of the zero initial state will create the zero state based solely on -the number of qubits. +This initial state is suitable for those situations in which the all-zeroes state is the desired +starting state. This is the case for a *vacuum state* in physics or chemistry. The zero initial +state has no parameters and is, therefore, not configurable. Configuring the use of the zero +initial state will create the zero state based solely on the number of qubits. .. topic:: Declarative Name @@ -43,25 +43,27 @@ the number of qubits. is ``ZERO``. .. _hartree-fock: + ------------ Hartree-Fock ------------ -This initial state is specific for chemistry-related experiments. It corresponds to a molecule's *Hartree-Fock state*. -In computational physics and chemistry, the Hartree–Fock method is a way to approximate the determination of the wave function and -the energy of a quantum many-body system in a stationary state. -The Hartree–Fock method often assumes that the exact, :math:`N`-body wave function of the system can be approximated by a -single Slater determinant in the case where the particles are fermions) of :math:`N` spin-orbitals. -By invoking the variational method, one can derive a set of :math:`N`-coupled equations for the :math:`N` spin orbitals. -A solution of these equations yields the Hartree–Fock wave function and energy of the system. -For both atoms and molecules, the Hartree–Fock solution is the central starting point for most methods that describe -the many-electron system more accurately. In Aqua, for example, the Hartree-Fock solution is often the ideal -starting state for the :ref:`variational-forms` +This initial state is specific for chemistry-related experiments. It corresponds to a molecule's +*Hartree-Fock state*. In computational physics and chemistry, the Hartree–Fock method is a way to +approximate the determination of the wave function and the energy of a quantum many-body system in +a stationary state. The Hartree–Fock method often assumes that the exact, :math:`N`-body wave +function of the system can be approximated by a single Slater determinant in the case where the +particles are fermions) of :math:`N` spin-orbitals. By invoking the variational method, one can +derive a set of :math:`N`-coupled equations for the :math:`N` spin orbitals. A solution of these +equations yields the Hartree–Fock wave function and energy of the system. For both atoms and +molecules, the Hartree–Fock solution is the central starting point for most methods that describe +the many-electron system more accurately. In Aqua, for example, the Hartree-Fock solution is often +the ideal starting state for the :ref:`variational-forms` and a trial state to be evolved by the :ref:`qpe` algorithm. For example, when the transformation type of a chemistry operator is set to be particle hole, then the configuration of the initial qubit state offsetting the computation of the final result -should be set to be the Hartree-Fock energy of the molecule in the :ref:`aqua-chemistry-input-file`. -Hartree-Fock is also the preferred initial state when using the +should be set to be the Hartree-Fock energy of the molecule in the +:ref:`aqua-chemistry-input-file`. Hartree-Fock is also the preferred initial state when using the :ref:`uccsd` and :ref:`swaprz` variational forms. The following parameters allow @@ -101,7 +103,7 @@ the Hartree-Fock initial state to be configured: without loss of precision by setting the ``two_qubit_reduction`` parameter to ``True``, as explained next. 3. ``bravyi_kitaev`` corresponds to the :ref:`bravyi-kitaev` transformation, - also known as *binary-tree-based qubit mapping*. + also known as *binary-tree-based qubit mapping*. - A Boolean flag specifying whether or not to apply the precision-preserving two-qubit reduction optimization: @@ -123,16 +125,15 @@ the Hartree-Fock initial state to be configured: When the ``auto_substitutions`` flag in the ``problem`` section of the :ref:`aqua-chemistry-input-file` - is set to ``True``, which is the default, the values of parameters + is set to ``True``, which is the default, the values of parameters ``num_particles`` and ``num_orbitals`` are automatically computed by Aqua Chemistry - when ``Hartree-Fock`` is selected as the value of the ``name`` parameter in the ``InitialState`` section. - As such, their configuration is disabled; the user will not be required, or even allowed, to assign values to - these two parameters. This is also reflected in the :ref:`aqua-chemistry-gui`, where - these parameters will be grayed out and uneditable as long as ``auto_substitutions`` is set to ``True`` - in the ``problem`` section. - Furthermore, Aqua Chemistry automatically sets - parameters ``qubit_mapping`` and ``two_qubit_reduction`` in section ``initial_state`` when - ``HartreeFock`` is selected as the value of the ``name`` + when ``Hartree-Fock`` is selected as the value of the ``name`` parameter in the + ``InitialState`` section. As such, their configuration is disabled; the user will not be + required, or even allowed, to assign values to these two parameters. This is also reflected in + the :ref:`aqua-chemistry-gui`, where these parameters will be grayed out and uneditable as + long as ``auto_substitutions`` is set to ``True`` in the ``problem`` section. Furthermore, + Aqua Chemistry automatically sets parameters ``qubit_mapping`` and ``two_qubit_reduction`` in + section ``initial_state`` when ``HartreeFock`` is selected as the value of the ``name`` parameter. Specifically, Aqua Chemistry sets ``qubit_mapping`` and ``two_qubit_reduction`` to the values the user assigned to them in the ``operator`` section of the input file in order to enforce parameter/value matching across these different @@ -156,20 +157,21 @@ the Hartree-Fock initial state to be configured: .. topic:: Declarative Name - When referring to the Hartree-Fock initial state declaratively inside Aqua, its code ``name``, by which Aqua dynamically discovers and loads it, - is ``HartreeFock``. + When referring to the Hartree-Fock initial state declaratively inside Aqua, its code ``name``, + by which Aqua dynamically discovers and loads it, is ``HartreeFock``. ------ Custom ------ Should the :ref:`zero` and :ref:`hartree-fock` pre-defined initial states not meet the user's -needs for a particular quantum experiment, this option allows the user of Aqua to fully customize the initial state -(e.g. for :ref:`variational-forms` and the :ref:`qpe` algorithm) by directly configuring a *custom probability distribution* for the state vector -or even providing the desired *custom quantum circuit*. -No matter what custom probability distribution the user chooses, the state vector will be normalized by Aqua, -so the total probability represented is :math:`1.0`. -Setting up a custom probability distribution requires assigning a value to the following parameters: +needs for a particular quantum experiment, this option allows the user of Aqua to fully customize +the initial state (e.g. for :ref:`variational-forms` and the :ref:`qpe` algorithm) by directly +configuring a *custom probability distribution* for the state vector or even providing the +desired *custom quantum circuit*. No matter what custom probability distribution the user chooses, +the state vector will be normalized by Aqua, so the total probability represented is :math:`1.0`. +Setting up a custom probability distribution requires assigning a value to the following +parameters: - A label specifying a predefined probability distribution used to configure the state vector: @@ -177,14 +179,17 @@ Setting up a custom probability distribution requires assigning a value to the f state = "zero" | "uniform" | "random" - The ``state`` parameter accepts a ``str`` value. Currently, the following three ``str`` values are supported: + The ``state`` parameter accepts a ``str`` value. Currently, the following three ``str`` + values are supported: - 1. ``"zero"`` --- This setting configures the state vector with the *zero probability distribution*, and is effectively - equivalent to the :ref:`zero` initial state. - 2. ``"uniform"`` --- This setting configures the state vector with the *uniform probability distribution*. All the qubits - are set in superposition, each of them being initialized to the Hadamard gate, which means that - a measurement will have equal probabilities to become :math:`1` or :math:`0`. - 3. ``"random"`` --- This setting assigns the elements of the state vector according to a random probability distribution. + 1. ``"zero"`` --- This setting configures the state vector with the *zero probability + distribution*, and is effectively equivalent to the :ref:`zero` initial state. + 2. ``"uniform"`` --- This setting configures the state vector with the *uniform probability + distribution*. All the qubits + are set in superposition, each of them being initialized to the Hadamard gate, which means + that a measurement will have equal probabilities to become :math:`1` or :math:`0`. + 3. ``"random"`` --- This setting assigns the elements of the state vector according to a random + probability distribution. - The state vector itself: @@ -193,40 +198,42 @@ Setting up a custom probability distribution requires assigning a value to the f state_vector : [complex, complex, ... , complex] The ``state_vector`` parameter allows a specific custom initial state to be defined as a - list of ``complex`` numbers. The length of the list must be :math:`2^q`, where :math:`q` is the total number of qubits. + list of ``complex`` numbers. The length of the list must be :math:`2^q`, where :math:`q` is the + total number of qubits. - The custom quantum circuit: .. code:: python circuit: QuantumCircuit - + The ``circuit`` parameter takes the value of a ``QuantumCircuit`` object representing the custom quantum circuit for the initial state. .. warning:: - The ``InitialState`` Application Programming Interface (API) exposes a constructor that allows for - programmatically setting ``num_qubits``, the number of qubits in the ``InitialState`` object. However, when configured declaratively, - Aqua and its domain specific applications - (:ref:`aqua-chemistry`, :ref:`aqua-ai`, and :ref:`aqua-optimization`) do not expose a configuration parameter in - an ``InitialState`` object to set - the number of qubits to use in an experiment. This is because, when it is used as a tool to execute experiments, + The ``InitialState`` Application Programming Interface (API) exposes a constructor that + allows for programmatically setting ``num_qubits``, the number of qubits in the + ``InitialState`` object. However, when configured declaratively, Aqua and its domain specific + applications + (:ref:`aqua-chemistry`, :ref:`aqua-ai`, and :ref:`aqua-optimization`) do not expose a + configuration parameter in an ``InitialState`` object to set the number of qubits to use in an + experiment. This is because, when it is used as a tool to execute experiments, Aqua is working at a higher, more abstract level. In such cases, the number of qubits - is computed internally at run time based on the particular experiment, and passed programmatically to - the constructor. Manually configuring the state vector, therefore, - requires knowing the number of qubits :math:`q`, since the length of the state vector is :math:`2^q`. Providing a state vector of the wrong - size will generate a run-time error. Therefore, caution should be used when manually configuring the state vector. - The same also applies when the actual custom circuit is directly supplied. + is computed internally at run time based on the particular experiment, and passed + programmatically to the constructor. Manually configuring the state vector, therefore, + requires knowing the number of qubits :math:`q`, since the length of the state vector is + :math:`2^q`. Providing a state vector of the wrong size will generate a run-time error. + Therefore, caution should be used when manually configuring the state vector. The same also + applies when the actual custom circuit is directly supplied. .. note:: - The multiple ways of manually configuring an initial state abide to the following priority order: - `circuit > state_vector > state`. So, when a higher order item is supplied, the lower-order item(s) will be ignored - if also supplied. + The multiple ways of manually configuring an initial state abide to the following priority + order: `circuit > state_vector > state`. So, when a higher order item is supplied, the + lower-order item(s) will be ignored if also supplied. .. topic:: Declarative Name - When referring to the custom initial state declaratively inside Aqua, its code ``name``, by which Aqua dynamically discovers and loads it, - is ``CUSTOM``. - + When referring to the custom initial state declaratively inside Aqua, its code ``name``, by + which Aqua dynamically discovers and loads it, is ``CUSTOM``. diff --git a/docs/aqua/installation.rst b/docs/aqua/installation.rst index 3a2375888cbd..a76f1c36f869 100644 --- a/docs/aqua/installation.rst +++ b/docs/aqua/installation.rst @@ -45,8 +45,8 @@ of quantum algorithms is via the `pip `__ packa pip will handle all dependencies automatically and you will always install the latest (and well-tested) release version. -A different class of users --- namely, quantum researchers and developers --- might be more interested -in exploring the source code of Aqua and :ref:`aqua-extending` by providing +A different class of users --- namely, quantum researchers and developers --- might be more +interested in exploring the source code of Aqua and :ref:`aqua-extending` by providing new components, such as :ref:`quantum-algorithms`, :ref:`optimizers`, :ref:`variational-forms`, :ref:`iqfts`, :ref:`oracles` and :ref:`initial-states`. The best way to install Aqua when the goal is to extend its capabilities is by cloning diff --git a/docs/aqua/iqfts.rst b/docs/aqua/iqfts.rst index 2a885c4fcd06..67cd99aa091c 100644 --- a/docs/aqua/iqfts.rst +++ b/docs/aqua/iqfts.rst @@ -28,7 +28,7 @@ adjoint of :math:`F` and :math:`I` is the identity matrix. It follows that :math:`F^{-1} = F^\dagger`. Since there is an efficient quantum circuit implementing the QFT, the circuit can be run in reverse to perform the Inverse Quantum Fourier Transform (IQFT). -Thus, both transforms can be efficiently performed on a quantum computer. +Thus, both transforms can be efficiently performed on a quantum computer. As mentioned above, the :ref:`QPE` algorithm uses the QFT for estimating the eigenvalues of a unitary operator. More precisely, QPE uses the Inverse Quantum Fourier Transform @@ -68,7 +68,7 @@ Standard IQFT The standard version of the IQFT is simply the inverse of a plain QFT. It generates the inverse of a QFT circuit with no approximation. -The standard IQFT takes no parameters and is not configurable. +The standard IQFT takes no parameters and is not configurable. .. topic:: Declarative Name diff --git a/docs/aqua/library.rst b/docs/aqua/library.rst index 9eb4bfd5695a..e7d60d71bb0f 100644 --- a/docs/aqua/library.rst +++ b/docs/aqua/library.rst @@ -11,7 +11,7 @@ real quantum device). .. toctree:: :maxdepth: 2 - Overview + Overview Installation and Setup Configuring and Running an Experiment Contributing to Aqua diff --git a/docs/aqua/multiclass_extensions.rst b/docs/aqua/multiclass_extensions.rst index 19f6c4caa5b3..3da36f97d74a 100644 --- a/docs/aqua/multiclass_extensions.rst +++ b/docs/aqua/multiclass_extensions.rst @@ -50,13 +50,13 @@ highest value from its decision function is selected as the winner and the corresponding class label is returned. In order to instantiate a ``OneAgainstRest`` object, you need to provide a ``FeatureMap`` and -an ``Estimator`` object representing the binary classifier to be used. The ``FeatureMap`` is required only -for the QSVM Kernel algorithm -- not by the SVM RBF Kernel classical algorithm. +an ``Estimator`` object representing the binary classifier to be used. The ``FeatureMap`` is +required only for the QSVM Kernel algorithm -- not by the SVM RBF Kernel classical algorithm. .. topic:: Declarative Name - When referring to the one-against-rest method declaratively inside Aqua, its code ``name``, by which Aqua - dynamically discovers and loads it, is ``OneAgainstRest``. + When referring to the one-against-rest method declaratively inside Aqua, its code ``name``, by + which Aqua dynamically discovers and loads it, is ``OneAgainstRest``. .. _all-pairs: @@ -66,14 +66,14 @@ All Pairs In the *all-pairs* reduction, one trains :math:`k(k−1)/2` binary classifiers for a :math:`k`-way multiclass problem; each receives the samples of a pair of classes from the original training set, -and must learn to distinguish these two classes. At prediction time, a *weighted voting scheme* is used: -all :math:`k(k−1)/2` classifiers are applied to an unseen sample, and each class gets assigned the sum -of all the scores obtained by the various classifiers. The combined classifier +and must learn to distinguish these two classes. At prediction time, a *weighted voting scheme* is +used: all :math:`k(k−1)/2` classifiers are applied to an unseen sample, and each class gets +assigned the sum of all the scores obtained by the various classifiers. The combined classifier returns as a result the class getting the highest value. In order to instantiate an ``AllPairs`` object, you need to provide a ``FeatureMap`` and -an ``Estimator`` object representing the binary classifier to be used. The ``FeatureMap`` is required only -for the QSVM Kernel algorithm -- not by the SVM RBF Kernel classical algorithm. +an ``Estimator`` object representing the binary classifier to be used. The ``FeatureMap`` is +required only for the QSVM Kernel algorithm -- not by the SVM RBF Kernel classical algorithm. .. topic:: Declarative Name diff --git a/docs/aqua/optimization/qiskit_optimization.rst b/docs/aqua/optimization/qiskit_optimization.rst index ecfa357c5c30..b93dedb15148 100644 --- a/docs/aqua/optimization/qiskit_optimization.rst +++ b/docs/aqua/optimization/qiskit_optimization.rst @@ -59,14 +59,15 @@ Research and developers interested in :ref:`aqua-extending` with new optimnizati capabilities can take advantage of the modular architecture of Aqua and easily extend Aqua with more algorithms and algorithm components, such as new :ref:`oracles` for the :ref:`grover` algorithm, -:ref:`optimizers` and :ref:`variational-forms` for :ref:`vqe`, :ref:`qaoa`, and :ref:`svm-variational`, -:ref:`iqfts` for :ref:`qpe`, :ref:`initial-states` for :ref:`variational-forms`, -as well as :ref:`feature-maps` and :ref:`multiclass-extensions` for Support Vector Machine +:ref:`optimizers` and :ref:`variational-forms` for :ref:`vqe`, :ref:`qaoa`, and +:ref:`svm-variational`, :ref:`iqfts` for :ref:`qpe`, :ref:`initial-states` for +:ref:`variational-forms`, as well as :ref:`feature-maps` and :ref:`multiclass-extensions` +for Support Vector Machine -------- Examples --------- +-------- The ``optimization`` folder of the `Aqua Tutorials GitHub Repository `__ contains numerous diff --git a/docs/aqua/optimizers.rst b/docs/aqua/optimizers.rst index dc2d17b4476a..63c0c89162c3 100644 --- a/docs/aqua/optimizers.rst +++ b/docs/aqua/optimizers.rst @@ -8,11 +8,11 @@ Aqua contains a variety of classical optimizers for use by quantum variational algorithms, such as :ref:`vqe`. Logically, these optimizers can be divided into two categories: -- :ref:`Local Optimizers`: Given an optimization problem, a *local optimizer* is a function that attempts to find an optimal value - within the neighboring set of a candidate solution. +- :ref:`Local Optimizers`: Given an optimization problem, a *local optimizer* is a function that + attempts to find an optimal value within the neighboring set of a candidate solution. -- :ref:`Global Optimizers`: Given an optimization problem, a *global optimizer* is a function that attempts to find an optimal value - among all possible solutions. +- :ref:`Global Optimizers`: Given an optimization problem, a *global optimizer* is a function that + attempts to find an optimal value among all possible solutions. .. topic:: Extending the Optimizer Library @@ -54,10 +54,11 @@ algorithms: - :ref:`Simultaneous Perturbation Stochastic Approximation (SPSA)` - :ref:`Truncated Newton (TNC)` -Except for :ref:`Parallel Broyden-Fletcher-Goldfarb-Shann (P-BFGS)`, all these optimizers are directly based on the ``scipy.optimize.minimize`` optimization function in the -`SciPy `__ Python library. -They all have a common pattern for parameters. Specifically, the ``tol`` parameter, whose value -must be a ``float`` indicating *tolerance for termination*, +Except for :ref:`Parallel Broyden-Fletcher-Goldfarb-Shann (P-BFGS)`, all these optimizers are +directly based on the ``scipy.optimize.minimize`` optimization function in the +`SciPy `__ +Python library. They all have a common pattern for parameters. Specifically, the ``tol`` +parameter, whose value must be a ``float`` indicating *tolerance for termination*, is from the ``scipy.optimize.minimize`` method itself, while the remaining parameters are from the `options dictionary `__, @@ -65,50 +66,52 @@ which may be referred to for further information. .. topic:: Transparent Parallelization of Gradient-based Local Opitmizers -Aqua comes with a large collection of adaptive algorithms, such as the -`Variational Quantum Eigensolver (VQE) algorithm `__, -`Quantum Approximate Optimization -Algorithm (QAOA) `__, the `Quantum -Support Vector Machine (SVM) Variational -Algorithm `__ for AI. All these -algorithms interleave quantum and classical computations, making use of -classical optimizers. Aqua includes nine local and five global -optimizers to choose from. By profiling the execution of the adaptive -algorithms, we have detected that a large portion of the execution time -is taken by the optimization phase, which runs classically. Among the -most widely used optimizers are the *gradient-based* ones; these -optimizers attempt to compute the absolute minimum (or maximum) of a -function :math:`f` through its gradient. - -Five local optimizers among those integrated into Aqua are -gradient-based: the four local optimizers *Limited-memory -Broyden-Fletcher-Goldfarb-Shanno Bound (L-BFGS-B)*, *Sequential Least SQuares Programming (SLSQP)*, *Conjugate -Gradient (CG)*, and *Truncated Newton (TNC)* from -`SciPy `__, -as well as `Simultaneous Perturbation Stochastic Approximation -(SPSA) `__. Aqua contains a -methodology that parallelizes the classical computation of the partial -derivatives in the gradient-based local optimizers listed above. This -parallelization takes place *transparently*, in the sense that Aqua -intercepts the computation of the partial derivatives and parallelizes -it without making any change to the actual source code of the -optimizers. - -In order to activate the parallelization mechanism for an adaptive -algorithm included in Aqua, it is sufficient to construct it with -parameter ``batch_mode`` set to ``True``. Our experiments have proven -empirically that parallelizing the process of a gradient-based local -optimizer achieves a 30% speedup in the execution time of an adaptive algorithms on -a simulator. + Aqua comes with a large collection of adaptive algorithms, such as the + `Variational Quantum Eigensolver (VQE) algorithm `__, + `Quantum Approximate Optimization + Algorithm (QAOA) `__, the `Quantum + Support Vector Machine (SVM) Variational + Algorithm `__ for AI. All these + algorithms interleave quantum and classical computations, making use of + classical optimizers. Aqua includes nine local and five global + optimizers to choose from. By profiling the execution of the adaptive + algorithms, we have detected that a large portion of the execution time + is taken by the optimization phase, which runs classically. Among the + most widely used optimizers are the *gradient-based* ones; these + optimizers attempt to compute the absolute minimum (or maximum) of a + function :math:`f` through its gradient. + + Five local optimizers among those integrated into Aqua are + gradient-based: the four local optimizers *Limited-memory + Broyden-Fletcher-Goldfarb-Shanno Bound (L-BFGS-B)*, *Sequential Least SQuares Programming + (SLSQP)*, *Conjugate Gradient (CG)*, and *Truncated Newton (TNC)* from + `SciPy `__, + as well as `Simultaneous Perturbation Stochastic Approximation + (SPSA) `__. Aqua contains a + methodology that parallelizes the classical computation of the partial + derivatives in the gradient-based local optimizers listed above. This + parallelization takes place *transparently*, in the sense that Aqua + intercepts the computation of the partial derivatives and parallelizes + it without making any change to the actual source code of the + optimizers. + + In order to activate the parallelization mechanism for an adaptive + algorithm included in Aqua, it is sufficient to construct it with + parameter ``batch_mode`` set to ``True``. Our experiments have proven + empirically that parallelizing the process of a gradient-based local + optimizer achieves a 30% speedup in the execution time of an adaptive algorithms on + a simulator. .. _cg: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Conjugate Gradient (CG) Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -CG is an algorithm for the numerical solution of systems of linear equations whose matrices are symmetric and positive-definite. -It is an *iterative algorithm* in that it uses an initial guess to generate a sequence of improving approximate solutions for a problem, -in which each approximation is derived from the previous ones. It is often used to solve unconstrained optimization problems, such as energy minimization. +CG is an algorithm for the numerical solution of systems of linear equations whose matrices are +symmetric and positive-definite. It is an *iterative algorithm* in that it uses an initial guess +to generate a sequence of improving approximate solutions for a problem, +in which each approximation is derived from the previous ones. It is often used to solve +unconstrained optimization problems, such as energy minimization. The following parameters are supported: @@ -128,7 +131,8 @@ The following parameters are supported: The default value is ``False``. -- A tolerance value that must be greater than the gradient norm before successful termination. +- A tolerance value that must be greater than the gradient norm before successful + termination. .. code:: python @@ -213,17 +217,17 @@ COBYLA supports the following parameters: Limited-memory Broyden-Fletcher-Goldfarb-Shanno Bound (L-BFGS-B) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The target goal of L-BFGS-B is to minimize the value of a differentiable scalar function :math:`f`. -This optimizer is a *quasi-Newton method*, meaning that, in contrast to *Newtons's method*, it +The target goal of L-BFGS-B is to minimize the value of a differentiable scalar function :math:`f`. +This optimizer is a *quasi-Newton method*, meaning that, in contrast to *Newtons's method*, it does not require :math:`f`'s *Hessian* (the matrix of :math:`f`'s second derivatives) when attempting to compute :math:`f`'s minimum value. -Like BFGS, L-BFGS is an iterative method for solving unconstrained, non-linear optimization problems, but approximates -BFGS using a limited amount of computer memory. +Like BFGS, L-BFGS is an iterative method for solving unconstrained, non-linear optimization +problems, but approximates BFGS using a limited amount of computer memory. L-BFGS starts with an initial estimate of the optimal value, and proceeds iteratively to refine that estimate with a sequence of better estimates. The derivatives of :math:`f` are used to identify the direction of steepest descent, and also to form an estimate of the Hessian matrix (second derivative) of :math:`f`. -L-BFGS-B extends L-BFGS to handle simple, per-variable bound constraints. +L-BFGS-B extends L-BFGS to handle simple, per-variable bound constraints. The following parameters are supported: @@ -278,7 +282,7 @@ Nelder-Mead The Nelder-Mead algorithm performs unnconstrained optimization; it ignores bounds or constraints. It is used to find the minimum or maximum of an objective function in a multidimensional space. It is based on the Simplex algorithm. Nelder-Mead -is robust in many applications, especially when the first and second derivatives of the +is robust in many applications, especially when the first and second derivatives of the objective function are not known. However, if the numerical computation of the derivatives can be trusted to be accurate, other algorithms using the first and/or second derivatives information might be preferred to Nelder-Mead for their @@ -293,8 +297,8 @@ The following parameters are supported: maxiter = 1 | 2 | ... - This parameter is optional. If specified, the value of this parameter must be a positive ``int``, otherwise, it is ``None``. - The default is ``None``. + This parameter is optional. If specified, the value of this parameter must be a positive + ``int``, otherwise, it is ``None``. The default is ``None``. - The maximum number of functional evaluations to perform: @@ -312,12 +316,12 @@ The following parameters are supported: The default is ``False``. -- A tolerance parameter indicating the absolute error in ``xopt`` between iterations that will be considered acceptable - for convergence. +- A tolerance parameter indicating the absolute error in ``xopt`` between iterations that will + be considered acceptable for convergence. .. code:: python - xatol : float + xatol : float The default value is ``0.0001``. @@ -349,13 +353,15 @@ The following parameters are supported: Parallel Broyden-Fletcher-Goldfarb-Shann (P-BFGS) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -P-BFGS is a parallellized version of `L-BFGS-B <#limited-memory-broyden-fletcher-goldfarb-shanno-bound-l-bfgs-b>`__, +P-BFGS is a parallellized version of +`L-BFGS-B <#limited-memory-broyden-fletcher-goldfarb-shanno-bound-l-bfgs-b>`__, with which it shares the same parameters. P-BFGS can be useful when the target hardware is a quantum simulator running on a classical machine. This allows the multiple processes to use simulation to potentially reach a minimum faster. The parallelization may help the optimizer avoid getting stuck at local optima. In addition to the parameters of -L-BFGS-B, P-BFGS supports an following parameter --- the maximum number of processes spawned by P-BFGS: +L-BFGS-B, P-BFGS supports an following parameter --- the maximum number of processes spawned by +P-BFGS: .. code:: python @@ -402,7 +408,8 @@ The following parameters are supported: maxiter = 1 | 2 | ... - This parameter is optional. If specified, the value of this parameter must be a positive ``int``, otherwise, it is ``None``. + This parameter is optional. If specified, the value of this parameter must be a positive + ``int``, otherwise, it is ``None``. The default is ``None``. - The maximum number of functional evaluations to perform: @@ -421,8 +428,8 @@ The following parameters are supported: The default is ``False``. -- A tolerance parameter indicating the absolute error in ``xopt`` between iterations that will be considered acceptable - for convergence. +- A tolerance parameter indicating the absolute error in ``xopt`` between iterations that will be + considered acceptable for convergence. .. code:: python @@ -454,10 +461,9 @@ SLSQP minimizes a function of several variables with any combination of bounds, equality and inequality constraints. The method wraps the SLSQP Optimization subroutine originally implemented by Dieter Kraft. -SLSQP is ideal for mathematical problems for which the objective function and the constraints are twice continuously differentiable. -Note that the wrapper -handles infinite values in bounds by converting them into large floating -values. +SLSQP is ideal for mathematical problems for which the objective function and the constraints are +twice continuously differentiable. Note that the wrapper handles infinite values in bounds by +converting them into large floating values. The following parameters are supported: @@ -477,7 +483,8 @@ The following parameters are supported: The default is ``False``. -- A tolerance value indicating precision goal for the value of the objective function in the stopping criterion. +- A tolerance value indicating precision goal for the value of the objective function in the + stopping criterion. .. code:: python @@ -514,7 +521,8 @@ Simultaneous Perturbation Stochastic Approximation (SPSA) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SPSA is an algorithmic method for optimizing systems with multiple unknown parameters. -As an optimization method, it is appropriately suited to large-scale population models, adaptive modeling, and simulation optimization. +As an optimization method, it is appropriately suited to large-scale population models, +adaptive modeling, and simulation optimization. .. seealso:: Many examples are presented at the `SPSA Web site `__. @@ -540,7 +548,7 @@ functional evaluations. Overall, the following parameters are supported: .. code:: python max_trials = 1 | 2 | ... - + A positive ``int`` value is expected. The default value is ``1000``. - An ``int`` value determining how often optimization outcomes should be stored during execution: @@ -571,7 +579,8 @@ functional evaluations. Overall, the following parameters are supported: c3 : float; default value is 0.101 c4 : float; default value is 0 - These are the SPSA control parameters, consisting of 5 ``float`` values, and are used as described below. + These are the SPSA control parameters, consisting of 5 ``float`` values, and are used as + described below. SPSA updates the parameters (``theta``) for the objective function (``J``) through the following equation at @@ -585,9 +594,11 @@ functional evaluations. Overall, the following parameters are supported: theta_{k}+ = theta_{k} + c1 * ( k + 1)^(-c3) * delta theta_{k}- = theta_{k} - c1 * ( k + 1)^(-c3) * delta - ``J(theta)`` is the objective value of ``theta``. ``c0``, ``c1``, ``c2``, ``c3`` and ``c4`` are the five control parameters. + ``J(theta)`` is the objective value of ``theta``. ``c0``, ``c1``, ``c2``, ``c3`` and ``c4`` + are the five control parameters. By default, ``c0`` is calibrated through a few evaluations on the - objective function with the initial ``theta``. ``c1``, ``c2``, ``c3`` and ``c4`` are set as ``0.1``, + objective function with the initial ``theta``. ``c1``, ``c2``, ``c3`` and ``c4`` are set as + ``0.1``, ``0.602``, ``0.101``, ``0.0``, respectively. - Calibration step for SPSA. @@ -596,9 +607,12 @@ functional evaluations. Overall, the following parameters are supported: skip_calibration: bool - The default value is ``False``. When calibration is done, i.e. when ``skip_calibration`` is ``False`` (by default) the - control parameter ``c0`` as supplied is adjusted by the calibration step before optimization. If ``skip_calibration`` - is ``True`` then the calibration step, which occurs ahead of optimization, is skipped and ``c0`` will be used unaltered. + The default value is ``False``. When calibration is done, i.e. when ``skip_calibration`` is + ``False`` (by default) the + control parameter ``c0`` as supplied is adjusted by the calibration step before optimization. + If ``skip_calibration`` + is ``True`` then the calibration step, which occurs ahead of optimization, is skipped and + ``c0`` will be used unaltered. .. topic:: Declarative Name @@ -619,7 +633,6 @@ allows each variable to be given upper and lower bounds. The following parameters are supported: - The maximum number of iterations: - .. code:: python maxiter = 1 | 2 | ... @@ -627,7 +640,6 @@ The following parameters are supported: A positive ``int`` value is expected. The default is ``100``. - A Boolean value indicating whether or not to print convergence messages: - .. code:: python disp : bool @@ -635,32 +647,31 @@ The following parameters are supported: The default value is ``False``. - Relative precision for finite difference calculations: - .. code:: python accuracy : float The default value is ``0.0``. -- A tolerance value indicating the precision goal for the value of the objective function ``f`` in the stopping criterion. - +- A tolerance value indicating the precision goal for the value of the objective function + ``f`` in the stopping criterion. .. code:: python ftol : float The default value is ``-1``. -- A tolerance value indicating precision goal for the value of ``x`` in the stopping criterion, after applying ``x`` scaling factors. - +- A tolerance value indicating precision goal for the value of ``x`` in the stopping criterion, + after applying ``x`` scaling factors. .. code:: python xtol : float The default value is ``-1``. -- A tolerance value indicating precision goal for the value of the projected gradient ``g`` in the stopping criterion, +- A tolerance value indicating precision goal for the value of the projected gradient ``g`` in + the stopping criterion, after applying ``x`` scaling factors. - .. code:: python gtol : float @@ -668,7 +679,6 @@ The following parameters are supported: The default value is ``-1``. - The tolerance for termination: - .. code:: tol : float @@ -677,7 +687,6 @@ The following parameters are supported: The default is ``None`` - Step size used for numerical approximation of the Jacobian. - .. code:: python eps : float @@ -763,9 +772,9 @@ Controller Random Search (CRS) with Local Mutation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `CRS with local mutation `__ is part of the family of the CRS optimizers. -The CRS optimizers start with a random population of points, and randomly evolve these points by heuristic rules. -In the case of CRS with local mutation, the evolution is a randomized version of the -:ref:`Nelder-Mead` local optimizer. +The CRS optimizers start with a random population of points, and randomly evolve these points by +heuristic rules. In the case of CRS with local mutation, the evolution is a randomized version of +the :ref:`Nelder-Mead` local optimizer. .. topic:: Declarative Name @@ -778,8 +787,8 @@ In the case of CRS with local mutation, the evolution is a randomized version of DIviding RECTangles algorithm - Locally based (DIRECT-L) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -DIviding RECTangles (DIRECT) is a deterministic-search algorithms based on systematic division of the search domain -into increasingly smaller hyperrectangles. +DIviding RECTangles (DIRECT) is a deterministic-search algorithms based on systematic division of +the search domain into increasingly smaller hyperrectangles. The `DIRECT-L `__ version is a variant of DIRECT that makes the algorithm more biased towards local search, so that it is more efficient for functions with few local minima. @@ -827,12 +836,13 @@ Improved Stochastic Ranking Evolution Strategy (ISRES) `ISRES `__ is an algorithm for nonlinearly-constrained global optimization. -It has heuristics to escape local optima, even though convergence to a global optima is not guaranteed. -The evolution strategy is based on a combination of a mutation rule and differential variation. -The fitness ranking is simply via the objective function for problems without nonlinear constraints. -When nonlinear constraints are included, the -`stochastic ranking proposed by Runarsson and Yao `__ is employed. -This method supports arbitrary nonlinear inequality and equality constraints, in addition to the bound constraints. +It has heuristics to escape local optima, even though convergence to a global optima is not +guaranteed. The evolution strategy is based on a combination of a mutation rule and differential +variation. The fitness ranking is simply via the objective function for problems without nonlinear +constraints. When nonlinear constraints are included, the +`stochastic ranking proposed by Runarsson and Yao `__ +is employed. This method supports arbitrary nonlinear inequality and equality constraints, in +addition to the bound constraints. .. topic:: Declarative Name diff --git a/docs/aqua/oracles.rst b/docs/aqua/oracles.rst index 61ee94a67ce3..55d07d02a257 100644 --- a/docs/aqua/oracles.rst +++ b/docs/aqua/oracles.rst @@ -97,8 +97,8 @@ clause. Essentially, the code above corresponds to the following CNF: An example showing how to use the Grover algorithm on a DIMACS oracle to search for a satisfying assignment to an SAT problem encoded in DIMACS -is available in the -``optimization`` folder of the `Qiskit Tutorials GitHub repository +is available in the ``optimization`` folder of the +`Qiskit Tutorials GitHub repository `__. Logic expressions, regardless of the input formats, diff --git a/docs/aqua/overview.rst b/docs/aqua/overview.rst index 775405a4e04f..bc255f6cd9e4 100644 --- a/docs/aqua/overview.rst +++ b/docs/aqua/overview.rst @@ -42,8 +42,8 @@ Quantum algorithm researchers and developers can experiment with the algorithms in Aqua, or contribute their own algorithms via the pluggable interface exposed by Aqua. In addition to plain quantum algorithms, Aqua offers a vast set of supporting components, such as variational forms, local and global optimizers, initial states, -Quantum Fourier Transforms (QFTs) and Grover oracles. These components are also extensible via pluggable -interfaces. +Quantum Fourier Transforms (QFTs) and Grover oracles. These components are also extensible +via pluggable interfaces. -------------- Novel Features @@ -51,8 +51,8 @@ Novel Features In addition to its modularity and extensibility, ability to span across multiple domains, and top-to-bottom completeness from classical computational software to -quantum hardware, compared to other quantum software stacks, Aqua presents numerous unique advantages -in terms of usability, functionality, and configuration-correctness enforcement. +quantum hardware, compared to other quantum software stacks, Aqua presents numerous unique +advantages in terms of usability, functionality, and configuration-correctness enforcement. ^^^^^^^^^^^^^^^ User Experience @@ -81,18 +81,15 @@ Functionality ^^^^^^^^^^^^^ If Aqua had been designed to interpose a quantum programming language -or new APIs between the user and the classical computational software, it would not have been able to -fully exploit all the features of the underlying classical computational software unless those features -had been exposed at the higher programming-language or API level. In other words, in order to drive -the classical execution of any interfaced computational software to the most -precise computation of the intermediate data needed to form +or new APIs between the user and the classical computational software, it would not have been able +to fully exploit all the features of the underlying classical computational software unless +those features had been exposed at the higher programming-language or API level. In other +words, in order to drive the classical execution of any interfaced computational +software to the most precise computation of the intermediate data needed to form the quantum input, the advanced features of that software would have had to be configurable -through Aqua. -Given the intention for Aqua to have an extensible interface capable of accepting -any classical computational -software, the insertion of a quantum-specific programming language or API would have -been not only a usability -obstacle, but also a functionality-limiting factor. +through Aqua. Given the intention for Aqua to have an extensible interface capable of accepting +any classical computational software, the insertion of a quantum-specific programming language or +API would have been not only a usability obstacle, but also a functionality-limiting factor. The ability of Aqua to directly interface classical computational software allows that software to compute the intermediate data needed to form the quantum input at its highest level of precision. @@ -116,7 +113,6 @@ resilient to configuration errors. Very importantly, configuration correctness is dynamically enforced even for components that are dynamically discovered and loaded. - .. include:: CONTRIBUTORS.rst ------- diff --git a/docs/aqua/random_distributions.rst b/docs/aqua/random_distributions.rst index 44b0ce080ff8..fc3bb06f2131 100644 --- a/docs/aqua/random_distributions.rst +++ b/docs/aqua/random_distributions.rst @@ -4,9 +4,10 @@ Random Distributions ==================== -A random distribution is an implementation of a circuit factory that provides a way to construct a quantum circuit -to prepare a state which corresponds to a random distribution. -More precisely, the resulting state together with an affine map can be used to sample from the considered distribution. +A random distribution is an implementation of a circuit factory that provides a way to construct a +quantum circuit to prepare a state which corresponds to a random distribution. +More precisely, the resulting state together with an affine map can be used to sample from the +considered distribution. The qubits are measured and then mapped to the desired range using the affine map. In the following, we discuss the currently existing implementations. diff --git a/docs/aqua/reciprocals.rst b/docs/aqua/reciprocals.rst index 8aacaeed8bca..427fff0118d3 100644 --- a/docs/aqua/reciprocals.rst +++ b/docs/aqua/reciprocals.rst @@ -4,8 +4,9 @@ Reciprocals =========== -Aqua bundles methods to invert a fixed-point number prepared in a quantum register in the Reciprocals library. -Rather than being used as a standalone algorithm, the members of the library are to be used in a larger algorithm such as :ref:`HHL`. The following methods are available +Aqua bundles methods to invert a fixed-point number prepared in a quantum register in the +Reciprocals library. Rather than being used as a standalone algorithm, the members of the library +are to be used in a larger algorithm such as :ref:`HHL`. The following methods are available - :ref:`lookup` @@ -32,9 +33,12 @@ Rather than being used as a standalone algorithm, the members of the library are Partial Table Look Up --------------------- -This method applies a variable sized binning to the values. Only a specified number of bits after the most-significant bit is taken into account when assigning rotation angles to the numbers prepared as states in the input register. -Using precomputed angles, the reciprocal is multiplied to the amplitude via controlled rotations. -While no resolution of the result is lost for small values, towards larger values the bin size increases. The accuracy of the result is tuned by the parameters. The following parameters are exposed: +This method applies a variable sized binning to the values. Only a specified number of bits after +the most-significant bit is taken into account when assigning rotation angles to the numbers +prepared as states in the input register. Using precomputed angles, the reciprocal is multiplied +to the amplitude via controlled rotations. While no resolution of the result is lost for small +values, towards larger values the bin size increases. The accuracy of the result is tuned by the +parameters. The following parameters are exposed: - The number of bits used to approximate the numbers: @@ -42,7 +46,10 @@ While no resolution of the result is lost for small values, towards larger value pat_length : int - Specifies the number of bits following the most-significant bit that is used to identify a number. This leads to a binning of large values, while preserving the accuracy for smaller values. It should be chosen as :math:`min(k-1,5)` for an input register with k qubits to limit the error in the rotation to < 3%. + Specifies the number of bits following the most-significant bit that is used to identify a + number. This leads to a binning of large values, while preserving the accuracy for smaller + values. It should be chosen as :math:`min(k-1,5)` for an input register with k qubits to limit + the error in the rotation to < 3%. - The length of a sub string of the binary identifier: @@ -50,7 +57,8 @@ While no resolution of the result is lost for small values, towards larger value subpat_length : int - This parameter is computed in the circuit creation routine and helps reducing the gate count. For ``pat_length<=5`` it is chosen as :math:`\left\lceil(\frac{patlength}{2})\right\rceil`. + This parameter is computed in the circuit creation routine and helps reducing the gate count. + For ``pat_length<=5`` it is chosen as :math:`\left\lceil(\frac{patlength}{2})\right\rceil`. - Switch for negative values: @@ -58,7 +66,8 @@ While no resolution of the result is lost for small values, towards larger value negative_evals : bool - If known beforehand that only positive values are present, one can set this switch to False and achieve a higher resolution in the output. The default is ``True``. + If known beforehand that only positive values are present, one can set this switch to False and + achieve a higher resolution in the output. The default is ``True``. - The scale factor of the values: @@ -66,7 +75,9 @@ While no resolution of the result is lost for small values, towards larger value scale : float - This parameter is used to scale the reciprocals such that for a scale C, the rotation is performed by an angle :math:`\arcsin{\frac{C}{\lambda}}`. If neither the ``scale`` nor the ``evo_time`` and and ``min_lambda`` parameters are specified, the smallest resolvable Eigenvalue is used. + This parameter is used to scale the reciprocals such that for a scale C, the rotation is performed + by an angle :math:`\arcsin{\frac{C}{\lambda}}`. If neither the ``scale`` nor the ``evo_time`` and + ``min_lambda`` parameters are specified, the smallest resolvable Eigenvalue is used. - The mimimum value present: @@ -74,7 +85,8 @@ While no resolution of the result is lost for small values, towards larger value lambda_min : float - If the minimum value is known beforehand, the optimal ``scale`` parameter can be calculated using the parameters ``lambda_min`` and ``evo_time``. + If the minimum value is known beforehand, the optimal ``scale`` parameter can be calculated using + the parameters ``lambda_min`` and ``evo_time``. - The evolution time: @@ -82,7 +94,10 @@ While no resolution of the result is lost for small values, towards larger value evo_time : float - This parameter scales the Eigenvalues in the :ref:`qpe_components` onto the range (0,1] ( (-0.5,0.5] for negativ EV ). If the Partial Table Look Up is used together with the QPE, the scale parameter can be estimated if the minimum EV and the evolution time are passed as parameters. The default is ``None``. + This parameter scales the Eigenvalues in the :ref:`qpe_components` onto the range (0,1] + ( (-0.5,0.5] for negativ EV ). If the Partial Table Look Up is used together with the QPE, the + scale parameter can be estimated if the minimum EV and the evolution time are passed as + parameters. The default is ``None``. .. topic:: Declarative Name @@ -95,9 +110,14 @@ While no resolution of the result is lost for small values, towards larger value Long Division ------------- -This method calculates inverse of eigenvalues using binary long division and performs the corresponnding rotation. Long division is implemented as a sequance of subtraction (utilizing ripple carry adder module) and bit shifting. The method allows for adjusting of the reciprocal precision by changing number of iterations. The method was optimized for register conventions used in HHL algorithm (i.e. eigenvalues rescaled to values between 0 and 1). +This method calculates inverse of eigenvalues using binary long division and performs the +corresponnding rotation. Long division is implemented as a sequance of subtraction (utilizing +ripple carry adder module) and bit shifting. The method allows for adjusting of the reciprocal +precision by changing number of iterations. The method was optimized for register conventions +used in HHL algorithm (i.e. eigenvalues rescaled to values between 0 and 1). -The rotation value is always scaled down additionally to the normal scale parameter by 0.5 to get the angle into the linear part of the arcsin(x). The following parameters are exposed: +The rotation value is always scaled down additionally to the normal scale parameter by 0.5 to get +the angle into the linear part of the arcsin(x). The following parameters are exposed: - The scale factor of the values: @@ -105,7 +125,9 @@ The rotation value is always scaled down additionally to the normal scale parame scale : float -This parameter is used to scale the reciprocals such that for a scale C, the rotation is performed by an angle :math:`\arcsin{\frac{C}{\lambda}}`. If neither the ``scale`` nor the ``evo_time`` and and ``min_lambda`` parameters are specified, the smallest resolvable Eigenvalue is used. +This parameter is used to scale the reciprocals such that for a scale C, the rotation is performed +by an angle :math:`\arcsin{\frac{C}{\lambda}}`. If neither the ``scale`` nor the ``evo_time`` and +``min_lambda`` parameters are specified, the smallest resolvable Eigenvalue is used. - The number of ancillae: @@ -113,7 +135,9 @@ This parameter is used to scale the reciprocals such that for a scale C, the rot num_ancillae = 3 | 4 | ... -This parameter sets the number of ancillary qubits (the input register size). A positive ``int`` value is expected. The default value is ``None`` and the minimum value ``3``. If negative eigenvalues are enabled, the minimum value is ``4 ``The default is ``0``. +This parameter sets the number of ancillary qubits (the input register size). A positive ``int`` +value is expected. The default value is ``None`` and the minimum value ``3``. If negative +eigenvalues are enabled, the minimum value is ``4 ``The default is ``0``. - Switch for negative values: @@ -121,7 +145,8 @@ This parameter sets the number of ancillary qubits (the input register size). A negative_evals : bool - If known beforehand that only positive values are present, one can set this switch to False and achieve a higher resolution in the output. The default is ``True``. + If known beforehand that only positive values are present, one can set this switch to False and + achieve a higher resolution in the output. The default is ``True``. - The mimimum value present: @@ -129,7 +154,8 @@ This parameter sets the number of ancillary qubits (the input register size). A lambda_min : float - If the minimum value is known beforehand, the optimal ``scale`` parameter can be calculated using the parameters ``lambda_min`` and ``evo_time``. + If the minimum value is known beforehand, the optimal ``scale`` parameter can be calculated + using the parameters ``lambda_min`` and ``evo_time``. - The evolution time: @@ -137,7 +163,10 @@ This parameter sets the number of ancillary qubits (the input register size). A evo_time : float - This parameter scales the Eigenvalues in the :ref:`qpe_components` onto the range (0,1] ( (-0.5,0.5] for negativ EV ). If the Partial Table Look Up is used together with the QPE, the scale parameter can be estimated if the minimum EV and the evolution time are passed as parameters. The default is ``None``. + This parameter scales the Eigenvalues in the :ref:`qpe_components` onto the range (0,1] + ( (-0.5,0.5] for negativ EV ). If the Partial Table Look Up is used together with the QPE, the + scale parameter can be estimated if the minimum EV and the evolution time are passed as + parameters. The default is ``None``. - The Reciprocal precision: @@ -145,7 +174,8 @@ This parameter sets the number of ancillary qubits (the input register size). A precision : int -The parameter sets minimum desired bit precision for the reciprocal. Due to shifting some of reciprocals, however, are effectively estimated with higher than this minimum specified precision. +The parameter sets minimum desired bit precision for the reciprocal. Due to shifting some of +reciprocals, however, are effectively estimated with higher than this minimum specified precision. .. topic:: Declarative Name diff --git a/docs/aqua/release_history.rst b/docs/aqua/release_history.rst index 84a72067c1c5..71d821b0df59 100644 --- a/docs/aqua/release_history.rst +++ b/docs/aqua/release_history.rst @@ -25,25 +25,30 @@ we have added the following new features : - Compatibility with Terra 0.7 - Compatibility with Aer 0.1 -- Programmatic APIs for algorithms and components -- each component can now be instantiated and initialized via a single (non-empty) constructor call -- ``QuantumInstance`` API for algorithm/backend decoupling -- ``QuantumInstance`` encapsulates a backend and its settings +- Programmatic APIs for algorithms and components -- each component can now be instantiated and + initialized via a single (non-empty) constructor call - ``QuantumInstance`` API for + algorithm/backend decoupling -- ``QuantumInstance`` encapsulates a backend and its settings - Updated documentation and Jupyter Notebooks illustrating the new programmatic APIs - Transparent parallelization for gradient-based optimizers - Multiple-Controlled-NOT (cnx) operation - Pluggable algorithmic component ``RandomDistribution`` -- Concrete implementations of ``RandomDistribution``: ``BernoulliDistribution``, ``LogNormalDistribution``, - ``MultivariateDistribution``, ``MultivariateNormalDistribution``, ``MultivariateUniformDistribution``, ``NormalDistribution``, - ``UniformDistribution``, and ``UnivariateDistribution`` +- Concrete implementations of ``RandomDistribution``: ``BernoulliDistribution``, + ``LogNormalDistribution``, ``MultivariateDistribution``, ``MultivariateNormalDistribution``, + ``MultivariateUniformDistribution``, ``NormalDistribution``, ``UniformDistribution``, and + ``UnivariateDistribution`` - Pluggable algorithmic component: -- Concrete implementations of ``UncertaintyProblem``: ``FixedIncomeExpectedValue``, ``EuropeanCallExpectedValue``, and - ``EuropeanCallDelta`` +- Concrete implementations of ``UncertaintyProblem``: ``FixedIncomeExpectedValue``, + ``EuropeanCallExpectedValue``, and ``EuropeanCallDelta`` - Amplitude Estimation algorithm -- Qiskit Optimization: New Ising models for optimization problems exact cover, set packing, vertex cover, clique, and graph partition +- Qiskit Optimization: New Ising models for optimization problems exact cover, set packing, vertex + cover, clique, and graph partition - Qiskit AI: - - New feature maps extending the ``FeatureMap`` pluggable interface: ``PauliExpansion`` and ``PauliZExpansion`` - - Training model serialization/deserialization mechanism + - New feature maps extending the ``FeatureMap`` pluggable interface: ``PauliExpansion`` and + ``PauliZExpansion`` +- Training model serialization/deserialization mechanism - Qiskit Finance: - - Amplitude estimation for Bernoulli random variable: illustration of amplitude estimation on a single qubit problem + - Amplitude estimation for Bernoulli random variable: illustration of amplitude estimation on a + single qubit problem - Loading of multiple univariate and multivariate random distributions - European call option: expected value and delta (using univariate distributions) - Fixed income asset pricing: expected value (using multivariate distributions) @@ -200,8 +205,8 @@ function :math:`f` through its gradient. Five local optimizers among those integrated into Aqua are gradient-based: the four local optimizers *Limited-memory -Broyden-Fletcher-Goldfarb-Shanno Bound (L-BFGS-B)*, *Sequential Least SQuares Programming (SLSQP)*, *Conjugate -Gradient (CG)*, and *Truncated Newton (TNC)* from +Broyden-Fletcher-Goldfarb-Shanno Bound (L-BFGS-B)*, *Sequential Least SQuares Programming +(SLSQP)*, *Conjugate Gradient (CG)*, and *Truncated Newton (TNC)* from `SciPy `__, as well as `Simultaneous Perturbation Stochastic Approximation (SPSA) `__. Aqua 0.4 contains a @@ -264,9 +269,9 @@ considered distribution. The qubits are measured and then mapped to the desired range using the affine map. Aqua 0.4 introduces random distributions in the form of the ``RandomDistribution`` pluggable component, and provides numerous concrete implementations, such as -``BernoulliDistribution``, ``LogNormalDistribution``,  +``BernoulliDistribution``, ``LogNormalDistribution``, ``MultivariateDistribution``, ``MultivariateNormalDistribution``, -``MultivariateUniformDistribution``, ``NormalDistribution``,  +``MultivariateUniformDistribution``, ``NormalDistribution``, ``UniformDistribution``, and ``UnivariateDistribution``. ^^^^^^^^^^^^^^^^^^^^ diff --git a/docs/aqua/tutorials/aqua_tutorials.rst b/docs/aqua/tutorials/aqua_tutorials.rst index 9d89612eefd6..2d48d1d33bed 100644 --- a/docs/aqua/tutorials/aqua_tutorials.rst +++ b/docs/aqua/tutorials/aqua_tutorials.rst @@ -4,8 +4,9 @@ Aqua Tutorials ************** -A large number of tutorials illustrating how to use and extend Qiskit Aqua and its applications are available -in the ``qiskit/aqua`` and ``community/aqua`` folders of the `Qiskit Tutorials `__ repository. +A large number of tutorials illustrating how to use and extend Qiskit Aqua and its applications +are available in the ``qiskit/aqua`` and ``community/aqua`` folders of the +`Qiskit Tutorials `__ repository. These tutorials are a set of code examples, `Jupyter Notebooks `__ and sample input files diff --git a/docs/aqua/uncertainty_problems.rst b/docs/aqua/uncertainty_problems.rst index 27f5e6f65d91..ee1366c10037 100644 --- a/docs/aqua/uncertainty_problems.rst +++ b/docs/aqua/uncertainty_problems.rst @@ -7,21 +7,21 @@ Uncertainty Problems Uncertainty is present in most realistic applications, and often it is necessary to evaluate the behavior of a system under uncertain data. For instance, in finance, it is of interest to evaluate expected value or risk metrics of -financial products that depend on underlying stock prices, economic factors, or changing interest rates. -Classically, such problems are often evaluated using Monte Carlo simulation. -However, Monte Carlo simulation does not converge very fast, which implies that large numbers of samples -are required to achieve estimators of reasonable accuracy and confidence. -In quantum computing, *amplitude estimation* can be used instead, which can lead to a quadratic speed-up. -Thus, millions of classical samples could be replaced by a few thousand quantum samples. - -*Amplitude estimation* is a derivative of *quantum phase estimation* applied to a particular operator :math:`A`. -:math:`A` is assumed to operate on (n+1) qubits (+ possible ancillas) where the n qubits represent the uncertainty -(random distribution :ref:`random_distribution`) and the last qubit is used to represent the (normalized) objective value -as its amplitude. -In other words, :math:`A` is constructed such that the probability of measuring a '1' in the objective qubit is equal to the -value of interest. -An implementation of an uncertainty problem is assumed to provide a dictionary with parameter, -particularly containing the index of the qubit used for the objective: +financial products that depend on underlying stock prices, economic factors, or changing +interest rates. Classically, such problems are often evaluated using Monte Carlo simulation. +However, Monte Carlo simulation does not converge very fast, which implies that large numbers of +samples are required to achieve estimators of reasonable accuracy and confidence. +In quantum computing, *amplitude estimation* can be used instead, which can lead to a quadratic +speed-up. Thus, millions of classical samples could be replaced by a few thousand quantum samples. + +*Amplitude estimation* is a derivative of *quantum phase estimation* applied to a particular +operator :math:`A`. :math:`A` is assumed to operate on (n+1) qubits (+ possible ancillas) where +the n qubits represent the uncertainty (random distribution :ref:`random_distribution`) and the +last qubit is used to represent the (normalized) objective value as its amplitude. +In other words, :math:`A` is constructed such that the probability of measuring a '1' in the +objective qubit is equal to the value of interest. An implementation of an uncertainty problem is +assumed to provide a dictionary with parameter, particularly containing the index of the qubit +used for the objective: .. code:: python @@ -30,7 +30,8 @@ particularly containing the index of the qubit used for the objective: 'i_objective': i_objective } -Since the value of interest has to be normalized to lie in [0, 1], an uncertainty problem also provides a function: +Since the value of interest has to be normalized to lie in [0, 1], an uncertainty problem also +provides a function: .. code:: python diff --git a/docs/aqua/variational_forms.rst b/docs/aqua/variational_forms.rst index 721d4b7004ac..12b082602aea 100644 --- a/docs/aqua/variational_forms.rst +++ b/docs/aqua/variational_forms.rst @@ -4,24 +4,25 @@ Variational Forms ================= -In quantum mechanics, the *variational method* is one way of finding approximations to the lowest energy -eigenstate, or *ground state*, and some excited states. This allows calculating approximate wave functions, -such as molecular orbitals. The basis for this method is the *variational principle*. - -The variational method consists of choosing a *trial wave function*, or *variational form*, that depends on one -or more parameters, and finding the values of these parameters for which the expectation value of the energy -is the lowest possible. The wave function obtained by fixing the parameters to such values is then an -approximation to the ground state wave function, and the expectation value of the energy in that state -is an upper bound to the ground state energy. Quantum variational algorithms, such as -:ref:`vqe`, apply -the variational method. As such, they require a variational form. +In quantum mechanics, the *variational method* is one way of finding approximations to the lowest +energy eigenstate, or *ground state*, and some excited states. This allows calculating approximate +wave functions, such as molecular orbitals. The basis for this method is the *variational +principle*. + +The variational method consists of choosing a *trial wave function*, or *variational form*, that +depends on one or more parameters, and finding the values of these parameters for which the +expectation value of the energy is the lowest possible. The wave function obtained by fixing the +parameters to such values is then an approximation to the ground state wave function, and the +expectation value of the energy in that state is an upper bound to the ground state energy. Quantum +variational algorithms, such as :ref:`vqe`, apply the variational method. As such, they require a +variational form. In Aqua, variational forms are pluggable entities. Practitioners who want to use Aqua mainly as a tool to experiment with :ref:`quantum-algorithms`, and particularly -with variational algorithms, will need to make use of variational forms. On the other hand, researchers -who want the advance the field of quantum computing, and design and develop new variational forms, can do so -by extending Aqua with new variational forms, which will be dynamically discovered at run time and made -available for use by quantum variational algorithms. +with variational algorithms, will need to make use of variational forms. On the other hand, +researchers who want the advance the field of quantum computing, and design and develop new +variational forms, can do so by extending Aqua with new variational forms, which will be +dynamically discovered at run time and made available for use by quantum variational algorithms. .. topic:: Extending the Variational Form Library @@ -42,7 +43,7 @@ available for use by quantum variational algorithms. called with parameters as per the schema. The number of qubits will also be supplied as the value of the parameter following ``self`` in the method argument list. During initialization, in ``init_args``, the variational form should set the number of parameters it has and their bounds, as in the following example: - + .. code:: python self._num_parameters = num_qubits * (depth + 1) @@ -57,7 +58,7 @@ available for use by quantum variational algorithms. using the previous computed optimal solution as the starting initial point for the next interatomic distance is going to reduce the number of iterations necessary for the variational algorithm to converge. Aqua provides `a tutorial detailing this use case `__. - + :ref:`vqe` can, therefore, take an optional initial point from the user as the value of the ``initial_point`` parameter, specified as a list of ``float`` values. The length of this list must match the number of the parameters expected by the variational form being used. @@ -94,8 +95,9 @@ Currently, Aqua supplies the following variational forms: Ry -- -The Ry trial wave function is layers of :math:`y` rotations with entanglements. The number of optimizer parameters this form -creates and uses is given by :math:`q \times (d + 1)`, where :math:`q` is the total number of qubits and :math:`d` is the depth of the circuit. +The Ry trial wave function is layers of :math:`y` rotations with entanglements. The number of +optimizer parameters this form creates and uses is given by :math:`q \times (d + 1)`, where +:math:`q` is the total number of qubits and :math:`d` is the depth of the circuit. The following allows a specific form to be configured in the ``variational_form`` section of the Aqua @@ -116,10 +118,11 @@ is set to ``RY``: entanglement = "full" | "linear" - Only two ``str`` values are supported: ``"full"`` and ``"linear"``, corresponding to the *full* (or *all-to-all*) and - *linear* (or *next-neighbor coupling*) entangler maps, respectively. With full entanglement, each qubit is entangled with all the - others; with linear entanglement, qubit :math:`i` is entangled with qubit :math:`i + 1`, for all :math:`i \in \{0, 1, ... , q - 2\}`, - where :math:`q` is the total number of qubits. + Only two ``str`` values are supported: ``"full"`` and ``"linear"``, corresponding to the + *full* (or *all-to-all*) and *linear* (or *next-neighbor coupling*) entangler maps, respectively. + With full entanglement, each qubit is entangled with all the others; with linear entanglement, + qubit :math:`i` is entangled with qubit :math:`i + 1`, for all + :math:`i \in \{0, 1, ... , q - 2\}`, where :math:`q` is the total number of qubits. - A dictionary of lists of non-negative ``int`` values specifying the entangler map: @@ -127,50 +130,64 @@ is set to ``RY``: entangler_map = {0: [1 | ... | q - 1], 1: [0 | 2 | ... | q - 1], ... , q - 1: [0 | 1 | ... | q - 2]} - The ``entanglement`` parameter defined above can be overridden by an entangler map explicitly specified as the value of the - ``entangler_map`` parameter, if an entanglement map different + The ``entanglement`` parameter defined above can be overridden by an entangler map explicitly + specified as the value of the ``entangler_map`` parameter, if an entanglement map different from full or linear is desired. - As explained more generally above, the form of the map is a dictionary; each entry in the dictionary has a source qubit - index as the key, with the corresponding value being a list of target qubit indexes to which the source qubit should + As explained more generally above, the form of the map is a dictionary; each entry in the + dictionary has a source qubit + index as the key, with the corresponding value being a list of target qubit indexes to which the + source qubit should be entangled. - Indexes are ``int`` values from :math:`0` to :math:`q-1`, where :math:`q` is the total number of qubits, + Indexes are ``int`` values from :math:`0` to :math:`q-1`, where :math:`q` is the total number of + qubits, as in the following example: - + .. code:: python entangler_map = {0: [1, 2], 1: [3]} .. warning:: - The source qubit index is excluded from the list of its corresponding target qubit indexes. In other words, - qubit :math:`i` cannot be in the list `:math:D(i)` of qubits mapped to qubit :math:`i` itself. + The source qubit index is excluded from the list of its corresponding target qubit indexes. + In other words, qubit :math:`i` cannot be in the list `:math:D(i)` of qubits mapped to qubit + :math:`i` itself. - Furthermore, by default, if - the ``entangler_map`` parameter specifies that :math:`j \in D(i)`, where :math:`i,j \in \{0, 1, q-1\}, i \neq j`, then it cannot also specify - :math:`j \in D(i)`. A run-time error will be generated if double entanglement is configured. This - restriction can be lifted programmatically by setting the ``allow_double_entanglement`` boolean flag to ``True`` inside the - ``validate_entangler_map`` method in the ``entangler_map`` Application Programming Interface (API). + Furthermore, by default, if + the ``entangler_map`` parameter specifies that :math:`j \in D(i)`, where + :math:`i,j \in \{0, 1, q-1\}, i \neq j`, then it cannot also specify + :math:`j \in D(i)`. A run-time error will be generated if double entanglement is configured. + This + restriction can be lifted programmatically by setting the ``allow_double_entanglement`` + boolean flag to ``True`` inside the + ``validate_entangler_map`` method in the ``entangler_map`` Application Programming + Interface (API). .. warning:: When configured declaratively, Aqua and its domain specific applications - (:ref:`aqua-chemistry`, :ref:`aqua-ai`, :ref:`aqua-optimization` and :ref:`aqua-finance`) do not expose a configuration parameter in + (:ref:`aqua-chemistry`, :ref:`aqua-ai`, :ref:`aqua-optimization` and :ref:`aqua-finance`) + do not expose a configuration parameter in a ``VariationalForm`` object to set - the number of qubits that will be used in an experiment. This is because, when it is used as a tool to execute experiments, + the number of qubits that will be used in an experiment. This is because, when it is used as + a tool to execute experiments, Aqua is working at a higher, more abstract level. In such cases, the number of qubits - is computed internally at run time based on the particular experiment, and passed programmatically to + is computed internally at run time based on the particular experiment, and passed + programmatically to the ``init_args`` initialization method of the ``VariationalForm`` object. Manually configuring the entangler map, therefore, requires knowing the number of qubits :math:`q`, since the qubit indexes allowed - in the entangler map comfiguration can only take ``int`` values from :math:`0` to :math:`q-1`. Providing an entangler - map with indexes outside of this range will generate a run-time error. Therefore, caution should be used when + in the entangler map comfiguration can only take ``int`` values from :math:`0` to :math:`q-1`. + Providing an entangler + map with indexes outside of this range will generate a run-time error. Therefore, caution + should be used when manually configuring the entangler map. .. topic:: Declarative Name - When referring to Ry declaratively inside Aqua, its code ``name``, by which Aqua dynamically discovers and loads it, + When referring to Ry declaratively inside Aqua, its code ``name``, by which Aqua dynamically + discovers and loads it, is ``RY``. .. _ryrz: @@ -181,14 +198,18 @@ RyRz The RyRz trial wave function is layers of :math:`y` plus :math:`z` rotations with entanglements. The number of optimizer parameters this form -creates and uses is given by :math:`q \times (d + 1) \times 2`, where :math:`q` is the total number of qubits and :math:`d` is the depth of the circuit. -The parameters of RyRz can be configured after selecting ``RYRZ`` as the value of the ``name`` field in the -``variational_form`` section of the Aqua :ref:`input-file`. These parameters are ``depth``, ``entanglement``, and ``entangler_map`` --- the same +creates and uses is given by :math:`q \times (d + 1) \times 2`, where :math:`q` is the total +number of qubits and :math:`d` is the depth of the circuit. +The parameters of RyRz can be configured after selecting ``RYRZ`` as the value of the ``name`` +field in the +``variational_form`` section of the Aqua :ref:`input-file`. These parameters are ``depth``, +``entanglement``, and ``entangler_map`` --- the same as those of :ref:`Ry`. .. topic:: Declarative Name - When referring to RyRz declaratively inside Aqua, its code ``name``, by which Aqua dynamically discovers and loads it, + When referring to RyRz declaratively inside Aqua, its code ``name``, by which Aqua dynamically + discovers and loads it, is ``RYRZ``. .. _uccsd: @@ -214,26 +235,31 @@ more general experiments. be missing, or additional particles would be accounted for that were not there in the initial configuration. -In general, Unitary Coupled Cluster (UCC) preserves the number of particles across the computation and, consequently, +In general, Unitary Coupled Cluster (UCC) preserves the number of particles across the computation +and, consequently, the number of electrons. This is true, in particular, for UCCSD. Therefore, the initial state should be prepared with the desired number of electrons in the :ref:`hartree-fock` state. For a neutral molecule, the number of electrons equals the number of protons. -Note that the UCCSD implementation does not require the use of Trotter steps in the expansion of the +Note that the UCCSD implementation does not require the use of Trotter steps in the expansion of +the cluster operators. Assuming that :math:`T_1` and :math:`T_2` are the cluster operators for the single and double excitations, respectively, the Trotter expansion can be written as :math:`e^{(T_1-{T_1}^\dagger)+(T_2-{T_2}^\dagger)}`. -This amount can be approximated as :math:`\left(e^{\left(T_1-{T_1}^\dagger\right)/n}e^{\left(T_2-{T_2}^\dagger\right)/n}\right)^n`. +This amount can be approximated as +:math:`\left(e^{\left(T_1-{T_1}^\dagger\right)/n}e^{\left(T_2-{T_2}^\dagger\right)/n}\right)^n`. This approximation becomes exact in the limit :math:`n \rightarrow \infty`. -However, `it has been shown `__ that the variational approach gives good accuracy +However, `it has been shown `__ that the variational approach +gives good accuracy with just a single Trotter step. Rather than allowing single and double excitations with all particles and all unoccupied orbitals, the particles and unoccupied orbitals can be restricted to a so called *active space*. This allows -UCCSD to have a simpler form and correspondingly a shorter circuit. While simpler, this will result in an approximation +UCCSD to have a simpler form and correspondingly a shorter circuit. While simpler, this will result +in an approximation of the exact value. The acceptability of such approximation depends on the active space chosen. The following parameters allow a specific form to be configured: @@ -244,8 +270,10 @@ The following parameters allow a specific form to be configured: depth = 1 | 2 | ... - This parameter takes a positive ``int`` value, representing the depth of the circuit. The default value is ``1``. - Differently from the heuristic trial wave function approach, in UCCSD we do not need repetition of the circuit. + This parameter takes a positive ``int`` value, representing the depth of the circuit. + The default value is ``1``. + Differently from the heuristic trial wave function approach, in UCCSD we do not need repetition + of the circuit. - The total number of spin orbitals for which the variational form is to be created: @@ -254,7 +282,7 @@ The following parameters allow a specific form to be configured: num_orbitals = 1 | 2 | ... This parameter expects a positive ``int`` value. - + - The total number of particles for which the variational form is to be created: .. code:: python @@ -281,7 +309,7 @@ The following parameters allow a specific form to be configured: without loss of precision by setting the ``two_qubit_reduction`` parameter to ``True``, as explained next. 3. ``bravyi_kitaev`` corresponds to the :ref:`bravyi-kitaev` transformation, - also known as *binary-tree-based qubit mapping*. + also known as *binary-tree-based qubit mapping*. - A Boolean flag specifying whether or not to apply the precision-preserving two-qubit reduction optimization: @@ -306,7 +334,7 @@ The following parameters allow a specific form to be configured: num_time_slices = 0 | 1 | ... This parameter expects a non-negative ``int`` value. The default value is ``1``. - + - A list of occupied orbitals whose particles are to be used in the creation of single and double excitations: @@ -319,7 +347,7 @@ The following parameters allow a specific form to be configured: from the computation. Spin orbitals are as in the diagram below, where ``No`` and ``Nv`` indicate the number of active occupied alpha orbitals and active unoccupied virtual alpha orbitals, respectively. - + .. code:: alpha or up electrons beta or down electrons @@ -327,14 +355,14 @@ The following parameters allow a specific form to be configured: 0 1 No-1 No No+Nv-1 No+Nv 2(No+Nv)-1 \---------------------/\--------------------/ \--------------------/\---------------------/ occupied virtual occupied virtual - + 0---------------------n 0-------------------m active_occupied active_unoccupied - range range + range range The ``int`` values in the ``active_occupied`` list are orbital indices ranging from ``0`` to ``n``, where ``n = No - 1``. The user needs only to supply - the indexes of the active occupied alpha orbitals desired in the computation, + the indexes of the active occupied alpha orbitals desired in the computation, as the indexes of the active occupied beta orbitals can be computed. Indexes can be given with negative numbers too, in which case ``-1`` is the highest occupied orbital, ``-2`` the next one down, and so on. @@ -349,7 +377,7 @@ The following parameters allow a specific form to be configured: to `active_unoccupied` is ``None``, which corresponds to the configuration in which none of the unoccupied orbitals is excluded from the computation. Particles from the ``active_occupied`` list are only allowed to be excited into - orbitals defined by the ``active_unoccupied`` list. + orbitals defined by the ``active_unoccupied`` list. Assuming that ``Nv`` is the number of active unoccupied virtual alpha orbitals, the ``int`` values in the ``active_unoccupied`` list are orbital indices ranging from ``0`` to ``m``, where ``m = Nv - 1``. @@ -377,7 +405,7 @@ The following parameters allow a specific form to be configured: When the ``auto_substitutions`` flag in the ``problem`` section of the Aqua Chemistry :ref:`aqua-chemistry-input-file` - is set to ``True``, which is the default, the values of parameters + is set to ``True``, which is the default, the values of parameters ``num_particles`` and ``num_orbitals`` are automatically computed by Aqua Chemistry when ``UCCSD`` is selected as the value of the ``name`` parameter in the ``variational_forms`` section. As such, their configuration is disabled; the user will not be required, or even allowed, to assign values to @@ -412,7 +440,7 @@ The following parameters allow a specific form to be configured: When referring to UCCSD declaratively inside Aqua, its code ``name``, by which Aqua dynamically discovers and loads it, is ``UCCSD``. - + .. _swaprz: ------ @@ -428,14 +456,17 @@ It was designed principally to be a particle-preserving variational form for Particle preservation with SwapRz is not guaranteed unless SwapRz is used in conjunction with the :ref:`jordan-wigner` qubit mapping and the :ref:`hartree-fock` initial state. -The parameters of SwapRz can be configured after selecting ``SWAPRZ`` as the value of the ``name`` field in the +The parameters of SwapRz can be configured after selecting ``SWAPRZ`` as the value of the ``name`` +field in the ``variational_form`` section of the Aqua -:ref:`aqua-input file`. These parameters are ``depth``. ``entanglement``, and ``entangler_map`` --- the same +:ref:`aqua-input file`. These parameters are ``depth``. ``entanglement``, and ``entangler_map`` +--- the same as those of :ref:`Ry`. Based on the notation introduced above for the entangler map associated with a variational form, the number of optimizer parameters SwapRz creates and uses is given by -:math:`q + d \times \left(q + \sum_{k=0}^{q-1}|D(k)|\right)`, where :math:`|D(k)|` denotes the *cardinality* of +:math:`q + d \times \left(q + \sum_{k=0}^{q-1}|D(k)|\right)`, where :math:`|D(k)|` denotes the +*cardinality* of :math:`D(k)` or, more precisely, the *length* of :math:`D(k)` (since :math:`D(k)` is not just a set, but a list). diff --git a/docs/community.rst b/docs/community.rst index 9c06bfff3229..72f040aae364 100644 --- a/docs/community.rst +++ b/docs/community.rst @@ -1,26 +1,30 @@ Community Extensions ==================== -Qiskit has been designed with modularity in mind. It is extensible in many different ways and +Qiskit has been designed with modularity in mind. It is extensible in many different ways and it is important to us to highlight the community projects Backend Providers ----------------- -The Qiskit base provider is an entity that provides access to a group of different -backends (for example, backends available through IBM Q). It interacts with +The Qiskit base provider is an entity that provides access to a group of different +backends (for example, backends available through IBM Q). It interacts with those backends to do many things: find out which ones are available, retrieve an instance of a particular backend, get backend properties and configurations, -and handling running and working with jobs. +and handling running and working with jobs. Additional providers ~~~~~~~~~~~~~~~~~~~~ -Circuit Optimization +Circuit Optimization -------------------- -Circuit optimization is at the heart of making quantum computing. A central component of Qiskit is the transpiler, which is designed for modularity and extensibility. The goal is to be able to easily write new circuit transformations (known as transpiler passes) and combine them with other existing passes. In this way, the transpiler opens up the door for research into aggressive optimization of quantum circuits. +Circuit optimization is at the heart of making quantum computing. A central component of Qiskit is +the transpiler, which is designed for modularity and extensibility. The goal is to be able to +easily write new circuit transformations (known as transpiler passes) and combine them with other +existing passes. In this way, the transpiler opens up the door for research into aggressive +optimization of quantum circuits. Additional passes @@ -30,7 +34,8 @@ Additional passes Tools ----- -Extending Qiskit with new tools and functionality is an important part of building a community. These tools can be new visualizations, slack integration, Juypter extensions and much more. +Extending Qiskit with new tools and functionality is an important part of building a community. +These tools can be new visualizations, slack integration, Juypter extensions and much more. Additional Tools ~~~~~~~~~~~~~~~~ diff --git a/docs/components.rst b/docs/components.rst index cd3a1608abe4..aac66f062757 100644 --- a/docs/components.rst +++ b/docs/components.rst @@ -2,17 +2,17 @@ Component Status ================ Qiskit is developing so fast that is it is hard to keep all different parts -of the API supported for various versions. We do our best and we use +of the API supported for various versions. We do our best and we use the rule that for one minor version update, for example 0.6 to 0.7, we will keep the API working with a deprecated warning. Please don’t ignore these warnings. Sometimes there are cases in which this can’t be done and for these in the release history we will outline these in -great details. +great details. + +This being said as we work towards Qiskit 1.0 there are some modules +that have become stable and the table below is our attempt to label them -This being said as we work towards Qiskit 1.0 there are some modules -that have become stable and the table below is our attempt to label them - Modules ------- diff --git a/docs/contributing_to_qiskit.rst b/docs/contributing_to_qiskit.rst index 34d4b1b0ef37..fc5733c246a3 100644 --- a/docs/contributing_to_qiskit.rst +++ b/docs/contributing_to_qiskit.rst @@ -4,7 +4,8 @@ Contributing to Qiskit ====================== -Qiskit is an open-source project committed to bringing quantum computing to people of all backgrounds. This page describes how you can join the Qiskit community in this goal. +Qiskit is an open-source project committed to bringing quantum computing to people of all +backgrounds. This page describes how you can join the Qiskit community in this goal. diff --git a/docs/getting_started.rst b/docs/getting_started.rst index b32b1572100f..2822a9b75643 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -1,12 +1,15 @@ - - - -=========================== -======= +=============== Getting Started =============== -Here, we provide an overview of working with Qiskit. Qiskit provides the basic building blocks necessary to program quantum computers. The basic concept of Qiskit is an array of quantum circuits. A workflow using Qiskit consists of two stages: **Build** and **Execute**. **Build** allows you to make different quantum circuits that represent the problem you are solving, and **Execute** allows you to run them on different *backends*, a term meant to encompass both devices and simulation frameworks. After the jobs have been run, the data is collected. There are methods for putting this data together, depending on the program. This either gives you the answer you wanted, or allows you to make a better program for the next instance. +Here, we provide an overview of working with Qiskit. Qiskit provides the basic building blocks +necessary to program quantum computers. The basic concept of Qiskit is an array of quantum +circuits. A workflow using Qiskit consists of two stages: **Build** and **Execute**. **Build** +allows you to make different quantum circuits that represent the problem you are solving, and +**Execute** allows you to run them on different *backends*, a term meant to encompass both +devices and simulation frameworks. After the jobs have been run, the data is collected. There +are methods for putting this data together, depending on the program. This either gives you the +answer you wanted, or allows you to make a better program for the next instance. **Code imports** @@ -92,9 +95,10 @@ that gates which are applied earlier in the circuit show up further to the left). Simulating Circuits using Qiskit Aer -------------------------------------- +------------------------------------ -Qiskit Aer is our package for simulating quantum circuits. It provides many different backends for doing a simulation. Here we use the basic Python version. +Qiskit Aer is our package for simulating quantum circuits. It provides many +different backends for doing a simulation. Here we use the basic Python version. Statevector backend ~~~~~~~~~~~~~~~~~~~ @@ -359,7 +363,8 @@ the estimated probabilities change. Running Circuits on IBM Q Devices --------------------------------- -To follow along with this section, first be sure to set up an IBM Q account as explained in the :ref:`install_access_ibm_q_devices_label` section of the Qiskit installation instructions. +To follow along with this section, first be sure to set up an IBM Q account as explained in the +:ref:`install_access_ibm_q_devices_label` section of the Qiskit installation instructions. Load your IBM Q account credentials by calling @@ -389,9 +394,11 @@ Once your account has been loaded, you can view the list of devices available to Running circuits on real devices ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Today’s quantum information processors are small and noisy, but are advancing at a fast pace. They provide a great opportunity to explore what noisy quantum computers can do. +Today’s quantum information processors are small and noisy, but are advancing at a fast pace. +They provide a great opportunity to explore what noisy quantum computers can do. -The IBMQ provider uses a queue to allocate the devices to users. We now choose a device with the least busy queue which can support our program (has at least 3 qubits). +The IBMQ provider uses a queue to allocate the devices to users. We now choose a device with the +least busy queue which can support our program (has at least 3 qubits). .. code:: python diff --git a/docs/install.rst b/docs/install.rst index ff51c84f0dfd..bafc5929a560 100644 --- a/docs/install.rst +++ b/docs/install.rst @@ -1,8 +1,6 @@ Installing Qiskit ================= - - Requirements ------------ @@ -14,27 +12,33 @@ Qiskit is tested and supported on the following 64-bit systems: Qiskit supports Python 3.5 or later. -We recommend installing `Anaconda `_, a cross-platform Python distribution for scientific computing. Jupyter Notebook, included in Anaconda, is recommended for interacting with the `Qiskit tutorials `_. +We recommend installing `Anaconda `_, a cross-platform Python +distribution for scientific computing. Jupyter Notebook, included in Anaconda, is recommended for +interacting with the `Qiskit tutorials `_. Using Qiskit on Windows requires VC++ runtime components. We recommend one of the following: -* `Microsoft Visual C++ Redistributable for Visual Studio 2017 `_ -* `Microsoft Visual C++ Redistributable for Visual Studio 2015 `_ +* `Microsoft Visual C++ Redistributable for Visual Studio 2017 `_ +* `Microsoft Visual C++ Redistributable for Visual Studio 2015 `_ Install ------- -We recommend using Python virtual environments to cleanly separate Qiskit from other applications and improve your experience. +We recommend using Python virtual environments to cleanly separate Qiskit from other applications +and improve your experience. -The simplest way to use environments is by using the ``conda`` command, included with Anaconda. A Conda environment allows you to specify a specific version of Python and set of libraries. Run the following commands from a terminal window: +The simplest way to use environments is by using the ``conda`` command, included with Anaconda. A +Conda environment allows you to specify a specific version of Python and set of libraries. Run the +following commands from a terminal window: .. code:: sh conda create -n name_of_my_env python=3 -This will create a minimal environment with only Python installed in it. To put yourself inside this environment run: +This will create a minimal environment with only Python installed in it. To put yourself inside +this environment run: .. code:: sh @@ -52,38 +56,41 @@ The final step required is to install Qiskit with the following command: pip install qiskit qiskit-aqua -There are optional dependencies that are required to use all the visualization functions available in Qiskit. You can install Qiskit along with these optional dependencies by running +There are optional dependencies that are required to use all the visualization functions available +in Qiskit. You can install Qiskit along with these optional dependencies by running .. code:: sh pip install qiskit[visualization] qiskit-aqua - .. _install_install_from_source_label: Install from Source ------------------- -To get involved with the development of Qiskit, you can build any of the packages from source. See the contributing guide for each element of Qiskit for complete instructions: +To get involved with the development of Qiskit, you can build any of the packages from source. See +the contributing guide for each element of Qiskit for complete instructions: -* `Qiskit Terra `_ -* `Qiskit Aer `_ -* `Qiskit Aqua `_ -* `Qiskit Chemistry `_ +* `Qiskit Terra `_ +* `Qiskit Aer `_ +* `Qiskit Aqua `_ +* `Qiskit Chemistry `_ .. _install_access_ibm_q_devices_label: - Access IBM Q Devices -------------------- -IBM Q offers several real quantum computers and high-performance classical computing simulators through its `quantum cloud services `_ with Qiskit. +IBM Q offers several real quantum computers and high-performance classical computing simulators +through its `quantum cloud services `_ with +Qiskit. -`Create a free IBM Q account `_ to get an API token. +`Create a free IBM Q account `_ to get an API +token. After logging in, navigate to your account settings. @@ -93,7 +100,8 @@ Navigate to the Advanced tab and click the Generate button in the API Token sect .. image:: ./images/figures/install_api_token.png -Store your API token locally for later use in a configuration file called ``qiskitrc`` by running the following Python code: +Store your API token locally for later use in a configuration file called ``qiskitrc`` by running +the following Python code: .. code:: python @@ -106,11 +114,15 @@ where ``MY_API_TOKEN`` should be replaced with your token. IBM Q Network members must specify more than just an API token, as explained below. -If you are a member of the IBM Q Network, you must pass an additional argument to ``IBMQ.save_account()``. The ``url`` argument can be found on your q-console account page, along with any other additional information required, e.g. proxy information. Pass your API token and the ``url`` argument by running the following Python code: +If you are a member of the IBM Q Network, you must pass an additional argument to +``IBMQ.save_account()``. The ``url`` argument can be found on your q-console account page, along +with any other additional information required, e.g. proxy information. Pass your API token and the +``url`` argument by running the following Python code: .. code:: python from qiskit import IBMQ IBMQ.save_account('MY_API_TOKEN', url='https://...') -Refer to :ref:`advanced_use_of_ibm_q_devices_label` for more details, such as how to manage multiple IBM Q account credentials. +Refer to :ref:`advanced_use_of_ibm_q_devices_label` for more details, such as how to manage +multiple IBM Q account credentials. diff --git a/docs/license.rst b/docs/license.rst index 4719295daf06..9137b49ec341 100644 --- a/docs/license.rst +++ b/docs/license.rst @@ -2,4 +2,4 @@ License ======= This project uses the `Apache License Version 2.0 software -license `__. \ No newline at end of file +license `__. diff --git a/docs/overview.rst b/docs/overview.rst index 148a9336c97a..8fc403fbbeab 100644 --- a/docs/overview.rst +++ b/docs/overview.rst @@ -1,26 +1,26 @@ Overview ======== -Qiskit is an open-source framework for working with +Qiskit is an open-source framework for working with noisy quantum computers at the level of pulses, circuits, and algorithms. -Certainly, a central goal of Qiskit is to build a software stack -that makes it easy for anyone to use quantum computers. However, Qiskit also aims +Certainly, a central goal of Qiskit is to build a software stack +that makes it easy for anyone to use quantum computers. However, Qiskit also aims to facilitate research on the most important open issues facing quantum computation today. Qiskit allows the user to easily design experiments and run them on simulators and real -quantum computers. +quantum computers. -Qiskit consists of four foundational elements: Terra (the code foundation, -for composing quantum programs at the level of circuits and pulses), -Aqua (for building algorithms and applications), Ignis (for addressing noise +Qiskit consists of four foundational elements: Terra (the code foundation, +for composing quantum programs at the level of circuits and pulses), +Aqua (for building algorithms and applications), Ignis (for addressing noise and errors), and Aer (for accelerating development via simulators, emulators and debuggers). -Qiskit Elements ---------------- +Qiskit Elements +=============== .. image:: images/qiskit_elements.png @@ -28,49 +28,49 @@ Qiskit Elements Qiskit Terra ^^^^^^^^^^^^ -Terra , the ‘earth’ element, is the foundation on which the rest of Qiskit lies. -Terra provides a bedrock for composing quantum programs at the level of circuits and pulses, -to optimize them for the constraints of a particular device, and to manage the execution -of batches of experiments on remote-access devices. Terra defines the interfaces -for a desirable end-user experience, as well as the efficient handling of layers +Terra , the ‘earth’ element, is the foundation on which the rest of Qiskit lies. +Terra provides a bedrock for composing quantum programs at the level of circuits and pulses, +to optimize them for the constraints of a particular device, and to manage the execution +of batches of experiments on remote-access devices. Terra defines the interfaces +for a desirable end-user experience, as well as the efficient handling of layers of optimization, pulse scheduling and backend communication. Qiskit Aer ^^^^^^^^^^ -Aer, the ‘air’ element, permeates all Qiskit elements. To really speed up development +Aer, the ‘air’ element, permeates all Qiskit elements. To really speed up development of quantum computers we need better simulators, emulators and debuggers. Aer will help -us understand the limits of classical processors by demonstrating to what extent they -can mimic quantum computation. Furthermore, we can use Aer to verify that current -and near-future quantum computers function correctly. This can be done by stretching -the limits of simulation, and by simulating the effects of realistic noise on +us understand the limits of classical processors by demonstrating to what extent they +can mimic quantum computation. Furthermore, we can use Aer to verify that current +and near-future quantum computers function correctly. This can be done by stretching +the limits of simulation, and by simulating the effects of realistic noise on the computation. Qiskit Ignis ^^^^^^^^^^^^ -Ignis, the ‘fire’ element, is dedicated to fighting noise and errors and to forging -a new path. This includes better characterization of errors, improving gates, and computing -in the presence of noise. Ignis is meant for those who want to design quantum error -correction codes, or who wish to study ways to characterize errors through methods -such as tomography, or even to find a better way for using gates by exploring -dynamical decoupling and optimal control. +Ignis, the ‘fire’ element, is dedicated to fighting noise and errors and to forging +a new path. This includes better characterization of errors, improving gates, and computing +in the presence of noise. Ignis is meant for those who want to design quantum error +correction codes, or who wish to study ways to characterize errors through methods +such as tomography, or even to find a better way for using gates by exploring +dynamical decoupling and optimal control. Qiskit Aqua ^^^^^^^^^^^ -Aqua, the ‘water’ element, is the element of life. To make quantum computing live up -to its expectations, we need to find real-world applications. Aqua is where algorithms -for NISQ computers are built. These algorithms can be used to build applications -for quantum computing. Aqua is accessible to domain experts in chemistry, optimization -or AI, who want to explore the benefits of using quantum computers as accelerators -for specific computational tasks, without needing to worry about how to translate +Aqua, the ‘water’ element, is the element of life. To make quantum computing live up +to its expectations, we need to find real-world applications. Aqua is where algorithms +for NISQ computers are built. These algorithms can be used to build applications +for quantum computing. Aqua is accessible to domain experts in chemistry, optimization +or AI, who want to explore the benefits of using quantum computers as accelerators +for specific computational tasks, without needing to worry about how to translate the problem into the language of quantum machines. -Qiskit Components +Qiskit Components ----------------- -The components of Qiskit extend the functionality. +The components of Qiskit extend the functionality. Qiskit Chemistry ^^^^^^^^^^^^^^^^ diff --git a/docs/release_history.rst b/docs/release_history.rst index 2338e9adc86f..aa8e3403932a 100644 --- a/docs/release_history.rst +++ b/docs/release_history.rst @@ -292,16 +292,22 @@ New Features Aer provides three simulator backends: * ``QasmSimulator``: simulate experiments and return measurement outcomes. - * ``StatevectorSimulator``: return the final statevector for a quantum circuit acting on the all zero state + * ``StatevectorSimulator``: return the final statevector for a quantum circuit acting on the all + zero state * ``UnitarySimulator``: return the unitary matrix for a quantum circuit ``noise`` module: contains advanced noise modeling features for the ``QasmSimulator`` - * ``NoiseModel``, ``QuantumError``, ``ReadoutError`` classes for simulating a Qiskit quantum circuit in the presence of errors - * ``errors`` submodule including functions for generating ``QuantumError`` objects for the following types of quantum errors: Kraus, mixed unitary, coherent unitary, Pauli, depolarizing, thermal relaxation, amplitude damping, phase damping, combined phase and amplitude damping. - * ``device`` submodule for automatically generating a noise model based on the ``BackendProperties`` of a device + * ``NoiseModel``, ``QuantumError``, ``ReadoutError`` classes for simulating a Qiskit quantum + circuit in the presence of errors + * ``errors`` submodule including functions for generating ``QuantumError`` objects for the + following types of quantum errors: Kraus, mixed unitary, coherent unitary, Pauli, depolarizing, + thermal relaxation, amplitude damping, phase damping, combined phase and amplitude damping. + * ``device`` submodule for automatically generating a noise model based on the + ``BackendProperties`` of a device ``utils`` module: - * ``qobj_utils`` provides functions for directly modifying a ``qobj`` to insert special simulator instructions not yet supported through the Qiskit Terra API + * ``qobj_utils`` provides functions for directly modifying a ``qobj`` to insert special simulator + instructions not yet supported through the Qiskit Terra API Qiskit 0.6 diff --git a/docs/roadmap.rst b/docs/roadmap.rst index 4ff2b56e72dc..7e27c25b4ae4 100644 --- a/docs/roadmap.rst +++ b/docs/roadmap.rst @@ -49,9 +49,9 @@ In 2019, Aer will be extended in many ways: that are more efficient for specific subclasses of circuits, such as the T-gate simulator, which works on Clifford and T gates (with low T-depth), and a stabilizer simulator, which works just on Clifford gates. -- **Add noise approximation tools.** We plan to add noise approximation tools to mapping general (Kraus) - noise models to approximate noise model that may be implemented on an approximate backends - (for example only mixed Clifford and reset errors in the noise model). +- **Add noise approximation tools.** We plan to add noise approximation tools to mapping general + (Kraus) noise models to approximate noise model that may be implemented on an approximate + backends (for example only mixed Clifford and reset errors in the noise model). Qiskit Ignis ------------ @@ -87,8 +87,8 @@ Quantum Kernel and Variational algorithms, suitable for supervised learning. In Aqua includes algorithm-supporting components, such as optimizers, variational forms, oracles, Quantum Fourier Transforms, feature maps, multiclass classification extension algorithms, uncertainty problems, and random distributions. -As a framework for quantum applications, Aqua provides support for Chemistry (released separately as the -Qiskit Chemistry component), as well as Artificial Intelligence (AI), Optimization and +As a framework for quantum applications, Aqua provides support for Chemistry (released separately +as the Qiskit Chemistry component), as well as Artificial Intelligence (AI), Optimization and Finance. Aqua is extensible across multiple domains, and has been designed and structured as a framework that allows researchers to contribute their own implementations of new algorithms and algorithm-supporting components. diff --git a/docs/terra/overview.rst b/docs/terra/overview.rst index 2d46b26bd2aa..b6fcdca70df3 100644 --- a/docs/terra/overview.rst +++ b/docs/terra/overview.rst @@ -13,7 +13,8 @@ Terra Organization ------------------ Python example programs can be found in the *examples* directory, and test scripts are -located in *test*. The *qiskit* directory is the main module of Terra. This moudule has six main parts. +located in *test*. The *qiskit* directory is the main module of Terra. This +module has six main parts. Quantum Circuits @@ -21,11 +22,11 @@ Quantum Circuits A quantum circuit is a model for quantum computing in which a computation is done by performing a sequence of quantum operations (usually gates) on a register of qubits. A quantum circuit usually -starts with the qubits in the :math:`|0,…,0>` state (Terra assumes this unless otherwise specified) and -these gates evolve the qubits to states that cannot be efficiently represented on a classical computer. -To extract information on the state a quantum circuit must have a measurement which maps the outcomes -(possible random due to the fundamental nature of quantum systems) to classical registers which -can be efficiently represented. +starts with the qubits in the :math:`|0,…,0>` state (Terra assumes this unless otherwise +specified) and these gates evolve the qubits to states that cannot be efficiently represented on a +classical computer. To extract information on the state a quantum circuit must have a measurement +which maps the outcomes (possible random due to the fundamental nature of quantum systems) to +classical registers which can be efficiently represented. Transpiler @@ -84,17 +85,18 @@ Quantum Information ^^^^^^^^^^^^^^^^^^^ To perform more advance algorithms and analysis of the circuits run on the quantum computer it is -important to have tools to perform simple quantum information tasks. These include methods to estimate -metrics on and generate quantum states, operations, and channels. +important to have tools to perform simple quantum information tasks. These include methods to +estimate metrics on and generate quantum states, operations, and channels. Visualization Tools ^^^^^^^^^^^^^^^^^^^ -In Terra we have many tools to visualize a quantum circuit. This allows a quick inspection of the quantum -circuit to make sure it is what the user wanted to implement. There is a text, python and latex version. -Once the circuit has run it is important to be able to view the output. There is a simple function -(`plot_histogram`) to plot the results from a quantum circuit including an interactive version. -There is also a function `plot_state` and ` plot_bloch_vector` that allow the plotting of a -quantum state. These functions are usually only used when using the `statevector_simulator` -backend but can also be used on real data after running state tomography experiments (ignis). +In Terra we have many tools to visualize a quantum circuit. This allows a quick inspection of the +quantum circuit to make sure it is what the user wanted to implement. There is a text, python and +latex version. Once the circuit has run it is important to be able to view the output. There is a +simple function (`plot_histogram`) to plot the results from a quantum circuit including an +interactive version. There is also a function `plot_state` and ` plot_bloch_vector` that allow +the plotting of a quantum state. These functions are usually only used when using the +`statevector_simulator` backend but can also be used on real data after running state tomography +experiments (ignis). diff --git a/docs/terra/plotting_data_in_qiskit.rst b/docs/terra/plotting_data_in_qiskit.rst index 916b6f30c000..63a2ad682e7d 100644 --- a/docs/terra/plotting_data_in_qiskit.rst +++ b/docs/terra/plotting_data_in_qiskit.rst @@ -30,16 +30,16 @@ As an example we make a 2 qubit Bell state q = QuantumRegister(2) c = ClassicalRegister(2) - - # quantum circuit to make a Bell state + + # quantum circuit to make a Bell state bell = QuantumCircuit(q,c) bell.h(q[0]) bell.cx(q[0],q[1]) - + meas = QuantumCircuit(q,c) meas.measure(q, c) - - # execute the quantum circuit + + # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell+meas result = execute(circ, backend, shots=1000).result() @@ -148,18 +148,18 @@ notebook it will fail. .. raw:: html - +

- + - + Plot State @@ -220,7 +220,7 @@ statevectors) .. code:: python - # execute the quantum circuit + # execute the quantum circuit backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = execute(bell, backend).result() psi = result.get_statevector(bell) @@ -410,18 +410,18 @@ outside of a jupyter notebook it will fail. .. raw:: html - +

- + - + Plot Bloch Vector diff --git a/docs/terra/quantum_circuits.rst b/docs/terra/quantum_circuits.rst index 0daca33502fb..6a89a8471cd4 100644 --- a/docs/terra/quantum_circuits.rst +++ b/docs/terra/quantum_circuits.rst @@ -13,7 +13,7 @@ they want with these objects. import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import BasicAer, execute - from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity + from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity Quantum and Classical Registers ------------------------------- @@ -103,13 +103,13 @@ using the ``add_register`` command. .. raw:: html -
                   
+    
     q0_0: |0>──────────
                   ┌───┐
     q0_1: |0>─────┤ X ├
              ┌───┐└───┘
     q1_0: |0>┤ X ├─────
-             └───┘     
+             └───┘
     q1_1: |0>──────────
                        
@@ -131,13 +131,13 @@ is the same as .. raw:: html -
                   
+    
     q0_0: |0>──────────
                   ┌───┐
     q0_1: |0>─────┤ X ├
              ┌───┐└───┘
     q1_0: |0>┤ X ├─────
-             └───┘     
+             └───┘
     q1_1: |0>──────────
                        
@@ -157,7 +157,7 @@ or added (**not** the tensor product for quantum registers). .. code:: python from copy import deepcopy - + q3 = QuantumRegister(2, 'q3') circ3 = deepcopy(circ) circ3.add_register(q3) @@ -168,17 +168,17 @@ or added (**not** the tensor product for quantum registers). .. raw:: html -
                   
+    
     q0_0: |0>──────────
                   ┌───┐
     q0_1: |0>─────┤ X ├
              ┌───┐└───┘
     q1_0: |0>┤ X ├─────
-             └───┘     
+             └───┘
     q1_1: |0>──────────
-                       
+
     q3_0: |0>──────────
-                       
+
     q3_1: |0>──────────
                        
@@ -208,9 +208,9 @@ measurement. meas = QuantumCircuit(q0, q1, c0, c1) meas.measure(q0, c0) meas.measure(q1, c1) - + qc = circ + meas - + qc.draw() @@ -222,17 +222,17 @@ measurement. q0_0: |0>───────────────────┤M├ ┌───┐┌─┐└╥┘ q0_1: |0>───────────┤ X ├┤M├─╫─ - ┌───┐┌─┐└───┘└╥┘ ║ + ┌───┐┌─┐└───┘└╥┘ ║ q1_0: |0>───┤ X ├┤M├──────╫──╫─ - ┌─┐└───┘└╥┘ ║ ║ + ┌─┐└───┘└╥┘ ║ ║ q1_1: |0>┤M├──────╫───────╫──╫─ - └╥┘ ║ ║ ║ + └╥┘ ║ ║ ║ c0_0: 0 ═╬═══════╬═══════╬══╩═ - ║ ║ ║ + ║ ║ ║ c0_1: 0 ═╬═══════╬═══════╩════ - ║ ║ + ║ ║ c1_0: 0 ═╬═══════╩════════════ - ║ + ║ c1_1: 0 ═╩════════════════════
@@ -247,9 +247,9 @@ measurement. meas2.add_register(c1) meas2.measure(q0, c0) meas2.measure(q1, c1) - + qc2 = circ2 + meas2 - + qc2.draw() @@ -261,17 +261,17 @@ measurement. q0_0: |0>───────────────────┤M├ ┌───┐┌─┐└╥┘ q0_1: |0>───────────┤ X ├┤M├─╫─ - ┌───┐┌─┐└───┘└╥┘ ║ + ┌───┐┌─┐└───┘└╥┘ ║ q1_0: |0>───┤ X ├┤M├──────╫──╫─ - ┌─┐└───┘└╥┘ ║ ║ + ┌─┐└───┘└╥┘ ║ ║ q1_1: |0>┤M├──────╫───────╫──╫─ - └╥┘ ║ ║ ║ + └╥┘ ║ ║ ║ c0_0: 0 ═╬═══════╬═══════╬══╩═ - ║ ║ ║ + ║ ║ ║ c0_1: 0 ═╬═══════╬═══════╩════ - ║ ║ + ║ ║ c1_0: 0 ═╬═══════╩════════════ - ║ + ║ c1_1: 0 ═╩════════════════════
@@ -333,9 +333,9 @@ The new register is added to the circuit: q1_0: |0>───────────────┤ X ├ ┌───┐└───┘ q1_1: |0>──────────┤ X ├───── - ┌───┐└───┘ + ┌───┐└───┘ q3_0: |0>─────┤ H ├────────── - ┌───┐└───┘ + ┌───┐└───┘ q3_1: |0>┤ H ├─────────────── └───┘
@@ -357,9 +357,9 @@ We have also overloaded ``+=`` to the ``QuantumCircuit`` object: q1_0: |0>───────────────┤ X ├ ┌───┐└───┘ q1_1: |0>──────────┤ X ├───── - ┌───┐└───┘ + ┌───┐└───┘ q3_0: |0>─────┤ H ├────────── - ┌───┐└───┘ + ┌───┐└───┘ q3_1: |0>┤ H ├─────────────── └───┘ @@ -381,13 +381,13 @@ regular computer science little endian ordering). In this example: .. raw:: html -
                   
+    
     q0_0: |0>──────────
                   ┌───┐
     q0_1: |0>─────┤ X ├
              ┌───┐└───┘
     q1_0: |0>┤ X ├─────
-             └───┘     
+             └───┘
     q1_1: |0>──────────
                        
@@ -480,17 +480,17 @@ have to use the example with measurements ``qc``: q0_0: |0>───────────────────┤M├ ┌───┐┌─┐└╥┘ q0_1: |0>───────────┤ X ├┤M├─╫─ - ┌───┐┌─┐└───┘└╥┘ ║ + ┌───┐┌─┐└───┘└╥┘ ║ q1_0: |0>───┤ X ├┤M├──────╫──╫─ - ┌─┐└───┘└╥┘ ║ ║ + ┌─┐└───┘└╥┘ ║ ║ q1_1: |0>┤M├──────╫───────╫──╫─ - └╥┘ ║ ║ ║ + └╥┘ ║ ║ ║ c0_0: 0 ═╬═══════╬═══════╬══╩═ - ║ ║ ║ + ║ ║ ║ c0_1: 0 ═╬═══════╬═══════╩════ - ║ ║ + ║ ║ c1_0: 0 ═╬═══════╩════════════ - ║ + ║ c1_1: 0 ═╩════════════════════
@@ -521,11 +521,11 @@ same as above on the second example circuit: backend_sim = BasicAer.get_backend('statevector_simulator') result = execute(circ2, backend_sim).result() states = result.get_statevector(circ2) - + backend_sim = BasicAer.get_backend('qasm_simulator') result = execute(qc2, backend_sim).result() counts = result.get_counts(qc2) - + backend_sim = BasicAer.get_backend('unitary_simulator') result = execute(circ2, backend_sim).result() unitary = result.get_unitary(circ2) @@ -590,17 +590,17 @@ things. .. raw:: html -
                   ┌───┐               ┌───┐                    
+    
                   ┌───┐               ┌───┐
     q0_0: |0>──────────┤ H ├──■────────────┤ X ├────────────────────
                        └───┘  │            └───┘               ┌───┐
     q0_1: |0>─────────────────■───────────────────■────────────┤ X ├
                             ┌─┴─┐┌───┐┌───┐       │            └───┘
     q0_2: |0>───────────────┤ X ├┤ X ├┤ H ├───────┼─────────────────
-                            └───┘└───┘└───┘     ┌─┴─┐┌───┐┌───┐     
+                            └───┘└───┘└───┘     ┌─┴─┐┌───┐┌───┐
     q0_3: |0>───────────────────────────────────┤ X ├┤ X ├┤ H ├─────
-                  ┌───┐                         └───┘└───┘└───┘     
+                  ┌───┐                         └───┘└───┘└───┘
     q0_4: |0>─────┤ X ├─────────────────────────────────────────────
-             ┌───┐└───┘                                             
+             ┌───┐└───┘
     q0_5: |0>┤ X ├──────────────────────────────────────────────────
              └───┘                                                  
diff --git a/docs/terra/summary_of_quantum_operations.rst b/docs/terra/summary_of_quantum_operations.rst index d121a0988955..49e48052460f 100644 --- a/docs/terra/summary_of_quantum_operations.rst +++ b/docs/terra/summary_of_quantum_operations.rst @@ -14,7 +14,7 @@ unitary_simulator - qasm_simulator - statevector_simulator .. code:: python - # Useful additional packages + # Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np @@ -26,7 +26,7 @@ unitary_simulator - qasm_simulator - statevector_simulator from qiskit.tools.visualization import circuit_drawer from qiskit.quantum_info import state_fidelity from qiskit import BasicAer - + backend = BasicAer.get_backend('unitary_simulator') Single Qubit Quantum states @@ -44,7 +44,7 @@ vector this is .. math:: - |\psi\rangle = + |\psi\rangle = \begin{pmatrix} \alpha \\ \beta @@ -81,7 +81,7 @@ above state. That is U = \begin{pmatrix} \cos(\theta/2) & a \\ - e^{i\phi}\sin(\theta/2) & b + e^{i\phi}\sin(\theta/2) & b \end{pmatrix} where :math:`a` and :math:`b` are complex numbers constrained such that @@ -96,7 +96,7 @@ where :math:`a` and :math:`b` are complex numbers constrained such that U = \begin{pmatrix} \cos(\theta/2) & -e^{i\lambda}\sin(\theta/2) \\ - e^{i\phi}\sin(\theta/2) & e^{i\lambda+i\phi}\cos(\theta/2) + e^{i\phi}\sin(\theta/2) & e^{i\lambda+i\phi}\cos(\theta/2) \end{pmatrix}. This is the most general form of a single qubit unitary. @@ -123,7 +123,7 @@ gate .. math:: - u3(\theta, \phi, \lambda) = U(\theta, \phi, \lambda) + u3(\theta, \phi, \lambda) = U(\theta, \phi, \lambda) .. code:: python @@ -163,7 +163,7 @@ form .. math:: - u2(\phi, \lambda) = + u2(\phi, \lambda) = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & -e^{i\lambda} \\ e^{i\phi} & e^{i(\phi + \lambda)} @@ -208,7 +208,7 @@ The :math:`u1(\lambda)= u3(0, 0, \lambda)` gate has the matrix form .. math:: - u1(\lambda) = + u1(\lambda) = \begin{pmatrix} 1 & 0 \\ 0 & e^{i \lambda} @@ -254,7 +254,7 @@ the matrix form .. math:: - u0(\delta) = + u0(\delta) = \begin{pmatrix} 1 & 0 \\ 0 & 1 @@ -343,7 +343,7 @@ The bit-flip gate :math:`X` is defined as: .. math:: - X = + X = \begin{pmatrix} 0 & 1\\ 1 & 0 @@ -389,7 +389,7 @@ The :math:`Y` gate is defined as: .. math:: - Y = + Y = \begin{pmatrix} 0 & -i\\ i & 0 @@ -435,7 +435,7 @@ The phase flip gate :math:`Z` is defined as: .. math:: - Z = + Z = \begin{pmatrix} 1 & 0\\ 0 & -1 @@ -482,7 +482,7 @@ Hadamard gate .. math:: - H = + H = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1\\ @@ -527,7 +527,7 @@ Hadamard gate .. math:: - S = + S = \begin{pmatrix} 1 & 0\\ 0 & i @@ -571,7 +571,7 @@ Hadamard gate .. math:: - S^{\dagger} = + S^{\dagger} = \begin{pmatrix} 1 & 0\\ 0 & -i @@ -618,11 +618,11 @@ Hadamard gate .. math:: - T = + T = \begin{pmatrix} 1 & 0\\ 0 & e^{i \pi/4} - \end{pmatrix}= u1(\pi/4) + \end{pmatrix}= u1(\pi/4) .. code:: python @@ -662,7 +662,7 @@ Hadamard gate .. math:: - T^{\dagger} = + T^{\dagger} = \begin{pmatrix} 1 & 0\\ 0 & e^{-i \pi/4} @@ -716,7 +716,7 @@ Rotation around X-axis .. math:: - R_x(\theta) = + R_x(\theta) = \begin{pmatrix} \cos(\theta/2) & -i\sin(\theta/2)\\ -i\sin(\theta/2) & \cos(\theta/2) @@ -804,7 +804,7 @@ Rotation around Z-axis .. math:: - R_z(\phi) = + R_z(\phi) = \begin{pmatrix} e^{-i \phi/2} & 0 \\ 0 & e^{i \phi/2} @@ -865,23 +865,23 @@ Let’s start by considering a 2-qubit system. Given two operators .. math:: \begin{equation} - A\otimes B = - \begin{pmatrix} - A_{00} \begin{pmatrix} + A\otimes B = + \begin{pmatrix} + A_{00} \begin{pmatrix} B_{00} & B_{01} \\ B_{10} & B_{11} - \end{pmatrix} & A_{01} \begin{pmatrix} + \end{pmatrix} & A_{01} \begin{pmatrix} B_{00} & B_{01} \\ B_{10} & B_{11} \end{pmatrix} \\ - A_{10} \begin{pmatrix} + A_{10} \begin{pmatrix} B_{00} & B_{01} \\ B_{10} & B_{11} - \end{pmatrix} & A_{11} \begin{pmatrix} + \end{pmatrix} & A_{11} \begin{pmatrix} B_{00} & B_{01} \\ B_{10} & B_{11} \end{pmatrix} - \end{pmatrix}, + \end{pmatrix}, \end{equation} where :math:`A_{jk}` and :math:`B_{lm}` are the matrix elements of @@ -893,46 +893,46 @@ the tensor product of basis vectors for a single qubit: .. math:: \begin{equation}\begin{split} - |{00}\rangle &= \begin{pmatrix} - 1 \begin{pmatrix} + |{00}\rangle &= \begin{pmatrix} + 1 \begin{pmatrix} 1 \\ 0 \end{pmatrix} \\ - 0 \begin{pmatrix} + 0 \begin{pmatrix} 1 \\ - 0 + 0 \end{pmatrix} - \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \\ 0 \\0 \end{pmatrix}~~~|{01}\rangle = \begin{pmatrix} - 1 \begin{pmatrix} + \end{pmatrix} = \begin{pmatrix} 1 \\ 0 \\ 0 \\0 \end{pmatrix}~~~|{01}\rangle = \begin{pmatrix} + 1 \begin{pmatrix} 0 \\ 1 \end{pmatrix} \\ - 0 \begin{pmatrix} + 0 \begin{pmatrix} 0 \\ - 1 + 1 \end{pmatrix} \end{pmatrix} = \begin{pmatrix}0 \\ 1 \\ 0 \\ 0 \end{pmatrix}\end{split} \end{equation} .. math:: - \begin{equation}\begin{split}|{10}\rangle = \begin{pmatrix} - 0\begin{pmatrix} + \begin{equation}\begin{split}|{10}\rangle = \begin{pmatrix} + 0\begin{pmatrix} 1 \\ 0 \end{pmatrix} \\ - 1\begin{pmatrix} + 1\begin{pmatrix} 1 \\ - 0 + 0 \end{pmatrix} - \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ 1 \\ 0 \end{pmatrix}~~~ |{11}\rangle = \begin{pmatrix} - 0 \begin{pmatrix} + \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ 1 \\ 0 \end{pmatrix}~~~ |{11}\rangle = \begin{pmatrix} + 0 \begin{pmatrix} 0 \\ 1 \end{pmatrix} \\ - 1\begin{pmatrix} + 1\begin{pmatrix} 0 \\ - 1 + 1 \end{pmatrix} \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ 0 \\1 \end{pmatrix}\end{split} \end{equation}. @@ -1079,13 +1079,13 @@ control qubit (e.g. ``cx(q[1],q[0])``), then the matrix would look like .. math:: - C_X = + C_X = \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & 1 & 0 - \end{pmatrix}. + \end{pmatrix}. However, when the LSB is the control qubit, (e.g. ``cx(q[0],q[1])``), this gate is equivalent to the following matrix: @@ -1093,13 +1093,13 @@ this gate is equivalent to the following matrix: .. math:: - C_X = + C_X = \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & 1 & 0\\ 0 & 1 & 0 & 0 - \end{pmatrix}. + \end{pmatrix}. .. code:: python @@ -1112,7 +1112,7 @@ this gate is equivalent to the following matrix: .. raw:: html -
              
+    
     q1_0: |0>──■──
              ┌─┴─┐
     q1_1: |0>┤ X ├
@@ -1146,7 +1146,7 @@ MSB
 .. math::
 
 
-   C_Y = 
+   C_Y =
    \begin{pmatrix}
    1 & 0 & 0 & 0\\
    0 & 1 & 0 & 0\\
@@ -1159,7 +1159,7 @@ or when the LSB is the control
 .. math::
 
 
-   C_Y = 
+   C_Y =
    \begin{pmatrix}
    1 & 0 & 0 & 0\\
    0 & 0 & 0 & -i\\
@@ -1178,7 +1178,7 @@ or when the LSB is the control
 
 .. raw:: html
 
-    
              
+    
     q1_0: |0>──■──
              ┌─┴─┐
     q1_1: |0>┤ Y ├
@@ -1213,7 +1213,7 @@ whether the MSB or LSB is the control qubit:
 .. math::
 
 
-   C_Z = 
+   C_Z =
    \begin{pmatrix}
    1 & 0 & 0 & 0\\
    0 & 1 & 0 & 0\\
@@ -1232,9 +1232,9 @@ whether the MSB or LSB is the control qubit:
 
 .. raw:: html
 
-    
            
+    
     q1_0: |0>─■─
-              │ 
+              │
     q1_1: |0>─■─
                 
@@ -1266,7 +1266,7 @@ Apply :math:`H` gate to the target qubit if the control qubit is .. math:: - C_H = + C_H = \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & \frac{1}{\sqrt{2}} & 0 & \frac{1}{\sqrt{2}}\\ @@ -1285,7 +1285,7 @@ Apply :math:`H` gate to the target qubit if the control qubit is .. raw:: html -
              
+    
     q1_0: |0>──■──
              ┌─┴─┐
     q1_1: |0>┤ H ├
@@ -1322,7 +1322,7 @@ Perform rotation around Z-axis on the target qubit if the control qubit
 .. math::
 
 
-   C_{Rz}(\lambda) = 
+   C_{Rz}(\lambda) =
    \begin{pmatrix}
    1 & 0 & 0 & 0\\
    0 & e^{-i\lambda/2} & 0 & 0\\
@@ -1341,7 +1341,7 @@ Perform rotation around Z-axis on the target qubit if the control qubit
 
 .. raw:: html
 
-    
                       
+    
     q1_0: |0>──────■───────
              ┌─────┴──────┐
     q1_1: |0>┤ Rz(1.5708) ├
@@ -1376,7 +1376,7 @@ the control qubit.
 .. math::
 
 
-   C_{u1}(\lambda) = 
+   C_{u1}(\lambda) =
    \begin{pmatrix}
    1 & 0 & 0 & 0\\
    0 & 1 & 0 & 0\\
@@ -1395,9 +1395,9 @@ the control qubit.
 
 .. raw:: html
 
-    
                  
+    
     q1_0: |0>─■───────
-              │1.5708 
+              │1.5708
     q1_1: |0>─■───────
                       
@@ -1429,7 +1429,7 @@ control qubit (here LSB) is :math:`|1\rangle`. .. math:: - C_{u3}(\theta, \phi, \lambda) \equiv + C_{u3}(\theta, \phi, \lambda) \equiv \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & e^{-i(\phi+\lambda)/2}\cos(\theta/2) & 0 & -e^{-i(\phi-\lambda)/2}\sin(\theta/2)\\ @@ -1448,7 +1448,7 @@ control qubit (here LSB) is :math:`|1\rangle`. .. raw:: html -
                                     
+    
     q1_0: |0>─────────────■──────────────
              ┌────────────┴─────────────┐
     q1_1: |0>┤ U3(1.5708,1.5708,1.5708) ├
@@ -1486,7 +1486,7 @@ which gives a matrix representation of the form
 .. math::
 
 
-   \mathrm{SWAP} = 
+   \mathrm{SWAP} =
    \begin{pmatrix}
    1 & 0 & 0 & 0\\
    0 & 0 & 1 & 0\\
@@ -1505,9 +1505,9 @@ which gives a matrix representation of the form
 
 .. raw:: html
 
-    
            
+    
     q1_0: |0>─X─
-              │ 
+              │
     q1_1: |0>─X─
                 
@@ -1560,7 +1560,7 @@ In matrix form, the Toffoli gate is .. math:: - C_{CX} = + C_{CX} = \begin{pmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\ @@ -1587,9 +1587,9 @@ In matrix form, the Toffoli gate is .. raw:: html -
              
+    
     q2_0: |0>──■──
-               │  
+               │
     q2_1: |0>──■──
              ┌─┴─┐
     q2_2: |0>┤ X ├
@@ -1633,7 +1633,7 @@ In matrix form, the Fredkin gate is
 .. math::
 
 
-   C_{\mathrm{SWAP}} = 
+   C_{\mathrm{SWAP}} =
    \begin{pmatrix}
    1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
    0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
@@ -1656,11 +1656,11 @@ In matrix form, the Fredkin gate is
 
 .. raw:: html
 
-    
            
+    
     q2_0: |0>─■─
-              │ 
+              │
     q2_1: |0>─X─
-              │ 
+              │
     q2_2: |0>─X─
                 
@@ -1966,12 +1966,12 @@ arbitrary state for :math:`n` qubits may be specified by a vector of 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0] - - + + q = QuantumRegister(3) - + qc = QuantumCircuit(q) - + qc.initialize(desired_vector, [q[0],q[1],q[2]]) @@ -1988,7 +1988,7 @@ arbitrary state for :math:`n` qubits may be specified by a vector of backend = BasicAer.get_backend('statevector_simulator') job = execute(qc, backend) qc_state = job.result().get_statevector(qc) - qc_state + qc_state @@ -2067,13 +2067,13 @@ amounts to the following unitary, which disentangles the LSB: .. math:: - U = \begin{pmatrix} - R_{y}(-\theta_0)R_{z}(-\phi_0) & & & &\\ + U = \begin{pmatrix} + R_{y}(-\theta_0)R_{z}(-\phi_0) & & & &\\ & R_{y}(-\theta_1)R_{z}(-\phi_1) & & &\\ & . & & &\\ & & . & &\\ & & & & R_y(-\theta_{2^{n-1}-1})R_z(-\phi_{2^{n-1}-1}) - \end{pmatrix} + \end{pmatrix} Hence, diff --git a/docs/terra/visualizing_a_quantum_circuit.rst b/docs/terra/visualizing_a_quantum_circuit.rst index e364dbe3eba6..d14746e36329 100644 --- a/docs/terra/visualizing_a_quantum_circuit.rst +++ b/docs/terra/visualizing_a_quantum_circuit.rst @@ -21,13 +21,13 @@ diagram. .. code:: python # Build a quantum circuit - - n = 3 # number of qubits + + n = 3 # number of qubits q = QuantumRegister(n) c = ClassicalRegister(n) - + circuit = QuantumCircuit(q, c) - + circuit.x(q[1]) circuit.h(q) circuit.cx(q[0], q[1]) @@ -46,13 +46,13 @@ diagram. q0_0: |0>──────────────────┤ H ├──■─────┤M├ ┌───┐┌───┐└───┘┌─┴─┐┌─┐└╥┘ q0_1: |0>────────┤ X ├┤ H ├─────┤ X ├┤M├─╫─ - ┌───┐┌─┐└───┘└───┘ └───┘└╥┘ ║ + ┌───┐┌─┐└───┘└───┘ └───┘└╥┘ ║ q0_2: |0>┤ H ├┤M├─────────────────────╫──╫─ - └───┘└╥┘ ║ ║ + └───┘└╥┘ ║ ║ c0_0: 0 ══════╬══════════════════════╬══╩═ - ║ ║ + ║ ║ c0_1: 0 ══════╬══════════════════════╩════ - ║ + ║ c0_2: 0 ══════╩═══════════════════════════
@@ -71,13 +71,13 @@ diagram. q0_0: |0>──────────────────┤ H ├──■─────┤M├ ┌───┐┌───┐└───┘┌─┴─┐┌─┐└╥┘ q0_1: |0>────────┤ X ├┤ H ├─────┤ X ├┤M├─╫─ - ┌───┐┌─┐└───┘└───┘ └───┘└╥┘ ║ + ┌───┐┌─┐└───┘└───┘ └───┘└╥┘ ║ q0_2: |0>┤ H ├┤M├─────────────────────╫──╫─ - └───┘└╥┘ ║ ║ + └───┘└╥┘ ║ ║ c0_0: 0 ══════╬══════════════════════╬══╩═ - ║ ║ + ║ ║ c0_1: 0 ══════╬══════════════════════╩════ - ║ + ║ c0_2: 0 ══════╩═══════════════════════════
@@ -155,14 +155,14 @@ backend, only ``latex`` is used for brevity. .. code:: python # Draw a new circuit with barriers and more registers - + q_a = QuantumRegister(3, name='qa') q_b = QuantumRegister(5, name='qb') c_a = ClassicalRegister(3) c_b = ClassicalRegister(5) - + circuit = QuantumCircuit(q_a, q_b, c_a, c_b) - + circuit.x(q_a[1]) circuit.x(q_b[1]) circuit.x(q_b[2]) @@ -338,33 +338,33 @@ line styles, etc. The list of available options for this are: «qa_0: ────────────────┤ H ├─░───────┤M├ « ┌───┐└───┘ ░ ┌─┐└╥┘ «qa_1: ───────────┤ H ├──────░────┤M├─╫─ - « ┌───┐└───┘ ░ ┌─┐└╥┘ ║ + « ┌───┐└───┘ ░ ┌─┐└╥┘ ║ «qa_2: ──────┤ H ├───────────░─┤M├─╫──╫─ - « ┌─┐└───┘ ░ └╥┘ ║ ║ + « ┌─┐└───┘ ░ └╥┘ ║ ║ «qb_0: ───┤M├───────────────────╫──╫──╫─ - « ┌─┐└╥┘ ║ ║ ║ + « ┌─┐└╥┘ ║ ║ ║ «qb_1: ┤M├─╫────────────────────╫──╫──╫─ - « └╥┘ ║ ║ ║ ║ + « └╥┘ ║ ║ ║ ║ «qb_2: ─╫──╫────────────────────╫──╫──╫─ - « ║ ║ ║ ║ ║ + « ║ ║ ║ ║ ║ «qb_3: ─╫──╫────────────────────╫──╫──╫─ - « ║ ║ ║ ║ ║ + « ║ ║ ║ ║ ║ «qb_4: ─╫──╫────────────────────╫──╫──╫─ - « ║ ║ ║ ║ ║ + « ║ ║ ║ ║ ║ «c1_0: ═╬══╬════════════════════╬══╬══╩═ - « ║ ║ ║ ║ + « ║ ║ ║ ║ «c1_1: ═╬══╬════════════════════╬══╩════ - « ║ ║ ║ + « ║ ║ ║ «c1_2: ═╬══╬════════════════════╩═══════ - « ║ ║ + « ║ ║ «c2_0: ═╬══╩════════════════════════════ - « ║ + « ║ «c2_1: ═╩═══════════════════════════════ - « + « «c2_2: ═════════════════════════════════ - « + « «c2_3: ═════════════════════════════════ - « + « «c2_4: ═════════════════════════════════ «
@@ -373,9 +373,9 @@ line styles, etc. The list of available options for this are: .. code:: python # Change the background color in mpl - + style = {'backgroundcolor': 'lightgreen'} - + circuit.draw(output='mpl', style=style) @@ -444,25 +444,25 @@ still return the string) instead of returning just a string. \begin{document} \begin{equation*} \Qcircuit @C=0.5em @R=0.0em @!R { - \lstick{qa_{0}: \ket{0}} & \qw & \qw \barrier{7} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \gate{H} & \qw \barrier[-1.15em]{2} & \qw & \qw & \meter & \qw & \qw\\ - \lstick{qa_{1}: \ket{0}} & \gate{X} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \gate{H} & \qw & \qw & \meter & \qw & \qw & \qw\\ - \lstick{qa_{2}: \ket{0}} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \gate{H} & \qw & \meter & \qw & \qw & \qw & \qw\\ - \lstick{qb_{0}: \ket{0}} & \qw & \qw & \gate{H} & \ctrl{1} & \qw & \qswap \qwx[4] & \qw \barrier[-1.15em]{4} & \qw & \qw & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw\\ - \lstick{qb_{1}: \ket{0}} & \gate{X} & \qw & \gate{H} & \qswap & \qw & \qw & \qw & \qw & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ - \lstick{qb_{2}: \ket{0}} & \gate{X} & \qw & \gate{H} & \qswap \qwx[-1] & \ctrl{1} & \qw & \qw & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ - \lstick{qb_{3}: \ket{0}} & \qw & \qw & \gate{H} & \qw & \qswap & \ctrl{1} & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ - \lstick{qb_{4}: \ket{0}} & \gate{X} & \qw & \gate{H} & \qw & \qswap \qwx[-1] & \qswap & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ - \lstick{c1_{0}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw\\ - \lstick{c1_{1}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw\\ - \lstick{c1_{2}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw\\ - \lstick{c2_{0}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw\\ - \lstick{c2_{1}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ - \lstick{c2_{2}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ - \lstick{c2_{3}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ - \lstick{c2_{4}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ - } + \lstick{qa_{0}: \ket{0}} & \qw & \qw \barrier{7} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \gate{H} & \qw \barrier[-1.15em]{2} & \qw & \qw & \meter & \qw & \qw\\ + \lstick{qa_{1}: \ket{0}} & \gate{X} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \gate{H} & \qw & \qw & \meter & \qw & \qw & \qw\\ + \lstick{qa_{2}: \ket{0}} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \gate{H} & \qw & \meter & \qw & \qw & \qw & \qw\\ + \lstick{qb_{0}: \ket{0}} & \qw & \qw & \gate{H} & \ctrl{1} & \qw & \qswap \qwx[4] & \qw \barrier[-1.15em]{4} & \qw & \qw & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw\\ + \lstick{qb_{1}: \ket{0}} & \gate{X} & \qw & \gate{H} & \qswap & \qw & \qw & \qw & \qw & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ + \lstick{qb_{2}: \ket{0}} & \gate{X} & \qw & \gate{H} & \qswap \qwx[-1] & \ctrl{1} & \qw & \qw & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ + \lstick{qb_{3}: \ket{0}} & \qw & \qw & \gate{H} & \qw & \qswap & \ctrl{1} & \qw & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ + \lstick{qb_{4}: \ket{0}} & \gate{X} & \qw & \gate{H} & \qw & \qswap \qwx[-1] & \qswap & \meter & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\ + \lstick{c1_{0}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw\\ + \lstick{c1_{1}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw\\ + \lstick{c1_{2}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw\\ + \lstick{c2_{0}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw\\ + \lstick{c2_{1}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ + \lstick{c2_{2}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ + \lstick{c2_{3}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ + \lstick{c2_{4}: 0} & \cw & \cw & \cw & \cw & \cw & \cw & \cw \cwx[-8] & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw & \cw\\ + } \end{equation*} - + \end{document} diff --git a/tox.ini b/tox.ini index 3e55ab82cf5e..f36123f66a55 100644 --- a/tox.ini +++ b/tox.ini @@ -17,6 +17,13 @@ commands = deps = pycodestyle pylint + doc8 + ipython commands = pycodestyle test pylint -rn --rcfile={toxinidir}/.pylintrc test + doc8 docs + +[doc8] +max-line-length=100 +ignore-path=docs/_build