Code Monkey home page Code Monkey logo

qiskit-aqua's Introduction

Qiskit Aqua (NOW DEPRECATED)

LicenseBuild StatusCoverage Status


PLEASE NOTE: As of version 0.9.0, released on 2nd April 2021, Qiskit Aqua has been deprecated with its support ending and eventual archival being no sooner than 3 months from that date. The function provided by Qiskit Aqua is not going away rather it has being split out to separate application repositories, with core algorithm and operator function moving to qiskit-terra. Please see the Migration Guide section below for more detail. We encourage you to migrate over at your earliest convenience.


Qiskit is an open-source framework for working with noisy quantum computers at the level of pulses, circuits, and algorithms.

Qiskit is made up elements that work together to enable quantum computing. This element is Aqua (Algorithms for QUantum computing Applications) providing a library of cross-domain algorithms upon which domain-specific applications can be built.

Aqua includes domain application support for:

Note: the chemistry module was the first domain worked on. Aqua version 0.7.0 introduced a new optimization module for solving quadratic problems. At the time of writing the other domains have some logic in them but are not as fully realised. Future work is expected to build out functionality in all application areas.

Aqua was designed to be extensible, and uses a framework where algorithms and support objects used by algorithms, such as optimizers, variational forms, and oracles etc, are derived from a defined base class for the type. These along with other building blocks provide a means for end-users and developers alike to have flexibility and facilitate building and experimenting with different configurations and capability.

Note: Aqua provides some classical algorithms that take the same input data as quantum algorithms solving the same problem. For instance a Hamiltonian operator input to VQE can be used as an input to the NumPyEigensolver. This may be useful for near-term quantum experiments, for problems that can still be solved classically, as their outcome can be easily compared against a classical equivalent since the same input data can be used.

Migration Guide

As of version 0.9.0, released on 2nd April 2021, Qiskit Aqua has been deprecated with its support ending and eventual archival being no sooner than 3 months from that date.

All the functionality that qiskit-aqua provides has been migrated to either new packages or to other qiskit packages. The application modules that are provided by qiskit-aqua have been split into several new packages:

  • qiskit-finance

    Aqua's qiskit.finance package was moved here

  • qiskit-machine-learning

    Aqua's qiskit.ml package was moved here

  • qiskit-nature

    Aqua's qiskit.chemistry package was moved here, where this new repository for natural science applications, will have a broader scope than chemistry.

  • qiskit-optimization

    Aqua's qiskit.optimization package was moved here

These new packages can be installed by themselves (via the standard pip install command, e.g. pip install qiskit-nature) or with the rest of the Qiskit metapackage as optional extras (e.g. pip install 'qiskit[finance,optimization]' or pip install 'qiskit[all]'.

The core building blocks for algorithms and of the operator flow have been moved, to become core function of Qiskit, and now exist as part of

  • qiskit-terra

    See the qiskit.algorithms and qiskit.opflow packages respectively. A Qiskit Algorithms Migration Guide has been created to inform and assist the migration, from using the algorithms as they are in Aqua, to their newly refactored equivalents as they exist now in their new location.

Migration by package/class

The following table gives a more detailed breakdown that relates the function, as it existed in Aqua, to where it now lives after this move.

Old New Library
qiskit.aqua.algorithms.amplitude_amplifiers qiskit.algorithms.amplitude_amplifiers qiskit-terra
qiskit.aqua.algorithms.amplitude_estimators qiskit.algorithms.amplitude_estimators qiskit-terra
qiskit.aqua.algorithms.classifiers qiskit_machine_learning.algorithms.classifiers qiskit-machine-learning
qiskit.aqua.algorithms.distribution_learners qiskit_machine_learning.algorithms.distribution_learners qiskit-machine-learning
qiskit.aqua.algorithms.eigen_solvers qiskit.algorithms.eigen_solvers qiskit-terra
qiskit.aqua.algorithms.factorizers qiskit.algorithms.factorizers qiskit-terra
qiskit.aqua.algorithms.minimum_eigen_solvers qiskit.algorithms.minimum_eigen_solvers qiskit-terra
qiskit.aqua.algorithms.VQAlgorithm qiskit.algorithms.VariationalAlgorithm qiskit-terra
qiskit.aqua.aqua_globals qiskit.utils.algorithm_globals qiskit-terra
qiskit.aqua.components.multiclass_extensions
qiskit.aqua.components.neural_networks qiskit_machine_learning.algorithms.distribution_learners.qgan qiskit-machine-learning
qiskit.aqua.components.optimizers qiskit.algorithms.optimizers qiskit-terra
qiskit.aqua.components.variational_forms
qiskit.aqua.operators qiskit.opflow qiskit-terra
qiskit.aqua.QuantumInstance qiskit.utils.QuantumInstance qiskit-terra
qiskit.chemistry qiskit_nature qiskit-nature
qiskit.finance qiskit_finance qiskit-finance
qiskit.ml qiskit_machine_learning qiskit-machine-learning
qiskit.optimization qiskit_optimization qiskit-optimization

Installation

We encourage installing Qiskit via the pip tool (a python package manager), which installs all Qiskit elements, including Aqua.

pip install qiskit

pip will handle all dependencies automatically and you will always install the latest (and well-tested) version.

If you want to work on the very latest work-in-progress versions, either to try features ahead of their official release or if you want to contribute to Aqua, then you can install from source. To do this follow the instructions in the documentation.

Note: there some optional packages that can be installed such as IBM CPLEX for Aqua and ab-initio chemistry libraries/programs. Refer to Optional Install information in the sections below.


Aqua

The qiskit.aqua package contains the core cross-domain algorithms and supporting logic to run these on a quantum backend, whether a real device or simulator.

Optional Installs

Note: while the packages below can be installed directly by pip install, e.g. pip install cplex by doing so via the Aqua extra_requires, in this case pip 'install qiskit-aqua[cplex]' will ensure that a version compatible with Qiskit is installed.

  • IBM CPLEX may be installed to allow the use of the CplexOptimizer classical solver algorithm. pip 'install qiskit-aqua[cplex]' may be used to install the community version.
  • PyTorch, may be installed either using command pip install 'qiskit-aqua[torch]' to install the package or refer to PyTorch getting started. PyTorch being installed will enable the neural networks PyTorchDiscriminator component to be used with the QGAN algorithm.
  • CVXPY, may be installed using command pip install 'qiskit-aqua[cvx]' to enable use of the QSVM and the classical SklearnSVM algorithms.

Creating Your First Quantum Program in Qiskit Aqua

Now that Qiskit is installed, it's time to begin working with Aqua. Let's try an experiment using Grover's algorithm to find a solution for a Satisfiability (SAT) problem.

$ python
from qiskit import Aer
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.aqua.algorithms import Grover

sat_cnf = """
c Example DIMACS 3-sat
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
"""

backend = Aer.get_backend('qasm_simulator')
oracle = LogicalExpressionOracle(sat_cnf)
algorithm = Grover(oracle)
result = algorithm.run(backend)
print(result.assignment)

The code above demonstrates how Grover’s search algorithm can be used with the LogicalExpressionOracle to find one satisfying assignment for the Satisfiability (SAT) problem instance encoded in the DIMACS CNF format. The input string sat_cnf corresponds to the following Conjunctive Normal Form (CNF):

x1 ∨ ¬x2 ∨ ¬x3) ∧ (x1 ∨ ¬x2x3) ∧ (x1x2 ∨ ¬x3) ∧ (x1 ∨ ¬x2 ∨ ¬x3) ∧ (¬x1x2x3)

