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

Commit 9c2c86c

Browse files
Merge pull request #1422 from manoelmarques/stable-0.8.1
[Stable] Qiskit Aqua Release 0.8.1
2 parents 5d7a8cb + c526bdb commit 9c2c86c

File tree

99 files changed

+429
-165
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

99 files changed

+429
-165
lines changed

.github/actions/install-libraries/action.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,4 @@ runs:
2626
pip install -U pip
2727
pip install -U setuptools wheel
2828
fi
29-
# sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
3029
shell: bash

.github/actions/install-master-dependencies/action.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ runs:
2424
pip install https://github.com/Qiskit/qiskit-terra/archive/master.zip
2525
pip install https://github.com/Qiskit/qiskit-ignis/archive/master.zip
2626
pip install https://github.com/Qiskit/qiskit-ibmq-provider/archive/master.zip
27-
# sudo apt-get -y update
2827
sudo apt-get -y install g++-7
2928
sudo apt-get -y install libopenblas-dev
3029
git clone https://github.com/Qiskit/qiskit-aer.git /tmp/qiskit-aer

.github/workflows/main.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,9 @@ jobs:
250250
if [ -f "$HOME/miniconda/etc/profile.d/conda.sh" ]; then
251251
source "$HOME/miniconda/etc/profile.d/conda.sh"
252252
conda activate
253+
# PSI4 has problems with dataclasses
254+
pip uninstall -y dataclasses
253255
fi
254-
# sudo apt-get -y update
255256
sudo apt-get -y install libgfortran5
256257
pip install https://github.com/rpmuller/pyquante2/archive/master.zip
257258
pip install pyscf
@@ -461,7 +462,6 @@ jobs:
461462
shell: bash
462463
- name: Install Dependencies
463464
run: |
464-
# sudo apt-get -y update
465465
sudo apt-get -y install libgfortran5
466466
pip install https://github.com/rpmuller/pyquante2/archive/master.zip
467467
pip install pyscf

qiskit/aqua/VERSION.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0.8.0
1+
0.8.1

qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,10 @@ def train(self, data, labels):
7676
"""
7777
scaling = 1.0 if self._qalgo.quantum_instance.is_statevector else None
7878
kernel_matrix = self._qalgo.construct_kernel_matrix(data)
79+
lambda2 = self._qalgo.lambda2
7980
labels = labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1
8081
labels = labels.astype(np.float)
81-
[alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling)
82+
[alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling, lambda2=lambda2)
8283
support_index = np.where(support)
8384
alphas = alpha[support_index]
8485
svms = data[support_index]

qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap],
8080
test_dataset: Optional[Dict[str, np.ndarray]] = None,
8181
datapoints: Optional[np.ndarray] = None,
8282
multiclass_extension: Optional[MulticlassExtension] = None,
83+
lambda2: float = 0.001,
8384
quantum_instance: Optional[
8485
Union[QuantumInstance, BaseBackend, Backend]] = None) -> None:
8586
"""
@@ -90,6 +91,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap],
9091
datapoints: Prediction dataset.
9192
multiclass_extension: If number of classes is greater than 2 then a multiclass scheme
9293
must be supplied, in the form of a multiclass extension.
94+
lambda2: L2 norm regularization factor
9395
quantum_instance: Quantum Instance or Backend
9496
9597
Raises:
@@ -118,6 +120,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap],
118120
self.setup_training_data(training_dataset)
119121
self.setup_test_data(test_dataset)
120122
self.setup_datapoint(datapoints)
123+
self.lambda2 = lambda2
121124

122125
self.feature_map = feature_map
123126
self.num_qubits = self.feature_map.num_qubits

qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import numpy as np
1818

19-
from qiskit.aqua.operators import (OperatorBase, X, I, H, Zero, CircuitStateFn,
19+
from qiskit.aqua.operators import (OperatorBase, X, I, H, CircuitStateFn,
2020
EvolutionFactory, LegacyBaseOperator)
2121
from qiskit.aqua.components.variational_forms import VariationalForm
2222
from qiskit.aqua.components.initial_states import InitialState
@@ -80,13 +80,12 @@ def construct_circuit(self, parameters, q=None):
8080
self.num_parameters, len(parameters)
8181
))
8282

