Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

Commit

Permalink
Merge branch 'master' into statefn-eval
Browse files Browse the repository at this point in the history
  • Loading branch information
manoelmarques authored Aug 21, 2020
2 parents 904812c + 90a764f commit 06ebbbf
Show file tree
Hide file tree
Showing 32 changed files with 125 additions and 86 deletions.
1 change: 1 addition & 0 deletions .pylintdict
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,7 @@ wigner
wikipedia
workq
wrt
wvf
xatol
xixj
xopt
Expand Down
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,19 @@ 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](https://qiskit.org/documentation/apidoc/qiskit.aqua.algorithms.minimum_eigen_solvers.cplex.html)
to allow the use of the `ClassicalCPLEX` classical solver algorithm. `pip install cplex` may be used
as an alternative.
* **PyTorch**, may be installed either using command `pip install torch` to install the
to allow the use of the `ClassicalCPLEX` 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](https://pytorch.org/get-started/locally/). 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[cvpxy]` to enable use of the
`QSVM` and the classical `SklearnSVM` algorithms.


### Creating Your First Quantum Program in Qiskit Aqua
Expand Down Expand Up @@ -399,8 +405,8 @@ validation, and benchmarking.

### Optional Installs

* **IBM CPLEX** may be installed using `pip install cplex` to allow the use of the `CplexOptimzer`
classical solver algorithm, as well as enabling the reading of `LP` files.
* **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

Expand Down Expand Up @@ -485,7 +491,7 @@ This project adheres to Qiskit's [code of conduct](./CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code.

We use [GitHub issues](https://github.com/Qiskit/qiskit-aqua/issues) for tracking requests and bugs. Please
[join the Qiskit Slack community](https://join.slack.com/t/qiskit/shared_invite/enQtODQ2NTIyOTgwMTQ3LTI0NzM2NzkzZjJhNDgzZjY5MTQzNDY3MGNiZGQzNTNkZTE4Nzg1MjMwMmFjY2UwZTgyNDlmYWQwYmZjMjE1ZTM)
[join the Qiskit Slack community](https://ibm.co/joinqiskitslack)
and use the [Aqua Slack channel](https://qiskit.slack.com/messages/aqua) for discussion and simple questions.
For questions that are more suited for a forum, we use the **Qiskit** tag in [Stack Overflow](https://stackoverflow.com/questions/tagged/qiskit).

Expand Down
12 changes: 6 additions & 6 deletions qiskit/aqua/algorithms/amplitude_estimators/mlae.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ def _get_hits(self) -> Tuple[List[float], List[int]]:
for c in self._ret['counts']:
one_hits += [c.get('1', 0)] # return 0 if no key '1' found
all_hits += [sum(c.values())]
except KeyError:
raise AquaError('Call run() first!')
except KeyError as ex:
raise AquaError('Call run() first!') from ex

return one_hits, all_hits

Expand Down Expand Up @@ -227,8 +227,8 @@ def _compute_fisher_information(self, a: Optional[float] = None,
if a is None:
try:
a = self._ret['value']
except KeyError:
raise KeyError('Call run() first!')
except KeyError as ex:
raise KeyError('Call run() first!') from ex

# Corresponding angle to the value a (only use real part of 'a')
theta_a = np.arcsin(np.sqrt(np.real(a)))
Expand Down Expand Up @@ -279,8 +279,8 @@ def _fisher_confint(self, alpha: float = 0.05, observed: bool = False) -> List[f
fisher_information = None
try:
fisher_information = self._ret['fisher_information']
except KeyError:
raise AssertionError("Call run() first!")
except KeyError as ex:
raise AssertionError("Call run() first!") from ex

if observed:
fisher_information = self._compute_fisher_information(observed=True)
Expand Down
4 changes: 2 additions & 2 deletions qiskit/aqua/algorithms/minimum_eigen_solvers/vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,10 @@ def _check_operator_varform(self):
try:
self.var_form.num_qubits = self.operator.num_qubits
self._var_form_params = sorted(self.var_form.parameters, key=lambda p: p.name)
except AttributeError:
except AttributeError as ex:
raise AquaError("The number of qubits of the variational form does not match "
"the operator, and the variational form does not allow setting "
"the number of qubits using `num_qubits`.")
"the number of qubits using `num_qubits`.") from ex

@VQAlgorithm.optimizer.setter # type: ignore
def optimizer(self, optimizer: Optimizer):
Expand Down
4 changes: 2 additions & 2 deletions qiskit/aqua/circuits/phase_estimation_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ def construct_circuit(
if self._iqft.num_qubits != len(a): # check if QFT has the right size
try: # try resizing
self._iqft.num_qubits = len(a)
except AttributeError:
except AttributeError as ex:
raise ValueError('The IQFT cannot be resized and does not have the '
'required size of {}'.format(len(a)))
'required size of {}'.format(len(a))) from ex

if hasattr(self._iqft, 'do_swaps'):
self._iqft.do_swaps = False
Expand Down
4 changes: 2 additions & 2 deletions qiskit/aqua/components/eigs/eigs_qpe.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ def apply_ne_qft(ne_qft):
if ne_qft.num_qubits != len(qs):
try: # try resizing
ne_qft.num_qubits = len(qs)
except AttributeError:
except AttributeError as ex:
raise ValueError('The IQFT cannot be resized and does not have the '
'required size of {}'.format(len(qs)))
'required size of {}'.format(len(qs))) from ex

if hasattr(ne_qft, 'do_swaps'):
ne_qft.do_swaps = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def __init__(self, n_features: int = 1, n_out: int = 1) -> None:
n_out: n out
"""

super(DiscriminatorNet, self).__init__()
super().__init__()
self.n_features = n_features

self.hidden0 = nn.Sequential(
Expand Down
5 changes: 3 additions & 2 deletions qiskit/aqua/components/oracles/logical_expression_oracle.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,9 @@ def __init__(self,
try:
expression = LogicalExpressionOracle._dimacs_cnf_to_expression(expression)
raw_expr = parse_expr(expression)
except Exception:
raise AquaError('Failed to parse the input expression: {}.'.format(orig_expression))
except Exception as ex:
raise AquaError(
'Failed to parse the input expression: {}.'.format(orig_expression)) from ex
self._expr = raw_expr
self._process_expr()
self.construct_circuit()
Expand Down
5 changes: 4 additions & 1 deletion qiskit/aqua/operators/list_ops/list_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,10 @@ def primitive_strings(self) -> Set[str]:

@property
def num_qubits(self) -> int:
return self.oplist[0].num_qubits
num_qubits0 = self.oplist[0].num_qubits
if not all(num_qubits0 == op.num_qubits for op in self.oplist):
raise ValueError('Operators in ListOp have differing numbers of qubits.')
return num_qubits0

def add(self, other: OperatorBase) -> OperatorBase:
if self == other:
Expand Down
4 changes: 2 additions & 2 deletions qiskit/aqua/operators/list_ops/summed_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@ def to_legacy_op(self, massive: bool = False) -> LegacyBaseOperator:
if isinstance(self.coeff, ParameterExpression):
try:
coeff = float(self.coeff)
except TypeError:
except TypeError as ex:
raise TypeError('Cannot convert Operator with unbound parameter {} to Legacy '
'Operator'.format(self.coeff))
'Operator'.format(self.coeff)) from ex
else:
coeff = cast(float, self.coeff)

Expand Down
4 changes: 2 additions & 2 deletions qiskit/aqua/operators/operator_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,8 +488,8 @@ def _unroll_param_dict(value_dict: Dict[Union[ParameterExpression, ParameterVect
OperatorBase._get_param_dict_for_index(unrolled_value_dict, # type: ignore
i))
return unrolled_value_dict_list
except IndexError:
raise AquaError('Parameter binding lists must all be the same length.')
except IndexError as ex:
raise AquaError('Parameter binding lists must all be the same length.') from ex
return unrolled_value_dict # type: ignore

@staticmethod
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/operators/primitive_ops/circuit_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def compose(self, other: OperatorBase) -> OperatorBase:
else:
return CircuitOp(new_qc, coeff=self.coeff * other.coeff)

return super(CircuitOp, self).compose(other)
return super().compose(other)

def to_matrix(self, massive: bool = False) -> np.ndarray:
if self.num_qubits > 16 and not massive:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/aqua/operators/primitive_ops/matrix_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def compose(self, other: OperatorBase) -> OperatorBase:
return MatrixOp(self.primitive.compose(other.primitive, front=True), # type: ignore
coeff=self.coeff * other.coeff)

return super(MatrixOp, self).compose(other)
return super().compose(other)

def to_matrix(self, massive: bool = False) -> np.ndarray:
return self.primitive.data * self.coeff # type: ignore
Expand Down
6 changes: 3 additions & 3 deletions qiskit/aqua/operators/primitive_ops/pauli_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def compose(self, other: OperatorBase) -> OperatorBase:
if isinstance(other, (CircuitOp, CircuitStateFn)):
return self.to_circuit_op().compose(other)

return super(PauliOp, self).compose(other)
return super().compose(other)

def to_matrix(self, massive: bool = False) -> np.ndarray:
if self.num_qubits > 16 and not massive:
Expand Down Expand Up @@ -283,9 +283,9 @@ def to_legacy_op(self, massive: bool = False) -> WeightedPauliOperator:
if isinstance(self.coeff, ParameterExpression):
try:
coeff = float(self.coeff)
except TypeError:
except TypeError as ex:
raise TypeError('Cannot convert Operator with unbound parameter {} to Legacy '
'Operator'.format(self.coeff))
'Operator'.format(self.coeff)) from ex
else:
coeff = cast(float, self.coeff)
return WeightedPauliOperator(paulis=[(coeff, self.primitive)]) # type: ignore
2 changes: 1 addition & 1 deletion qiskit/aqua/utils/dataset_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def split_dataset_to_data_and_labels(dataset, class_names=None):
labels.append(class_to_label[class_name])
except Exception as ex: # pylint: disable=broad-except
raise KeyError('The dataset has different class names to '
'the training data. error message: {}'.format(ex))
'the training data. error message: {}'.format(ex)) from ex
data = np.asarray(data)
labels = np.asarray(labels)
if class_names is None:
Expand Down
12 changes: 6 additions & 6 deletions qiskit/chemistry/drivers/fcidumpd/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ def parse(fcidump: str) -> Dict[str, Any]:
try:
with open(fcidump, 'r') as file:
fcidump_str = file.read()
except OSError:
raise QiskitChemistryError("Input file '{}' cannot be read!".format(fcidump))
except OSError as ex:
raise QiskitChemistryError("Input file '{}' cannot be read!".format(fcidump)) from ex

output = {} # type: Dict[str, Any]

Expand Down Expand Up @@ -139,18 +139,18 @@ def parse(fcidump: str) -> Dict[str, Any]:
try:
hij_elements.remove((i-1, a-1))
hij[i-1][a-1] = x
except KeyError:
except KeyError as ex:
if _uhf:
hij_b_elements.remove((i-1, a-1))
hij_b[i-1-norb][a-1-norb] = x
else:
raise QiskitChemistryError("Unkown 1-electron integral indices encountered in \
'{}'".format((i, a)))
'{}'".format((i, a))) from ex
else:
try:
hijkl_elements.remove((i-1, a-1, j-1, b-1))
hijkl[i-1][a-1][j-1][b-1] = x
except KeyError:
except KeyError as ex:
if _uhf:
try:
hijkl_ab_elements.remove((i-1, a-1, j-1, b-1))
Expand All @@ -164,7 +164,7 @@ def parse(fcidump: str) -> Dict[str, Any]:
hijkl_bb[i-1-norb][a-1-norb][j-1-norb][b-1-norb] = x
else:
raise QiskitChemistryError("Unkown 2-electron integral indices encountered in \
'{}'".format((i, a, j, b)))
'{}'".format((i, a, j, b))) from ex

# iterate over still empty elements in 1-electron matrix and populate with symmetric ones
# if any elements are not populated these will be zero
Expand Down
6 changes: 3 additions & 3 deletions qiskit/chemistry/drivers/gaussiand/gaussiandriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def _parse_matrix_file(self, fname, useao2e=False):
if mnfe.name == 'qcmatrixio' else str(mnfe)

logger.info(msg)
raise QiskitChemistryError(msg)
raise QiskitChemistryError(msg) from mnfe

mel = MatEl(file=fname)
logger.debug('MatrixElement file:\n%s', mel)
Expand Down Expand Up @@ -344,11 +344,11 @@ def _run_g16(cfg):
process = Popen(GAUSSIAN_16, stdin=PIPE, stdout=PIPE, universal_newlines=True)
stdout, _ = process.communicate(cfg)
process.wait()
except Exception:
except Exception as ex:
if process is not None:
process.kill()

raise QiskitChemistryError('{} run has failed'.format(GAUSSIAN_16_DESC))
raise QiskitChemistryError('{} run has failed'.format(GAUSSIAN_16_DESC)) from ex

if process.returncode != 0:
errmsg = ""
Expand Down
4 changes: 2 additions & 2 deletions qiskit/chemistry/drivers/psi4d/psi4driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,11 @@ def _run_psi4(input_file, output_file):
stdout=subprocess.PIPE, universal_newlines=True)
stdout, _ = process.communicate()
process.wait()
except Exception:
except Exception as ex:
if process is not None:
process.kill()

raise QiskitChemistryError('{} run has failed'.format(PSI4))
raise QiskitChemistryError('{} run has failed'.format(PSI4)) from ex

if process.returncode != 0:
errmsg = ""
Expand Down
2 changes: 1 addition & 1 deletion qiskit/chemistry/qmolecule.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ def twoe_to_spin(mohijkl, mohijkl_bb=None, mohijkl_ba=None, threshold=1E-12):
return moh2_qubit

symbols = [
# pylint: disable=bad-whitespace
# pylint: disable=bad-option-value,bad-whitespace
'_',
'H', 'He',
'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',
Expand Down
20 changes: 10 additions & 10 deletions qiskit/finance/data_providers/_base_data_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ def get_mean_vector(self) -> np.ndarray:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
except AttributeError:
except AttributeError as ex:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
) from ex
self.mean = np.mean(self._data, axis=1)
return self.mean

Expand Down Expand Up @@ -106,10 +106,10 @@ def get_period_return_mean_vector(self) -> np.ndarray:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
except AttributeError:
except AttributeError as ex:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
) from ex
_div_func = np.vectorize(BaseDataProvider._divide)
period_returns = _div_func(np.array(self._data)[:, 1:], np.array(self._data)[:, :-1]) - 1
self.period_return_mean = np.mean(period_returns, axis=1)
Expand All @@ -130,10 +130,10 @@ def get_covariance_matrix(self) -> np.ndarray:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
except AttributeError:
except AttributeError as ex:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
) from ex
self.cov = np.cov(self._data, rowvar=True)
return self.cov

Expand All @@ -152,10 +152,10 @@ def get_period_return_covariance_matrix(self) -> np.ndarray:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
except AttributeError:
except AttributeError as ex:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
) from ex
_div_func = np.vectorize(BaseDataProvider._divide)
period_returns = _div_func(np.array(self._data)[:, 1:], np.array(self._data)[:, :-1]) - 1
self.period_return_cov = np.cov(period_returns)
Expand All @@ -176,10 +176,10 @@ def get_similarity_matrix(self) -> np.ndarray:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
except AttributeError:
except AttributeError as ex:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
) from ex
self.rho = np.zeros((self._n, self._n))
for i_i in range(0, self._n):
self.rho[i_i, i_i] = 1.
Expand Down
Loading

0 comments on commit 06ebbbf

Please sign in to comment.