The Python code above prints out one possible solution for this CNF. For example, output 1, -2, 3 indicates that logical expression (x1 ∨ ¬x2x3) satisfies the given CNF.

Further examples

Learning path notebooks may be found in the algorithms tutorials section of the documentation and are a great place to start

Jupyter notebooks containing further examples, for Qiskit Aqua, may be found here in the following Qiskit GitHub repositories at qiskit-tutorials/tutorials/algorithms and qiskit-community-tutorials/aqua.


Chemistry

The qiskit.chemistry package supports problems including ground state energy computations, excited states and dipole moments of molecule, both open and closed-shell.

The code comprises chemistry drivers, which when provided with a molecular configuration will return one and two-body integrals as well as other data that is efficiently computed classically. This output data from a driver can then be used as input to the chemistry module that contains logic which is able to translate this into a form that is suitable for quantum algorithms. The conversion first creates a FermionicOperator which must then be mapped, e.g. by a Jordan Wigner mapping, to a qubit operator in readiness for the quantum computation.

Optional Installs

To run chemistry experiments using Qiskit's chemistry module, it is recommended that you install a classical computation chemistry software program/library interfaced by Qiskit. Several, as listed below, are supported, and while logic to interface these programs is supplied by the chemistry module via the above pip installation, the dependent programs/libraries themselves need to be installed separately.

  1. Gaussian 16™, a commercial chemistry program
  2. PSI4, a chemistry program that exposes a Python interface allowing for accessing internal objects
  3. PySCF, an open-source Python chemistry program
  4. PyQuante, a pure cross-platform open-source Python chemistry program

HDF5 Driver

A useful functionality integrated into Qiskit's chemistry module is its ability to serialize a file in hierarchical Data Format 5 (HDF5) format representing all the output data from a chemistry driver.

The HDF5 driver accepts such HDF5 files as input so molecular experiments can be run, albeit on the fixed data as stored in the file. As such, if you have some pre-created HDF5 files from created from Qiskit Chemistry, you can use these with the HDF5 driver even if you do not install one of the classical computation packages listed above.

A few sample HDF5 files for different are provided in the chemistry folder of the Qiskit Community Tutorials repository. This HDF5 Driver tutorial contains further information about creating and using such HDF5 files.

Creating Your First Chemistry Programming Experiment in Qiskit

Now that Qiskit is installed, it's time to begin working with the chemistry module. Let's try a chemistry application experiment using VQE (Variational Quantum Eigensolver) algorithm to compute the ground-state (minimum) energy of a molecule.

from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.aqua.operators import Z2Symmetries

# Use PySCF, a classical computational chemistry software
# package, to compute the one-body and two-body integrals in
# molecular-orbital basis, necessary to form the Fermionic operator
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735',
                     unit=UnitsType.ANGSTROM,
                     basis='sto3g')
molecule = driver.run()
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2

# Build the qubit operator, which is the input to the VQE algorithm in Aqua
ferm_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
map_type = 'PARITY'
qubit_op = ferm_op.mapping(map_type)
qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, num_particles)
num_qubits = qubit_op.num_qubits

# setup a classical optimizer for VQE
from qiskit.aqua.components.optimizers import L_BFGS_B
optimizer = L_BFGS_B()

# setup the initial state for the variational form
from qiskit.chemistry.circuit.library import HartreeFock
init_state = HartreeFock(num_spin_orbitals, num_particles)

# setup the variational form for VQE
from qiskit.circuit.library import TwoLocal
var_form = TwoLocal(num_qubits, ['ry', 'rz'], 'cz')

# add the initial state
var_form.compose(init_state, front=True)

# setup and run VQE
from qiskit.aqua.algorithms import VQE
algorithm = VQE(qubit_op, var_form, optimizer)

# set the backend for the quantum computation
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')

result = algorithm.run(backend)
print(result.eigenvalue.real)

The program above uses a quantum computer to calculate the ground state energy of molecular Hydrogen, H2, where the two atoms are configured to be at a distance of 0.735 angstroms. The molecular input specification is processed by PySCF driver and data is output that includes one- and two-body molecular-orbital integrals. From the output a fermionic-operator is created which is then parity mapped to generate a qubit operator. Parity mappings allow a precision-preserving optimization that two qubits can be tapered off; a reduction in complexity that is particularly advantageous for NISQ computers.

The qubit operator is then passed as an input to the Variational Quantum Eigensolver (VQE) algorithm, instantiated with a classical optimizer and a RyRz variational form (ansatz). A Hartree-Fock initial state is used as a starting point for the variational form.

The VQE algorithm is then run, in this case on the Qiskit Aer statevector simulator backend. Here we pass a backend but it can be wrapped into a QuantumInstance, and that passed to the run instead. The QuantumInstance API allows you to customize run-time properties of the backend, such as the number of shots, the maximum number of credits to use, settings for the simulator, initial layout of qubits in the mapping and the Terra PassManager that will handle the compilation of the circuits. By passing in a backend as is done above it is internally wrapped into a QuantumInstance and is a convenience when default setting suffice.

Further examples

Learning path notebooks may be found in the chemistry tutorials section of the documentation and are a great place to start

Jupyter notebooks containing further chemistry examples may be found in the following Qiskit GitHub repositories at qiskit-tutorials/tutorials/chemistry and qiskit-community-tutorials/chemistry.


Finance

The qiskit.finance package contains uncertainty components for stock/securities problems, Ising translators for portfolio optimizations and data providers to source real or random data to finance experiments.

Creating Your First Finance Programming Experiment in Qiskit

Now that Qiskit is installed, it's time to begin working with the finance module. Let's try an experiment using Amplitude Estimation algorithm to evaluate a fixed income asset with uncertain interest rates.

import numpy as np
from qiskit import BasicAer
from qiskit.aqua.algorithms import AmplitudeEstimation
from qiskit.circuit.library import NormalDistribution
from qiskit.finance.applications import FixedIncomeExpectedValue

# Create a suitable multivariate distribution
num_qubits = [2, 2]
bounds = [(0, 0.12), (0, 0.24)]
mvnd = NormalDistribution(num_qubits,
                          mu=[0.12, 0.24], sigma=0.01 * np.eye(2),
                          bounds=bounds)

# Create fixed income component
fixed_income = FixedIncomeExpectedValue(num_qubits, np.eye(2), np.zeros(2),
                                        cash_flow=[1.0, 2.0], rescaling_factor=0.125,
                                        bounds=bounds)

# the FixedIncomeExpectedValue provides us with the necessary rescalings
post_processing = fixed_income.post_processing