83-
circuit = (H ^ self._num_qubits)
8483
# initialize circuit, possibly based on given register/initial state
8584
if self._initial_state is not None:
86-
init_state = CircuitStateFn(self._initial_state.construct_circuit('circuit'))
85+
stateVector = CircuitStateFn(self._initial_state.construct_circuit('circuit'))
86+
circuit = stateVector.to_circuit_op()
8787
else:
88-
init_state = Zero
89-
circuit = circuit.compose(init_state)
88+
circuit = (H ^ self._num_qubits)
9089

9190
for idx in range(self._p):
9291
circuit = (self._cost_operator * parameters[idx]).exp_i().compose(circuit)

qiskit/aqua/algorithms/quantum_algorithm.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ def run(self,
6060
AquaError: If a quantum instance or backend has not been provided
6161
"""
6262
if quantum_instance is None and self.quantum_instance is None:
63-
raise AquaError("Quantum device or backend "
64-
"is needed since you are running quantum algorithm.")
63+
raise AquaError("A QuantumInstance or Backend "
64+
"must be supplied to run the quantum algorithm.")
6565
if isinstance(quantum_instance, (BaseBackend, Backend)):
6666
self.set_backend(quantum_instance, **kwargs)
6767
else:

qiskit/aqua/components/neural_networks/pytorch_discriminator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def load_model(self, load_dir: str):
9090
Args:
9191
load_dir: file with stored pytorch discriminator model to be loaded
9292
"""
93-
torch.load(load_dir)
93+
self._discriminator = torch.load(load_dir)
9494

9595
@property
9696
def discriminator_net(self):

qiskit/aqua/components/optimizers/nlopts/nloptimizer.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ def optimize(self, num_vars, objective_function, gradient_function=None,
9393
variable_bounds=None, initial_point=None):
9494
super().optimize(num_vars, objective_function,
9595
gradient_function, variable_bounds, initial_point)
96+
if variable_bounds is None:
97+
variable_bounds = [(None, None)] * num_vars
9698
return self._minimize(self._optimizer_names[self.get_nlopt_optimizer()],
9799
objective_function,
98100
variable_bounds,
@@ -101,7 +103,7 @@ def optimize(self, num_vars, objective_function, gradient_function=None,
101103
def _minimize(self,
102104
name: str,
103105
objective_function: Callable,
104-
variable_bounds: Optional[List[Tuple[float, float]]] = None,
106+
variable_bounds: Optional[List[Tuple[float, float]]],
105107
initial_point: Optional[np.ndarray] = None,
106108
max_evals: int = 1000) -> Tuple[float, float, int]:
107109
"""Minimize using objective function

qiskit/aqua/operators/converters/circuit_sampler.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from qiskit.providers import Backend
2222
from qiskit.circuit import QuantumCircuit, Parameter, ParameterExpression
2323
from qiskit import QiskitError
24-
from qiskit.aqua import QuantumInstance
24+
from qiskit.aqua import QuantumInstance, AquaError
2525
from qiskit.aqua.utils.backend_utils import is_aer_provider, is_statevector_backend
2626
from qiskit.aqua.operators.operator_base import OperatorBase
2727
from qiskit.aqua.operators.list_ops.list_op import ListOp
@@ -165,6 +165,8 @@ def convert(self,
165165
166166
Returns:
167167
The converted Operator with CircuitStateFns replaced by DictStateFns or VectorStateFns.
168+
Raises:
169+
AquaError: if extracted circuits are empty.
168170
"""
169171
if self._last_op is None or id(operator) != id(self._last_op):
170172
# Clear caches
@@ -181,6 +183,11 @@ def convert(self,
181183
if not self._circuit_ops_cache:
182184
self._circuit_ops_cache = {}
183185
self._extract_circuitstatefns(self._reduced_op_cache)
186+
if not self._circuit_ops_cache:
187+
raise AquaError(
188+
'Circuits are empty. '
189+
'Check that the operator is an instance of CircuitStateFn or its ListOp.'
190+
)
184191

185192
if params:
186193
p_0 = list(params.values())[0] # type: ignore
@@ -243,8 +250,13 @@ def sample_circuits(self,
243250
244251
Returns:
245252
The dictionary mapping ids of the CircuitStateFns to their replacement StateFns.
253+
Raises:
254+
AquaError: if extracted circuits are empty.
246255
"""
247-
if circuit_sfns or not self._transpiled_circ_cache:
256+
if not circuit_sfns and not self._transpiled_circ_cache:
257+
raise AquaError('CircuitStateFn is empty and there is no cache.')
258+
259+
if circuit_sfns:
248260
if self._statevector:
249261
circuits = [op_c.to_circuit(meas=False) for op_c in circuit_sfns]
250262
else:
@@ -266,14 +278,14 @@ def sample_circuits(self,
266278
start_time = time()
267279
ready_circs = self._prepare_parameterized_run_config(param_bindings)
268280
end_time = time()
269-
logger.info('Parameter conversion %.5f (ms)', (end_time - start_time) * 1000)
281+
logger.debug('Parameter conversion %.5f (ms)', (end_time - start_time) * 1000)
270282
else:
271283
start_time = time()
272284
ready_circs = [circ.assign_parameters(binding)
273285
for circ in self._transpiled_circ_cache
274286
for binding in param_bindings]
275287
end_time = time()
276-
logger.info('Parameter binding %.5f (ms)', (end_time - start_time) * 1000)
288+
logger.debug('Parameter binding %.5f (ms)', (end_time - start_time) * 1000)
277289
else:
278290
ready_circs = self._transpiled_circ_cache
279291

qiskit/aqua/operators/evolutions/trotterizations/trotter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,4 @@ def __init__(self,
2626
Args:
2727
reps: The number of times to repeat the Trotterization circuit.
2828
"""
29-
super().__init__(order=1, reps=1)
29+
super().__init__(order=1, reps=reps)

qiskit/aqua/operators/legacy/weighted_pauli_operator.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,19 @@ def to_opflow(self, reverse_endianness=False):
101101
pauli_ops = []
102102
for [w, p] in self.paulis:
103103
pauli = Pauli.from_label(str(p)[::-1]) if reverse_endianness else p
104-
# Adding the imaginary is necessary to handle the imaginary coefficients in UCCSD.
105-
# TODO fix these or add support for them in Terra.
106-
pauli_ops += [PrimitiveOp(pauli, coeff=np.real(w) + np.imag(w))]
104+
# This weighted pauli operator has the coeff stored as a complex type
105+
# irrespective of whether the value has any imaginary part or not.
106+
# For many operators the coeff will be real. Hence below the coeff is made real,
107+
# when creating the PrimitiveOp, since it can be stored then as a float, if its
108+
# value is real, i.e. has no imaginary part. This avoids any potential issues around
109+
# complex - but if there are complex coeffs then maybe that using the opflow
110+
# later will fail if it happens to be used where complex is not supported.
111+
# Now there are imaginary coefficients in UCCSD that would need to be handled
112+
# when this is converted to opflow (evolution of hopping operators) where currently
113+
# Terra does not handle complex.
114+
# TODO fix these or add support for them in Terra
115+
coeff = np.real(w) if np.isreal(w) else w
116+
pauli_ops += [PrimitiveOp(pauli, coeff=coeff)]
107117
return sum(pauli_ops)
108118

109119
@property

qiskit/aqua/operators/primitive_ops/circuit_op.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,8 @@ class CircuitOp(PrimitiveOp):
3535
"""
3636

3737
def __init__(self,
38-
primitive: Union[Instruction, QuantumCircuit] = None,
39-
coeff: Optional[Union[int, float, complex,
40-
ParameterExpression]] = 1.0) -> None:
38+
primitive: Union[Instruction, QuantumCircuit],
39+
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
4140
"""
4241
Args:
4342
primitive: The QuantumCircuit which defines the

qiskit/aqua/operators/primitive_ops/matrix_op.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
""" MatrixOp Class """
1414

15-
from typing import Union, Optional, Set, Dict, List, cast
15+
from typing import Union, Optional, Set, Dict, List, cast, get_type_hints
1616
import logging
1717
import numpy as np
1818
from scipy.sparse import spmatrix
@@ -40,8 +40,8 @@ class MatrixOp(PrimitiveOp):
4040
"""
4141

4242
def __init__(self,
43-
primitive: Union[list, np.ndarray, spmatrix, Operator] = None,
44-
coeff: Optional[Union[int, float, complex, ParameterExpression]] = 1.0) -> None:
43+
primitive: Union[list, np.ndarray, spmatrix, Operator],
44+
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
4545
"""
4646
Args:
4747
primitive: The matrix-like object which defines the behavior of the underlying function.
@@ -51,16 +51,18 @@ def __init__(self,
5151
TypeError: invalid parameters.
5252
ValueError: invalid parameters.
5353
"""
54+
primitive_orig = primitive
5455
if isinstance(primitive, spmatrix):
5556
primitive = primitive.toarray()
5657

5758
if isinstance(primitive, (list, np.ndarray)):
5859
primitive = Operator(primitive)
5960

6061
if not isinstance(primitive, Operator):
61-
raise TypeError(
62-
'MatrixOp can only be instantiated with MatrixOperator, '
63-
'not {}'.format(type(primitive)))
62+
type_hints = get_type_hints(MatrixOp.__init__).get('primitive')
63+
valid_cls = [cls.__name__ for cls in type_hints.__args__]
64+
raise TypeError(f"MatrixOp can only be instantiated with {valid_cls}, "
65+
f"not '{primitive_orig.__class__.__name__}'")
6466

6567
if not primitive.input_dims() == primitive.output_dims():
6668
raise ValueError('Cannot handle non-square matrices yet.')

qiskit/aqua/operators/primitive_ops/pauli_op.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class PauliOp(PrimitiveOp):
3939
"""
4040

4141
def __init__(self,
42-
primitive: Union[Pauli] = None,
42+
primitive: Union[Pauli],
4343
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
4444
"""
4545
Args:

qiskit/aqua/operators/primitive_ops/primitive_op.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,9 @@ class PrimitiveOp(OperatorBase):
4848
@staticmethod
4949
# pylint: disable=unused-argument
5050
def __new__(cls,
51-
primitive: Union[Instruction, QuantumCircuit, List,
52-
np.ndarray, spmatrix, MatrixOperator, Pauli] = None,
51+
primitive:
52+
Optional[Union[Instruction, QuantumCircuit, List,
53+
np.ndarray, spmatrix, MatrixOperator, Pauli]] = None,
5354
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> 'PrimitiveOp':
5455
""" A factory method to produce the correct type of PrimitiveOp subclass
5556
based on the primitive passed in. Primitive and coeff arguments are passed into
@@ -85,9 +86,10 @@ def __new__(cls,
8586
'factory constructor'.format(type(primitive)))
8687

8788
def __init__(self,
88-
primitive: Union[Instruction, QuantumCircuit, List,
89-
np.ndarray, spmatrix, MatrixOperator, Pauli] = None,
90-
coeff: Optional[Union[int, float, complex, ParameterExpression]] = 1.0) -> None:
89+
primitive:
90+
Optional[Union[Instruction, QuantumCircuit, List,
91+
np.ndarray, spmatrix, MatrixOperator, Pauli]] = None,
92+
coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None:
9193
"""
9294
Args:
9395
primitive: The operator primitive being wrapped.

qiskit/aqua/operators/state_fns/dict_state_fn.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def sample(self,
252252
shots: int = 1024,
253253
massive: bool = False,
254254
reverse_endianness: bool = False) -> dict:
255-
probs = np.array(list(self.primitive.values()))**2
255+
probs = np.square(np.abs(np.array(list(self.primitive.values()))))
256256
unique, counts = np.unique(aqua_globals.random.choice(list(self.primitive.keys()),
257257
size=shots,
258258
p=(probs / sum(probs))),

qiskit/aqua/operators/state_fns/operator_state_fn.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class OperatorStateFn(StateFn):
3434

3535
# TODO allow normalization somehow?
3636
def __init__(self,
37-
primitive: Union[OperatorBase] = None,
37+
primitive: OperatorBase = None,
3838
coeff: Union[int, float, complex, ParameterExpression] = 1.0,
3939
is_measurement: bool = False) -> None:
4040
"""

0 commit comments

Comments
 (0)