# create the A operator for amplitude estimation by prepending the
# normal distribution to the function mapping
state_preparation = fixed_income.compose(mvnd, front=True)

# Set number of evaluation qubits (samples)
num_eval_qubits = 5

# Construct and run amplitude estimation
backend = BasicAer.get_backend('statevector_simulator')
algo = AmplitudeEstimation(num_eval_qubits, state_preparation,
                            post_processing=post_processing)
result = algo.run(backend)

print('Estimated value:\t%.4f' % result.estimation)
print('Probability:    \t%.4f' % result.max_probability)

When running the above the estimated value result should be 2.46 and probability 0.8487.

Further examples

Learning path notebooks may be found in the finance tutorials section of the documentation and are a great place to start

Jupyter notebooks containing further finance examples may be found in the following Qiskit GitHub repositories at qiskit-tutorials/tutorials/finance and qiskit-community-tutorials/finance.


Machine Learning

The qiskit.ml package simply contains sample datasets at present. qiskit.aqua has some classification algorithms such as QSVM and VQC (Variational Quantum Classifier), where this data can be used for experiments, and there is also QGAN (Quantum Generative Adversarial Network) algorithm.

Creating Your First Machine Learning Programming Experiment in Qiskit

Now that Qiskit is installed, it's time to begin working with Machine Learning. Let's try an experiment using VQC (Variational Quantum Classified) algorithm to train and test samples from a data set to see how accurately the test set can be classified.

from qiskit import BasicAer
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQC
from qiskit.aqua.components.optimizers import COBYLA
from qiskit.aqua.components.feature_maps import RawFeatureVector
from qiskit.ml.datasets import wine
from qiskit.circuit.library import TwoLocal

seed = 1376
aqua_globals.random_seed = seed

# Use Wine data set for training and test data
feature_dim = 4  # dimension of each data point
_, training_input, test_input, _ = wine(training_size=12,
                                        test_size=4,
                                        n=feature_dim)

feature_map = RawFeatureVector(feature_dimension=feature_dim)
vqc = VQC(COBYLA(maxiter=100),
          feature_map,
          TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3),
          training_input,
          test_input)
result = vqc.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                                 shots=1024, seed_simulator=seed, seed_transpiler=seed))

print('Testing accuracy: {:0.2f}'.format(result['testing_accuracy']))

Further examples

Learning path notebooks may be found in the machine learning tutorials section of the documentation and are a great place to start

Jupyter notebooks containing further Machine Learning examples may be found in the following Qiskit GitHub repositories at qiskit-tutorials/tutorials/machine_learning and qiskit-community-tutorials/machine_learning.


Optimization

The qiskit.optimization package covers the whole range from high-level modeling of optimization problems, with automatic conversion of problems to different required representations, to a suite of easy-to-use quantum optimization algorithms that are ready to run on classical simulators, as well as on real quantum devices via Qiskit.

This optimization module enables easy, efficient modeling of optimization problems using docplex. A uniform interface as well as automatic conversion between different problem representations allows users to solve problems using a large set of algorithms, from variational quantum algorithms, such as the Quantum Approximate Optimization Algorithm QAOA, to Grover Adaptive Search using the GroverOptimizer leveraging fundamental algorithms provided by Aqua. Furthermore, the modular design of the optimization module allows it to be easily extended and facilitates rapid development and testing of new algorithms. Compatible classical optimizers are also provided for testing, validation, and benchmarking.

Optional Installs

  • IBM CPLEX may be installed using pip install 'qiskit-aqua[cplex]' to allow the use of the CplexOptimzer classical solver algorithm, as well as enabling the reading of LP files.

Creating Your First Optimization Programming Experiment in Qiskit

Now that Qiskit is installed, it's time to begin working with the optimization module. Let's try an optimization experiment to compute the solution of a Max-Cut. The Max-Cut problem can be formulated as quadratic program, which can be solved using many several different algorithms in Qiskit. In this example, the MinimumEigenOptimizer is employed in combination with the Quantum Approximate Optimization Algorithm (QAOA) as minimum eigensolver routine.

import networkx as nx
import numpy as np

from qiskit.optimization import QuadraticProgram
from qiskit.optimization.algorithms import MinimumEigenOptimizer

from qiskit import BasicAer
from qiskit.aqua.algorithms import QAOA
from qiskit.aqua.components.optimizers import SPSA

# Generate a graph of 4 nodes
n = 4
graph = nx.Graph()
graph.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
graph.add_weighted_edges_from(elist)

# Compute the weight matrix from the graph
w = nx.adjacency_matrix(graph)

# Formulate the problem as quadratic program
problem = QuadraticProgram()
_ = [problem.binary_var('x{}'.format(i)) for i in range(n)]  # create n binary variables
linear = w.dot(np.ones(n))
quadratic = -w
problem.maximize(linear=linear, quadratic=quadratic)

# Fix node 0 to be 1 to break the symmetry of the max-cut solution
problem.linear_constraint([1, 0, 0, 0], '==', 1)

# Run quantum algorithm QAOA on qasm simulator
spsa = SPSA(max_trials=250)
backend = BasicAer.get_backend('qasm_simulator')
qaoa = QAOA(optimizer=spsa, p=5, quantum_instance=backend)
algorithm = MinimumEigenOptimizer(qaoa)
result = algorithm.solve(problem)
print(result)  # prints solution, x=[1, 0, 1, 0], the cost, fval=4

Further examples

Learning path notebooks may be found in the optimization tutorials section of the documentation and are a great place to start.

Jupyter notebooks containing further examples, for the optimization module, may be found in the following Qiskit GitHub repositories at qiskit-tutorials/tutorials/optimization and qiskit-community-tutorials/optimization.


Using a Real Device

You can also use Qiskit to execute your code on a real quantum chip. In order to do so, you need to configure Qiskit to use the credentials in your IBM Quantum Experience account. For more detailed information refer to the relevant instructions in the Qiskit Terra GitHub repository .

Contribution Guidelines

If you'd like to contribute to Qiskit, please take a look at our contribution guidelines. This project adheres to Qiskit's code of conduct. By participating, you are expected to uphold this code.

We use GitHub issues for tracking requests and bugs. Please join the Qiskit Slack community and use the Aqua Slack channel for discussion and simple questions. For questions that are more suited for a forum, we use the Qiskit tag in Stack Overflow.

Next Steps

Now you're set up and ready to check out some of the other examples from the Qiskit Tutorials repository, that are used for the IBM Quantum Experience, and from the Qiskit Community Tutorials.

Authors and Citation

Aqua was inspired, authored and brought about by the collective work of a team of researchers. Aqua continues to grow with the help and work of many people, who contribute to the project at different levels. If you use Qiskit, please cite as per the provided BibTeX file.

Please note that if you do not like the way your name is cited in the BibTex file then consult the information found in the .mailmap file.

License

This project uses the Apache License 2.0.

However there is some code that is included under other licensing as follows:

qiskit-aqua's People

Contributors

a-matsuo avatar abdonrd avatar adekusar-drl avatar antoniomezzacapo avatar attp avatar brogis1 avatar chriseclectic avatar chunfuchen avatar cryoris avatar dabucher avatar dbucher97 avatar dongreenberg avatar gawelkus avatar hushaohan avatar ikkoham avatar jmarecek avatar jmueg avatar liupibm avatar manoelmarques avatar molar-volume avatar mrossinek avatar mtreinish avatar nick-singstock avatar paulineollitrault avatar pbark avatar stefan-woerner avatar t-imamichi avatar tigerjack avatar woodsp-ibm avatar zoufalc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

qiskit-aqua's Issues

split the eval of operator into multiple steps to get the circuits

What is the expected enhancement?

Now eval method in the operator includes multiple steps, so intermediate might be useful for the users.
E.g., users want to get the cirucits for the evaluation.

It will be better we split the steps of eval into multiple methods and then users have higher flexible to do that.

We can split it into three steps:

  1. Generate the circuits for evaluation
  2. Run the circuits to get results
  3. Use the result with Operator to calculate the observable.

With this enhancement, we create the potential to bundle the circuits of different parameters in wavefunction during the VQE.

E.g., in SPSA, we need to evaluate Operate against with theta+ and theta-. if we can bundle the circuits of theta+ and theta- together, we can submit them together, rather than run them separately.

VQE.run() only does one function evaluation with qasm_simulator backend

Informations

  • Qiskit Aqua version: master
  • Python version: 3.6.3
  • Operating system: macos

What is the current behavior?

Ground state energy evaluation with VQE succeeds with statevector_simulator backend but with qasm_simulator evaluates to 0 once and then terminates.

Steps to reproduce the problem

import numpy as np
from qiskit.tools.qi.pauli import Pauli

# lib from Qiskit AQUA Chemistry
from qiskit_aqua_chemistry import FermionicOperator


from qiskit_aqua.operator import Operator
from qiskit_aqua import (get_algorithm_instance, get_optimizer_instance, get_variational_form_instance)
from qiskit_aqua.algorithms.components.initial_states.hartree_fock import HartreeFock

# lib for driver
from qiskit_aqua_chemistry.drivers import ConfigurationManager
from collections import OrderedDict


# using driver to get fermionic Hamiltonian
# PySCF example
cfg_mgr = ConfigurationManager()
pyscf_cfg = OrderedDict([('atom', 'H .0 .0 .0; H .0 .0 0.735'), 
                         ('unit', 'Angstrom'), ('charge', 0), ('spin', 0), ('basis', 'sto3g')])
section = {}
section['properties'] = pyscf_cfg
driver = cfg_mgr.get_driver_instance('PYSCF')
molecule = driver.run(section)


n_electrons = 2
# print(molecule._nuclear_repulsion_energy)

n_qubits = molecule._one_body_integrals.shape[0]
# print(molecule._one_body_integrals)

# get fermionic operator and mapping to qubit operator
ferOp = FermionicOperator(h1=molecule._one_body_integrals, h2=molecule._two_body_integrals)
qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001)
# print(qubitOp)
qubitOp.convert('paulis','matrix')
qubitOp.chop(10**-10)

# setup VQE 
# setup optimizer, use L_BFGS_B optimizer for example
lbfgs = get_optimizer_instance('L_BFGS_B')
lbfgs.set_options(maxfun=1000, factr=10, iprint=10)
# setup variation form generator (generate trial circuits for VQE)
initial_hf = HartreeFock()
initial_hf.init_args(num_qubits=n_qubits, num_orbitals=n_qubits, 
                     qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_particles= n_electrons)

var_form = get_variational_form_instance('UCCSD')
var_form.init_args(num_qubits=n_qubits, num_orbitals=n_qubits, 
                   num_particles=n_electrons, depth=1, initial_state=initial_hf, qubit_mapping='jordan_wigner')


number_amplitudes = len(var_form._single_excitations)+ len(var_form._double_excitations)
amplitudes_0 = np.ndarray(shape=(number_amplitudes,), dtype=float, order='F')
for i in range(len(amplitudes_0)):
    amplitudes_0[i] = 0.000001


# setup VQE with operator, variation form, and optimzer
vqe_algorithm = get_algorithm_instance('VQE')

backend_name = 'qasm_simulator'

vqe_algorithm.setup_quantum_backend(backend=backend_name, skip_transpiler=True)
vqe_algorithm.init_args(qubitOp, 'matrix', var_form, lbfgs, opt_init_point=amplitudes_0)
results = vqe_algorithm.run()
results['eigvals'][0] = results['eigvals'][0] + molecule._nuclear_repulsion_energy
print("Minimum value: {}".format(results['eigvals'][0].real))
print("Parameters: {}".format(results['opt_params']))

What is the expected behavior?

same as statevector_simulator

Suggested solutions

Installation within virtualenv fails due to numpy versioning problem

Informations

  • Qiskit Aqua version: 0.1.2
  • Python version: 3.6
  • Operating system: Ubuntu 16.04 LTS

What is the current behavior?

Installation fails because qiskit specifies numpy >= 1.13 but qiskit-acqua and qiskit-acqua-chemistry specify numpy<1.15,>=1.13. Therefore, during installation, numpy==1.15 is installed creating an incompatibility with the requirements ffrom both acqua and acqua-chemistry.

Steps to reproduce the problem

Create a virtual environment with:

virtualenv venv -p /usr/bin/python3.6

Next, activate the virtual environment using:

source venv/bin/activate

Last, begin the installation with:

pip install qiskit qiskit-acqua qiskit-acqua-chemistry --no-cache-dir

What is the expected behavior?

I expect the installation to finish with numpy installed without any versioning issues.

Suggested solutions

Specify numpy<1.15,>=1.13 in qiskit, exactly the same as in qiskit-acqua and qiskit-acqua-chemistry.

Additional information

We are having an extensive discussion with Rudy regarding versioning issues in #235. Additional relevant details may be found there.

SVM Multiclass extensions estimator_cls parameter does not work with deafult QSVM_Kernel_Estimator value

Informations

  • Qiskit Aqua version: 0.6.1
  • Python version: 3.6.5
  • Operating system: Ubuntu 18.04.1 LTS

What is the current behavior?

I pass the value of the default kernel that i found on the aqua files that is the QSVM_Kernel_Estimator, but when i execute the run() method, i get the following error:

2018-11-12 16:25:39,680:qiskit_aqua.algorithms.components.multiclass_extensions.allpairs:INFO: Require 3.0 estimators.

TypeError Traceback (most recent call last)
in
----> 1 result = svm.run()

~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/many_sample/qsvm/qsvm_kernel.py in run(self)
143
144 def run(self):
--> 145 return self.instance.run()
146
147 @Property

~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/many_sample/qsvm/qsvm_kernel_multiclass.py in run(self)
53 put the train, test, predict together
54 """
---> 55 self.train(self.training_dataset[0], self.training_dataset[1])
56 if self.test_dataset is not None:
57 self.test(self.test_dataset[0], self.test_dataset[1])

~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/many_sample/qsvm/qsvm_kernel_multiclass.py in train(self, data, labels)
36
37 def train(self, data, labels):
---> 38 self.multiclass_classifier.train(data, labels)
39
40 def test(self, data, labels):

~/anaconda3/envs/quantum/lib/python3.6/site-packages/qiskit_aqua/algorithms/components/multiclass_extensions/allpairs.py in train(self, x, y)
65 for j in range(i + 1, n_classes):
66 if self.params is None:
---> 67 estimator = self.estimator_cls()
68 else:
69 estimator = self.estimator_cls(*self.params)

TypeError: init() missing 2 required positional arguments: 'feature_map' and 'qalgo'

Steps to reproduce the problem

What is the expected behavior?

I just want to know how to call the following method... Which parameters should be passed?

svm = get_algorithm_instance("QSVM.Kernel")
svm.random_seed = 10598
svm.setup_quantum_backend(backend='ibmq_20_tokyo')

feature_map = get_feature_map_instance('SecondOrderExpansion')
feature_map.init_args(num_qubits=20, depth=2, entanglement={0: [1]})

all_pairs_extension = get_multiclass_extension_instance('AllPairs')
all_pairs_extension.init_args(estimator_cls=QSVM_Kernel_Estimator) # THE PROBLEM IS HERE. WHAT ARE THE PARAMETERS AND VALUES THAT SHOULD BE PASSED?

svm.init_args(training_input, test_input, datapoints[0], feature_map, multiclass_extension=all_pairs_extension)

Suggested solutions

MaxCut VQE does not equal ExactEigen

Expected Behavior

Modifying the MaxCut tutorial to have larger dimension, N=10, results in different answers for the VQE and ExactDiagonal solvers.

Current Behavior

For

w = array([[ 0.,  8.,  0.,  0.,  9.,  0., -8.,  0.,  0., -4.],
       [ 8.,  0.,  0.,  0.,  0.,  0., -5.,  0.,  5.,  9.],
       [ 0.,  0.,  0., -8.,  0.,  0., -8.,  0.,  0.,  0.],
       [ 0.,  0., -8.,  0.,  0.,  0.,  0.,  6., -8.,  0.],
       [ 9.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [-8., -5., -8.,  0.,  0.,  0.,  0.,  0.,  0., -3.],
       [ 0.,  0.,  0.,  6.,  0.,  0.,  0.,  0., -2.,  0.],
       [ 0.,  5.,  0., -8.,  0.,  0.,  0., -2.,  0.,  0.],
       [-4.,  9.,  0.,  0.,  0.,  0., -3.,  0.,  0.,  0.]])

I get ExactEigenSolver:

energy: -34.5
maxcut objective: -30.0
solution: [0. 1. 0. 0. 1. 1. 0. 1. 0. 0.]
solution objective: 30.0

where as VQE gives:

energy: -19.499999887119802
time: 638.5913169384003
maxcut objective: -14.999999887119802
solution: [1. 1. 1. 1. 0. 1. 1. 0. 1. 0.]
solution objective: 15.0

Possible Solution

Steps to Reproduce (for bugs)

Try tutorial with above graph.

Context

Wanted to make a slide highlighting this feature

Your Environment

  • Version used:
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version:

OSX, Py36, latest Acqua

ImportError: cannot import name 'JSONSchema'

Informations

  • *importError

What is the current behavior?

If I do "from qiskit_aqua.parser import JSONSchema" it will complain
"ImportError: cannot import name 'JSONSchema'"

Steps to reproduce the problem

Open python REPL and input "from qiskit_aqua.parser import JSONSchema", it will complain "ImportError: cannot import name 'JSONSchema'"

What is the expected behavior?

Silently import the package

Suggested solutions

None.

VQE Gives Ground State Energy Below the Actual Energy

Expected Behavior

When doing a variational calculation, I would expect the energy predicted by the VQE to be greater than or equal to the actual ground state energy (variational principle).

Current Behavior

I am attempting to do a variational calculation with the VQE example code in the ACQUA tutorials using the local_qasm_simulator. I have slightly modified the file to make input easier, but none of the functionality is changed. I am using a Hamiltonian with ground state energy 0.54, but received a VQE prediction of the energy as 0.12, which is clearly less than the ground state.

Possible Solution

It is possible that I do not completely understand how is calculated in the simulator (I am relatively new to quantum computing) and that the behavior I have seen is not unexpected, but if so then how can this be claimed to be a variational calculation? I would imagine the error (if there is one) is in the calculation of the expectation value (in that is not actually directly calculated, as this would guarantee a higher value by the variational principle), but I cannot speculate any further than that.

Steps to Reproduce (for bugs)

I have attached the file containing the Hamiltonian I used (anharmonic_osc.txt) and my code (vqe_error.txt - just change the filename to .py). Within the vqe_error.txt file, I have included my output from when I received the error. All inputs were as assigned in vqe_error.txt. Running this file should reproduce the error with some probability, but it might be best to simply work with the outputs I received after running it (outputs are included at the bottom in a comment, including the optimal parameter values returned; running the file takes ~12.4 minutes).

anharmonic_osc.txt
vqe_error.txt

Context

I am relatively new to quantum computing, so I might be misinterpreting this and it might not be an unexpected output. However, it is troubling that a variational calculation can potentially yield an answer below the actual ground state, since that defeats the purpose of the variational calculation.

Thank you for taking the time to help.

Your Environment

  • Version used: QISKit ACQUA 0.1.1
  • Environment name and version (e.g. Python 3.6.1): Python 3.6.3
  • Operating System and version: Windows 7

algorithm.run vs run_algorithm

Also, what is the difference between

QuantumAlgorithm.run()

and using

run_algorithm(algo_input,params)

I personally don't think and algorithm should be able to run with a method. I think it should contain be ran by passing an algorithm and a backend to run_program (see #153).

Segmentation fault when using VQE with COBYLA optimizer

Informations

  • Qiskit Aqua version: current master
  • Python version: 3.6
  • Operating system: Linux

What is the current behavior?

A segmentation fault occurs for a specific input.

Steps to reproduce the problem

Create the following input file of aqua chemistry:

====================================================

&name
LiH excited states molecule experiment. Var for SWAPRZ with VQKE
&end

&driver
name=PYSCF
&end

&problem
name=energy
enable_substitutions=True
random_seed=50
&end

&pyscf
atom=H 0 0 -2.5; Be 0 0 0; H 0 0 2.5
unit=Angstrom
charge=0
spin=0
basis=sto3g
&end

&operator
name=hamiltonian
transformation=particle_hole
qubit_mapping=jordan_wigner
two_qubit_reduction=False
freeze_core=True
orbital_reduction=[]
max_workers=4
&end

&algorithm
name=VQE
operator_mode=matrix
initial_point=None
&end

&optimizer
name=COBYLA
maxiter=10000
&end

&variational_form
name=SWAPRZ
depth=1000
entanglement=full
entangler_map=None
&end

&initial_state
name=HartreeFock
qubit_mapping=jordan_wigner
two_qubit_reduction=False
&end

&backend
name=local_statevector_simulator
&end

====================================================

Then run:
qiskit_aqua_chemistry_cmd <file name>

The input cam from Julia Rice, but with other values of depth and maxIter. The bug occurs for these specific depth and maxIter (depth=1000, maxIter=10000). I haven't witnessed it for other values of these parameters.

What is the expected behavior?

Run without segmentation fault.

Suggested solutions

For the moment I only know that it happens inside COBYLA.optimize.

Operator class issues

Issues in implementation order:

1 - chop only in one representation at a time
2 - make sure summand operator is not updated in additions
3 - set to None other representations when using add or chop functions in one representation
4 - initialize diagonal representation as sparse

Optimization Stableset Error

Information

  • Qiskit Aqua version: 0.2.0
  • Python version: Python 3.6.5
  • Operating system: Linux

What is the current behavior?

Value Error raised when attempting to run the stableset optimization script using ExactEigensolver or VQE as the solver algorithm. A TypeError is raised when QAOA is used as the solver algorithm. Speifically, this used the stableset.py script to construct the operator for the Ising problem (all of this is outlined here https://github.com/Qiskit/aqua-tutorials/blob/master/optimization/stableset.ipynb).

Steps to reproduce the problem

Run the following code in Python3
from qiskit_aqua import Operator, run_algorithm, get_algorithm_instance
from qiskit_aqua.input import get_input_instance
from qiskit_aqua.algorithms.classical.cplex import stableset
import numpy as np
import networkx as nx

G = nx.gnp_random_graph(10, 0.567658261253)
w = nx.to_numpy_matrix(G)
qubitOp, offset = stableset.get_stableset_qubitops(w)
algo_input = get_input_instance('EnergyInput')
algo_input.qubit_op = qubitOp

if 1==1:
algorithm_cfg = {
'name': 'ExactEigensolver',
}

params = {
    'problem': {'name': 'ising'},
    'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)

x = stableset.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('stable set objective:', result['energy'] + offset)
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))

if 1==1:
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}

optimizer_cfg = {
    'name': 'L_BFGS_B',
    'maxfun': 2000
}

var_form_cfg = {
    'name': 'RYRZ',
    'depth': 3,
    'entanglement': 'linear'
}

params = {
    'problem': {'name': 'ising'},
    'algorithm': algorithm_cfg,
    'optimizer': optimizer_cfg,
    'variational_form': var_form_cfg,
    'backend': {'name': 'local_statevector_simulator'}
}

result = run_algorithm(params,algo_input)

x = stableset.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('stable set objective:', result['energy'] + offset)
print('solution:', stableset.get_graph_solution(x))
print('solution objective and feasibility:', stableset.stableset_value(x, w))

What is the expected behavior?

This Value Error (note this is error is specific to when ExactEigensolver is used, because ExactEigensolver is run first. The same error does occur if VQE is used in place of ExactEigensolver)

/root/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
Traceback (most recent call last):
File "mis_test.py", line 22, in
result = run_algorithm(params,algo_input)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/algomethods.py", line 83, in run_algorithm
algorithm.init_params(algo_params, algo_input)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/exacteigensolver/exacteigensolver.py", line 73, in init_params
self.init_args(algo_input.qubit_op, k, algo_input.aux_ops)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/exacteigensolver/exacteigensolver.py", line 88, in init_args
self._operator.convert('paulis', 'matrix')
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 824, in convert
self._paulis_to_matrix()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 939, in _paulis_to_matrix
self._to_dia_matrix(mode='paulis')
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 310, in _to_dia_matrix
dia_matrix += coeff * pauli.to_spmatrix().diagonal()
File "/root/anaconda3/lib/python3.6/site-packages/numpy/matrixlib/defmatrix.py", line 309, in mul
return N.dot(self, asmatrix(other))
ValueError: shapes (1,10) and (1,1024) not aligned: 10 (dim 1) != 1 (dim 0)

QAOA solve: another error encountered
In place of ExactEigensolver or VQE for algorithm_cfg, if we put in QAOA instead, we get a different error than the one observed for the other two algorithms.
/root/anaconda3/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
"This module will be removed in 0.20.", DeprecationWarning)
capi_return is NULL
Call-back cb_calcfc_in__cobyla__user__routines failed.
Traceback (most recent call last):
File "mis_test.py", line 54, in
result = run_algorithm(params,algo_input)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/algomethods.py", line 84, in run_algorithm
value = algorithm.run()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 236, in run
self._solve()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 188, in _solve
opt_params, opt_val = self.find_minimum_eigenvalue()
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 307, in find_minimum_eigenvalue
variable_bounds=bounds, initial_point=initial_point)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/utils/optimizers/cobyla.py", line 80, in optimize
res = minimize(objective_function, initial_point, tol=self._tol, method="COBYLA", options=self._options)
File "/root/anaconda3/lib/python3.6/site-packages/scipy/optimize/_minimize.py", line 608, in minimize
return _minimize_cobyla(fun, x0, args, constraints, **options)
File "/root/anaconda3/lib/python3.6/site-packages/scipy/optimize/cobyla.py", line 252, in _minimize_cobyla
dinfo=info)
File "/root/anaconda3/lib/python3.6/site-packages/scipy/optimize/cobyla.py", line 242, in calcfc
f = fun(x, *args)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/vqe/vqe.py", line 254, in _energy_evaluation
input_circuit = self._var_form.construct_circuit(parameters)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/qaoa/varform.py", line 60, in construct_circuit
circuit += self._cost_operator.evolve(None, gamma, 'circuit', 1, quantum_registers=q)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 1369, in evolve
slice_pauli_list, evo_time, num_time_slices, quantum_registers
File "/root/anaconda3/lib/python3.6/site-packages/qiskit_aqua/operator.py", line 1185, in construct_evolution_circuit
qc.u1(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/extensions/standard/u1.py", line 54, in u1
return self._attach(U1Gate(theta, q, self))
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/extensions/standard/u1.py", line 26, in init
super().init("u1", [theta], [qubit], circ)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/_gate.py", line 35, in init
super().init(name, param, args, circuit)
File "/root/anaconda3/lib/python3.6/site-packages/qiskit/_instruction.py", line 37, in init
self.param.append(Number(single_param))
File "/root/anaconda3/lib/python3.6/site-packages/sympy/core/numbers.py", line 547, in new
raise TypeError(msg % type(obj).name)
TypeError: expected str|int|long|float|Decimal|Number object but got 'matrix'

Suggested solutions

I would suggest implementing an error handling for the ValueError here, but I am not certain of how to solve the this specific problem. For the Qaoa algorithm error, I am not certain what why it is giving a TypeError in this specific case.

Allow customized compile in Aqua algorithms

What is the expected enhancement?

Currently Aqua uses wrapper.compile() in Terra. This function is a bit restrictive as is, because you can only choose to skip_transpiler or go through the default transpiler flow.

We will update this function to take a PassManager argument (Issue #1083 in Terra).

When that is done, can we also update the compile of Aqua to expose this? The skip_transpiler will then just be identical to passing an empty pass manager: pass_manager=PassManager().

Remove backends from params in run_algroithm

What is the expected enhancement?

Remove backends from params in run_algroithm

from qiskit_aqua import run_algorithm
from qiskit import IBMQ, Aer, ThirdPartyProvider


sat_cnf = """
c Example DIMACS 3-sat
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
"""

algo_params = {
 "problem": { "name": "search" },
 "algorithm": { "name": "Grover" },
 "oracle": { "name": "SAT", "cnf": sat_cnf },
}
IBMQ.load_accounts()
backend = IBMQ.get_backend("qasm_simulator")
result = run_algorithm(algo_params, backend=backend)
print(result["result"])

backend = Aer.get_backend("qasm_simulator")
result = run_algorithm(algo_params, backend=backend)
print(result["result"])

third_party = ThirdPartyProvider("some_login_details")
backend = third_party.get_backend("qasm_simulator")
result = run_algorithm(algo_params, backend=backend)
print(result["result"])

Make SVM Kernels a Pluggable Entity in Aqua AI

Expected Behavior

This is mainly a refactoring issue, where the advantage is that by making SVM Kernels as pluggable entities, researchers and developers who want to extend Aqua will have an easy interface to swap kernels in AI.

Current Behavior

Currently, kernels are hardcoded inside the SVM Q Kernel algorithm.

Possible Solution

Make SVM Kernels pluggable entities, such as algorithms, optimizers, variational forms, Grover oracles, IQFTs and initial states.

Steps to Reproduce (for bugs)

N/A

Context

The goal is to continue to promote the modular and extensible nature of Qiskit Aqua.

Your Environment

  • Version used: Aqua 0.1.2
  • Environment name and version (e.g. Python 3.6.1): Python >3.5
  • Operating System and version: Mac OS, Linux, Windows

internal parallelization of optimizer

This is requested by Antonio.

In p_bfgs https://github.com/Qiskit/qiskit-acqua/blob/master/qiskit_acqua/utils/optimizers/p_bfgs.py, we run multiple optimizers in parallel (embarassing parallelism).

It turns out we can parallelize the internal of the optimizer, which would lead to much better performance. At each point x, the optimizer needs to evaluate f(x') at a neighbor x' and compute the gradient (f(x')-f(x))/(x'-x). In general, the optimizer needs to evaluate 2N neighbors where N stands for the dimension. The evaluation of the 2N neighbors can be parallelized since they do not depend on each other.

In theory, this leads to 2N times speedup. In practice, this leads to C speedup, where C stands for the number of cores.

In terms of the implementation, we should choose the simplest optimizer.
And we simply follow the parallelism style in p_bfgs because it is simple and allows the parallelization of both the compiling and the execution.

If instead we follow the qiskit interface for multiple circuits, it will complicate the coding since we will have to modify the eval() function to merge multiple circuits into one job. Besides, this does not support the parallelization of compiling for now.

Add random circuit generator

What is the expected behavior?

The random circuit generator has been floating around qiskit in the form of a script. I encountered it in the Qiskit developer challenge.

  1. The version at https://github.com/Qiskit/openqasm/blob/7a1d95c5b610e828e6e97963b4ad40fbbc69959f/benchmarks/quantum_volume/quantum_volume.py comes closest to what I encountered there. Another, similar version is found in Qiskit/qiskit#574
  2. There is a newer variant that does something quite different at https://github.com/Qiskit/qiskit-terra/blob/2582fae6a3cf020f5715d8ed58b492eb91a7604d/tools/random_qasm_generator.py

I'd suggest adding such a random circuit generator to Aqua. It can be used for testing and for benchmarking. I prefer the first variant, since the depth is somewhat guaranteed. The parameter depth in the latter variant is somewhat of a misnomer since the output circuit does not have the given depth.

My experience

Personally, I've been using it in my mapper project (related to the Developer Challenge) to see how well the mapper performs on "Random" circuits. As it turns out, random circuits as generated by this tool are quite different from the circuits for other quantum algorithms.

Undefined name 't' on line 63 of stableset.py

Informations

What is the current behavior?

flake8 testing of https://github.com/Qiskit/aqua on Python 3.7.0

$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics

./qiskit_aqua/ising/stableset.py:63:73: F821 undefined name 't'
                        outfile.write('{} {} {}\n'.format(i + 1, j + 1, t))
                                                                        ^
1     F821 undefined name 't'
1

https://github.com/Qiskit/aqua/blob/master/qiskit_aqua/ising/stableset.py#L63

Steps to reproduce the problem

$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics

What is the expected behavior?

No errors.

Suggested solutions

update documentation about backend setting

As title.
After #63 is merged, more setting can set now.
Please refer to https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/wrapper/_wrapper.py#L298

New backend schema is here:
https://github.com/Qiskit/aqua/blob/master/qiskit_aqua/parser/input_schema.json#L32

Expected Behavior

Current Behavior

Possible Solution

Steps to Reproduce (for bugs)

Context

Your Environment

  • Version used:
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version:

Ising converters cleanup

Translators of various problems to Ising currently having duplicated code in these files. Refactoring is needed to eliminate this code and better structure the modules accordingly.

Have QPE work for unitaries, not only Hamiltonians

As suggested by Jay in last application meeting. The target unitary could be described in terms of a quantum circuit. To be used as a subroutine in the context of a more complex algorithm, we need a QPE function that takes in a set of quantum registers which are already used by said algorithm and a circuit describing the unitary, and then returns a QPE circuit defined on input registers. Said circuit can then be appended to other circuits produced by the complex super-routine.
An agnostic way to do the controlled unitary is to control every gate in the argument circuit.

A stand alone, unitary-based QPE algorithm can call this core QPE function.

I think the best option for the phase register is to be initialized outside the QPE function - even if is not used outside QPE function - , and passed in as argument. In general I think it is good practice to initialize all quantum registers at beginning of given algorithm, so the most logical use of QPE function inside a more complex algorithm is to have all registers passed in as arguments.

An alternative way of having registers as arguments is to import them from the argument circuit - this is debatable I think.

The QPE core function should initialize a new quantum circuit with the registers passed as arguments, not just append a circuit to an argument circuit passed in.
In fact the circuit appending should be done outside the core QPE function, in the super-routine. The reason for this is that in some cases in the super-routine that uses QPE we need to invert the QPE circuit, so we need to have it as a separate object, to be fed to an eventual circuit.invert() method.

The newest Terra breaks Aqua

Informations

Known breaks:

  • cnx.py, something wrong with composite gate
  • Pauli class, use z and x vectors rather than v and w, and do not modify the vector directly. or whereever use pauli string directly, since the order of pauli string is reversed for new Terra.
  • QuantumCircuits, get_cregs() and get_qregs() are became properties cregs and qregs
  • custom.py CustomInitialState is not able to unroll gates to basis gates
  • all exported Operator JSON, since the pauli order should be reversed.
  • fix the import of Pauli

show the summary of submitted circuits

Due to the fact that users might interest the scale of the quantum circuits they are running, it will be nice to summarize the circuits.

Expected Behavior

Print out the summary of submitted circuits in the DEBUG level.

Current Behavior

Possible Solution

We can get width, size, depth from the to-be-submitted circuit objects.
And we can try to get those stats right after we submit jobs since we wait for results, it is a good place to summarize the circuits.

Context

Feature request.

support sub and scaling for Operator

What is the expected enhancement?

let operator overloads - and -=, the current version only supports + and +=
On the other hand, support a method to apply a constant scale on the coefficient of an Operator.

bug in operator.py?

stack trace

Traceback (most recent call last):
  File "/Applications/PyCharm Edu.app/Contents/helpers/pydev/pydevd.py", line 1556, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm Edu.app/Contents/helpers/pydev/pydevd.py", line 940, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm Edu.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/ising/testgraphpartition.py", line 16, in <module>
    qubitOp, offset = graphpartition.get_graphpartition_qubitops(w)
  File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/ising/graphpartition.py", line 113, in get_graphpartition_qubitops
    return Operator(paulis=pauli_list), shift
  File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/operator.py", line 65, in __init__
    self._simplify_paulis()
  File "/Users/liup/quantum/qiskit-acqua/qiskit_acqua/operator.py", line 217, in _simplify_paulis
    paulis[idy][0] += self._paulis[idx][0]
TypeError: 'tuple' object does not support item assignment

Note: paulis[idy][0] is a tuple.

how to reproduce it?

You need to trigger the _simplify_paulis() method to trigger the bug, which is not easy.
To reproduce the bug, you can replace the get_maxcut_qubitops() method in maxcut.py as the following. The replacement does not make any logical sense but will help trigger the bug.

def get_maxcut_qubitops(weight_matrix):
    """Generate Hamiltonian for the maximum stableset in a graph.

    Args:
        weight_matrix (numpy.ndarray) : adjacency matrix.

    Returns:
        operator.Operator, float: operator for the Hamiltonian and a
        constant shift for the obj function.

    """
    num_nodes = len(weight_matrix)
    pauli_list = []
    shift = 0

    for i in range(num_nodes):
        for j in range(i):
            if (weight_matrix[i,j] != 0):
                wp = np.zeros(num_nodes)
                vp = np.zeros(num_nodes)
                vp[i] = 1
                vp[j] = 1
                pauli_list.append((-0.5, Pauli(vp, wp)))
                # shift += 0.5

    for i in range(num_nodes):
        for j in range(num_nodes):
            if i != j:
                wp = np.zeros(num_nodes)
                vp = np.zeros(num_nodes)
                vp[i] = 1
                vp[j] = 1
                pauli_list.append((1, Pauli(vp, wp)))
            # else:
            #     shift += 1
    return Operator(paulis=pauli_list), shift

expose all execute setting of terra to aqua

As title

Expected Behavior

Current Behavior

Possible Solution

Steps to Reproduce (for bugs)

Context

Your Environment

  • Version used:
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version:

qiskit proxy for buffering the circuits

instead of directly sending the requests to the HPC simulator or the qiskit simulator, we send them in parallel to the proxy, which will assmebly them into one job and send it to the simulator.

Expected Behavior

Current Behavior

Possible Solution

Steps to Reproduce (for bugs)

Context

Your Environment

  • Version used:
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version:

Tests are failing

Informations

  • Qiskit Aqua 0.2.0:
  • Python 3.6.6:
  • Fedora 28:

What is the current behavior?

When running the unit tests everything fails upon collection of the tests since it's trying to access qiskit modules which do not exist.

ModuleNotFoundError: No module named 'qiskit.wrapper.credentials'

Steps to reproduce the problem

pytest .

What is the expected behavior?

Smooth running unit tests.

Suggested solutions

It might possible have to do with the Qiskit version (I used pip3 for installation). Unit tests need to be updated.

Find Z2 symmetries fails if no symmetry is found

Informations

  • Qiskit Aqua version: master branch
  • Python version: 3.6
  • Operating system: macOS

What is the current behavior?

program crashed

Steps to reproduce the problem

What is the expected behavior?

return an empty list if no symmetry is found

Suggested solutions

act as expected behavior

Circuit stacking limit in Operator class

We should take into account that one cannot stack more than a certain number of circuits on a single job under the "paulis" and "grouped_paulis" mode in the eval method for Operator class, both with finite number of shots and with the statevector simulator.

qiskit_aqua.ising module import problem

Informations

  • Qiskit Aqua version: 0.3
  • Python version: 3.7.0
  • Operating system: ubuntu

What is the current behavior?

ModuleNotFoundError: No module named 'qiskit_aqua.ising'

Steps to reproduce the problem

run 'from qiskit_aqua.ising import maxcut, tsp'

What is the expected behavior?

module imported successfully

Suggested solutions


What is the expected behavior?


What is the expected enhancement?

Thank you!

[enhancement] simpler way to generate cnf strings/files for grover's algorithm

To make implementing grover's algorithm in code faster, there should be a simpler way to generate cnf's from a unstructured array and a list of target items.

Expected Behavior

The ideal end goal is for a black box function that outputs a cnf to use with acqua's grover implementation after taking in two parameters (a list to query, a list of targets to search for).

Current Behavior

Possible Solution

I plan for there to be several intermediate methods before fulfilling the final goal. For example, one key intermediate function would be to generate bitstring solutions and bitstring non-solutions from a list to query and a list of targets. The value of the bitstring converted to decimal would correspond to an index of the query list.
Also, another simpler function to implement that could serve as a stepping stone to the final goal would be to make a black box that takes in N, the size of the query list/database, and a list T of the target indices that are solutions, to output a cnf for acqua's grover algorithm

Context

Feature request.

Support auto recovery of internet connection error

What is the expected behavior?

For the iterative algorithm, like VQE, it submits the circuits to the backend multiple times; however, sometimes the local machine might lose internet connection or other reasons, and then the program is crashed.
This leads all intermediate results gone.

One aspect to resolve this issue is having a robust querying for the result from the backend.
Another one is generating the checkpoint for the iterative algorithm, and then users can resume that later.

I would like to work on the first one.

Operator will crash if the backend is None

Newly-added checking for max number of circuits might crash the Operator since backend sometimes is None.

Expected Behavior

Current Behavior

Possible Solution

if isinstance(input_circuit, np.ndarray):
            avg = self._eval_directly(input_circuit)
            std_dev = 0.0
        else:
            if backend.startswith('local'):
                self.MAX_CIRCUITS_PER_JOB = sys.maxsize
            if "statevector" in backend:
                execute_config['shots'] = 1
                avg = self._eval_with_statevector(operator_mode, input_circuit, backend, execute_config)
                std_dev = 0.0
            else:
                avg, std_dev = self._eval_multiple_shots(operator_mode, input_circuit, backend, execute_config, qjob_config)

Steps to Reproduce (for bugs)

  1. Use ExactEigensolver with Aqua-chem

Context

Your Environment

  • Version used:
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.