diff --git a/.github/actions/install-libraries/action.yml b/.github/actions/install-libraries/action.yml index caa12107c5..a8d420068c 100644 --- a/.github/actions/install-libraries/action.yml +++ b/.github/actions/install-libraries/action.yml @@ -26,5 +26,4 @@ runs: pip install -U pip pip install -U setuptools wheel fi - # sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test shell: bash diff --git a/.github/actions/install-master-dependencies/action.yml b/.github/actions/install-master-dependencies/action.yml index 261f43b0e7..bd910580e2 100644 --- a/.github/actions/install-master-dependencies/action.yml +++ b/.github/actions/install-master-dependencies/action.yml @@ -24,7 +24,6 @@ runs: pip install https://github.com/Qiskit/qiskit-terra/archive/master.zip pip install https://github.com/Qiskit/qiskit-ignis/archive/master.zip pip install https://github.com/Qiskit/qiskit-ibmq-provider/archive/master.zip - # sudo apt-get -y update sudo apt-get -y install g++-7 sudo apt-get -y install libopenblas-dev git clone https://github.com/Qiskit/qiskit-aer.git /tmp/qiskit-aer diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 017994a76d..f97328ba72 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -250,8 +250,9 @@ jobs: if [ -f "$HOME/miniconda/etc/profile.d/conda.sh" ]; then source "$HOME/miniconda/etc/profile.d/conda.sh" conda activate + # PSI4 has problems with dataclasses + pip uninstall -y dataclasses fi - # sudo apt-get -y update sudo apt-get -y install libgfortran5 pip install https://github.com/rpmuller/pyquante2/archive/master.zip pip install pyscf @@ -461,7 +462,6 @@ jobs: shell: bash - name: Install Dependencies run: | - # sudo apt-get -y update sudo apt-get -y install libgfortran5 pip install https://github.com/rpmuller/pyquante2/archive/master.zip pip install pyscf diff --git a/qiskit/aqua/VERSION.txt b/qiskit/aqua/VERSION.txt index a3df0a6959..6f4eebdf6f 100644 --- a/qiskit/aqua/VERSION.txt +++ b/qiskit/aqua/VERSION.txt @@ -1 +1 @@ -0.8.0 +0.8.1 diff --git a/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py b/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py index c533f9edc0..5d66d39889 100644 --- a/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py +++ b/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py @@ -76,9 +76,10 @@ def train(self, data, labels): """ scaling = 1.0 if self._qalgo.quantum_instance.is_statevector else None kernel_matrix = self._qalgo.construct_kernel_matrix(data) + lambda2 = self._qalgo.lambda2 labels = labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1 labels = labels.astype(np.float) - [alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling) + [alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling, lambda2=lambda2) support_index = np.where(support) alphas = alpha[support_index] svms = data[support_index] diff --git a/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py b/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py index 765cd72a71..f6039838db 100644 --- a/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py +++ b/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py @@ -80,6 +80,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap], test_dataset: Optional[Dict[str, np.ndarray]] = None, datapoints: Optional[np.ndarray] = None, multiclass_extension: Optional[MulticlassExtension] = None, + lambda2: float = 0.001, quantum_instance: Optional[ Union[QuantumInstance, BaseBackend, Backend]] = None) -> None: """ @@ -90,6 +91,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap], datapoints: Prediction dataset. multiclass_extension: If number of classes is greater than 2 then a multiclass scheme must be supplied, in the form of a multiclass extension. + lambda2: L2 norm regularization factor quantum_instance: Quantum Instance or Backend Raises: @@ -118,6 +120,7 @@ def __init__(self, feature_map: Union[QuantumCircuit, FeatureMap], self.setup_training_data(training_dataset) self.setup_test_data(test_dataset) self.setup_datapoint(datapoints) + self.lambda2 = lambda2 self.feature_map = feature_map self.num_qubits = self.feature_map.num_qubits diff --git a/qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py b/qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py index 16160da042..6180cd66c2 100755 --- a/qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py +++ b/qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py @@ -16,7 +16,7 @@ import numpy as np -from qiskit.aqua.operators import (OperatorBase, X, I, H, Zero, CircuitStateFn, +from qiskit.aqua.operators import (OperatorBase, X, I, H, CircuitStateFn, EvolutionFactory, LegacyBaseOperator) from qiskit.aqua.components.variational_forms import VariationalForm from qiskit.aqua.components.initial_states import InitialState @@ -80,13 +80,12 @@ def construct_circuit(self, parameters, q=None): self.num_parameters, len(parameters) )) - circuit = (H ^ self._num_qubits) # initialize circuit, possibly based on given register/initial state if self._initial_state is not None: - init_state = CircuitStateFn(self._initial_state.construct_circuit('circuit')) + stateVector = CircuitStateFn(self._initial_state.construct_circuit('circuit')) + circuit = stateVector.to_circuit_op() else: - init_state = Zero - circuit = circuit.compose(init_state) + circuit = (H ^ self._num_qubits) for idx in range(self._p): circuit = (self._cost_operator * parameters[idx]).exp_i().compose(circuit) diff --git a/qiskit/aqua/algorithms/quantum_algorithm.py b/qiskit/aqua/algorithms/quantum_algorithm.py index a420035927..2cf9518713 100644 --- a/qiskit/aqua/algorithms/quantum_algorithm.py +++ b/qiskit/aqua/algorithms/quantum_algorithm.py @@ -60,8 +60,8 @@ def run(self, AquaError: If a quantum instance or backend has not been provided """ if quantum_instance is None and self.quantum_instance is None: - raise AquaError("Quantum device or backend " - "is needed since you are running quantum algorithm.") + raise AquaError("A QuantumInstance or Backend " + "must be supplied to run the quantum algorithm.") if isinstance(quantum_instance, (BaseBackend, Backend)): self.set_backend(quantum_instance, **kwargs) else: diff --git a/qiskit/aqua/components/neural_networks/pytorch_discriminator.py b/qiskit/aqua/components/neural_networks/pytorch_discriminator.py index 794420437d..f8828db0e4 100644 --- a/qiskit/aqua/components/neural_networks/pytorch_discriminator.py +++ b/qiskit/aqua/components/neural_networks/pytorch_discriminator.py @@ -90,7 +90,7 @@ def load_model(self, load_dir: str): Args: load_dir: file with stored pytorch discriminator model to be loaded """ - torch.load(load_dir) + self._discriminator = torch.load(load_dir) @property def discriminator_net(self): diff --git a/qiskit/aqua/components/optimizers/nlopts/nloptimizer.py b/qiskit/aqua/components/optimizers/nlopts/nloptimizer.py index 0cf85f5bc6..4139ab1779 100644 --- a/qiskit/aqua/components/optimizers/nlopts/nloptimizer.py +++ b/qiskit/aqua/components/optimizers/nlopts/nloptimizer.py @@ -93,6 +93,8 @@ def optimize(self, num_vars, objective_function, gradient_function=None, variable_bounds=None, initial_point=None): super().optimize(num_vars, objective_function, gradient_function, variable_bounds, initial_point) + if variable_bounds is None: + variable_bounds = [(None, None)] * num_vars return self._minimize(self._optimizer_names[self.get_nlopt_optimizer()], objective_function, variable_bounds, @@ -101,7 +103,7 @@ def optimize(self, num_vars, objective_function, gradient_function=None, def _minimize(self, name: str, objective_function: Callable, - variable_bounds: Optional[List[Tuple[float, float]]] = None, + variable_bounds: Optional[List[Tuple[float, float]]], initial_point: Optional[np.ndarray] = None, max_evals: int = 1000) -> Tuple[float, float, int]: """Minimize using objective function diff --git a/qiskit/aqua/operators/converters/circuit_sampler.py b/qiskit/aqua/operators/converters/circuit_sampler.py index 2a3c1d0671..1000a128da 100644 --- a/qiskit/aqua/operators/converters/circuit_sampler.py +++ b/qiskit/aqua/operators/converters/circuit_sampler.py @@ -21,7 +21,7 @@ from qiskit.providers import Backend from qiskit.circuit import QuantumCircuit, Parameter, ParameterExpression from qiskit import QiskitError -from qiskit.aqua import QuantumInstance +from qiskit.aqua import QuantumInstance, AquaError from qiskit.aqua.utils.backend_utils import is_aer_provider, is_statevector_backend from qiskit.aqua.operators.operator_base import OperatorBase from qiskit.aqua.operators.list_ops.list_op import ListOp @@ -165,6 +165,8 @@ def convert(self, Returns: The converted Operator with CircuitStateFns replaced by DictStateFns or VectorStateFns. + Raises: + AquaError: if extracted circuits are empty. """ if self._last_op is None or id(operator) != id(self._last_op): # Clear caches @@ -181,6 +183,11 @@ def convert(self, if not self._circuit_ops_cache: self._circuit_ops_cache = {} self._extract_circuitstatefns(self._reduced_op_cache) + if not self._circuit_ops_cache: + raise AquaError( + 'Circuits are empty. ' + 'Check that the operator is an instance of CircuitStateFn or its ListOp.' + ) if params: p_0 = list(params.values())[0] # type: ignore @@ -243,8 +250,13 @@ def sample_circuits(self, Returns: The dictionary mapping ids of the CircuitStateFns to their replacement StateFns. + Raises: + AquaError: if extracted circuits are empty. """ - if circuit_sfns or not self._transpiled_circ_cache: + if not circuit_sfns and not self._transpiled_circ_cache: + raise AquaError('CircuitStateFn is empty and there is no cache.') + + if circuit_sfns: if self._statevector: circuits = [op_c.to_circuit(meas=False) for op_c in circuit_sfns] else: @@ -266,14 +278,14 @@ def sample_circuits(self, start_time = time() ready_circs = self._prepare_parameterized_run_config(param_bindings) end_time = time() - logger.info('Parameter conversion %.5f (ms)', (end_time - start_time) * 1000) + logger.debug('Parameter conversion %.5f (ms)', (end_time - start_time) * 1000) else: start_time = time() ready_circs = [circ.assign_parameters(binding) for circ in self._transpiled_circ_cache for binding in param_bindings] end_time = time() - logger.info('Parameter binding %.5f (ms)', (end_time - start_time) * 1000) + logger.debug('Parameter binding %.5f (ms)', (end_time - start_time) * 1000) else: ready_circs = self._transpiled_circ_cache diff --git a/qiskit/aqua/operators/evolutions/trotterizations/trotter.py b/qiskit/aqua/operators/evolutions/trotterizations/trotter.py index 3152c1d1a5..e2ed34768e 100644 --- a/qiskit/aqua/operators/evolutions/trotterizations/trotter.py +++ b/qiskit/aqua/operators/evolutions/trotterizations/trotter.py @@ -26,4 +26,4 @@ def __init__(self, Args: reps: The number of times to repeat the Trotterization circuit. """ - super().__init__(order=1, reps=1) + super().__init__(order=1, reps=reps) diff --git a/qiskit/aqua/operators/legacy/weighted_pauli_operator.py b/qiskit/aqua/operators/legacy/weighted_pauli_operator.py index 0893cbf863..52c420567b 100644 --- a/qiskit/aqua/operators/legacy/weighted_pauli_operator.py +++ b/qiskit/aqua/operators/legacy/weighted_pauli_operator.py @@ -101,9 +101,19 @@ def to_opflow(self, reverse_endianness=False): pauli_ops = [] for [w, p] in self.paulis: pauli = Pauli.from_label(str(p)[::-1]) if reverse_endianness else p - # Adding the imaginary is necessary to handle the imaginary coefficients in UCCSD. - # TODO fix these or add support for them in Terra. - pauli_ops += [PrimitiveOp(pauli, coeff=np.real(w) + np.imag(w))] + # This weighted pauli operator has the coeff stored as a complex type + # irrespective of whether the value has any imaginary part or not. + # For many operators the coeff will be real. Hence below the coeff is made real, + # when creating the PrimitiveOp, since it can be stored then as a float, if its + # value is real, i.e. has no imaginary part. This avoids any potential issues around + # complex - but if there are complex coeffs then maybe that using the opflow + # later will fail if it happens to be used where complex is not supported. + # Now there are imaginary coefficients in UCCSD that would need to be handled + # when this is converted to opflow (evolution of hopping operators) where currently + # Terra does not handle complex. + # TODO fix these or add support for them in Terra + coeff = np.real(w) if np.isreal(w) else w + pauli_ops += [PrimitiveOp(pauli, coeff=coeff)] return sum(pauli_ops) @property diff --git a/qiskit/aqua/operators/primitive_ops/circuit_op.py b/qiskit/aqua/operators/primitive_ops/circuit_op.py index 383e9d0b58..2bcc5d0791 100644 --- a/qiskit/aqua/operators/primitive_ops/circuit_op.py +++ b/qiskit/aqua/operators/primitive_ops/circuit_op.py @@ -35,9 +35,8 @@ class CircuitOp(PrimitiveOp): """ def __init__(self, - primitive: Union[Instruction, QuantumCircuit] = None, - coeff: Optional[Union[int, float, complex, - ParameterExpression]] = 1.0) -> None: + primitive: Union[Instruction, QuantumCircuit], + coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None: """ Args: primitive: The QuantumCircuit which defines the diff --git a/qiskit/aqua/operators/primitive_ops/matrix_op.py b/qiskit/aqua/operators/primitive_ops/matrix_op.py index ec91a450cd..49caa7922e 100644 --- a/qiskit/aqua/operators/primitive_ops/matrix_op.py +++ b/qiskit/aqua/operators/primitive_ops/matrix_op.py @@ -12,7 +12,7 @@ """ MatrixOp Class """ -from typing import Union, Optional, Set, Dict, List, cast +from typing import Union, Optional, Set, Dict, List, cast, get_type_hints import logging import numpy as np from scipy.sparse import spmatrix @@ -40,8 +40,8 @@ class MatrixOp(PrimitiveOp): """ def __init__(self, - primitive: Union[list, np.ndarray, spmatrix, Operator] = None, - coeff: Optional[Union[int, float, complex, ParameterExpression]] = 1.0) -> None: + primitive: Union[list, np.ndarray, spmatrix, Operator], + coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None: """ Args: primitive: The matrix-like object which defines the behavior of the underlying function. @@ -51,6 +51,7 @@ def __init__(self, TypeError: invalid parameters. ValueError: invalid parameters. """ + primitive_orig = primitive if isinstance(primitive, spmatrix): primitive = primitive.toarray() @@ -58,9 +59,10 @@ def __init__(self, primitive = Operator(primitive) if not isinstance(primitive, Operator): - raise TypeError( - 'MatrixOp can only be instantiated with MatrixOperator, ' - 'not {}'.format(type(primitive))) + type_hints = get_type_hints(MatrixOp.__init__).get('primitive') + valid_cls = [cls.__name__ for cls in type_hints.__args__] + raise TypeError(f"MatrixOp can only be instantiated with {valid_cls}, " + f"not '{primitive_orig.__class__.__name__}'") if not primitive.input_dims() == primitive.output_dims(): raise ValueError('Cannot handle non-square matrices yet.') diff --git a/qiskit/aqua/operators/primitive_ops/pauli_op.py b/qiskit/aqua/operators/primitive_ops/pauli_op.py index 6101995442..faf5547b3d 100644 --- a/qiskit/aqua/operators/primitive_ops/pauli_op.py +++ b/qiskit/aqua/operators/primitive_ops/pauli_op.py @@ -39,7 +39,7 @@ class PauliOp(PrimitiveOp): """ def __init__(self, - primitive: Union[Pauli] = None, + primitive: Union[Pauli], coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None: """ Args: diff --git a/qiskit/aqua/operators/primitive_ops/primitive_op.py b/qiskit/aqua/operators/primitive_ops/primitive_op.py index 62adbb7a91..68f0d7d12b 100644 --- a/qiskit/aqua/operators/primitive_ops/primitive_op.py +++ b/qiskit/aqua/operators/primitive_ops/primitive_op.py @@ -48,8 +48,9 @@ class PrimitiveOp(OperatorBase): @staticmethod # pylint: disable=unused-argument def __new__(cls, - primitive: Union[Instruction, QuantumCircuit, List, - np.ndarray, spmatrix, MatrixOperator, Pauli] = None, + primitive: + Optional[Union[Instruction, QuantumCircuit, List, + np.ndarray, spmatrix, MatrixOperator, Pauli]] = None, coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> 'PrimitiveOp': """ A factory method to produce the correct type of PrimitiveOp subclass based on the primitive passed in. Primitive and coeff arguments are passed into @@ -85,9 +86,10 @@ def __new__(cls, 'factory constructor'.format(type(primitive))) def __init__(self, - primitive: Union[Instruction, QuantumCircuit, List, - np.ndarray, spmatrix, MatrixOperator, Pauli] = None, - coeff: Optional[Union[int, float, complex, ParameterExpression]] = 1.0) -> None: + primitive: + Optional[Union[Instruction, QuantumCircuit, List, + np.ndarray, spmatrix, MatrixOperator, Pauli]] = None, + coeff: Union[int, float, complex, ParameterExpression] = 1.0) -> None: """ Args: primitive: The operator primitive being wrapped. diff --git a/qiskit/aqua/operators/state_fns/dict_state_fn.py b/qiskit/aqua/operators/state_fns/dict_state_fn.py index 8127a5aaf2..734aea8f5c 100644 --- a/qiskit/aqua/operators/state_fns/dict_state_fn.py +++ b/qiskit/aqua/operators/state_fns/dict_state_fn.py @@ -252,7 +252,7 @@ def sample(self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False) -> dict: - probs = np.array(list(self.primitive.values()))**2 + probs = np.square(np.abs(np.array(list(self.primitive.values())))) unique, counts = np.unique(aqua_globals.random.choice(list(self.primitive.keys()), size=shots, p=(probs / sum(probs))), diff --git a/qiskit/aqua/operators/state_fns/operator_state_fn.py b/qiskit/aqua/operators/state_fns/operator_state_fn.py index d7476a3b4b..97adbac61e 100644 --- a/qiskit/aqua/operators/state_fns/operator_state_fn.py +++ b/qiskit/aqua/operators/state_fns/operator_state_fn.py @@ -34,7 +34,7 @@ class OperatorStateFn(StateFn): # TODO allow normalization somehow? def __init__(self, - primitive: Union[OperatorBase] = None, + primitive: OperatorBase = None, coeff: Union[int, float, complex, ParameterExpression] = 1.0, is_measurement: bool = False) -> None: """ diff --git a/qiskit/aqua/quantum_instance.py b/qiskit/aqua/quantum_instance.py index d9e2bb8873..28f25e8071 100644 --- a/qiskit/aqua/quantum_instance.py +++ b/qiskit/aqua/quantum_instance.py @@ -12,19 +12,31 @@ """ Quantum Instance module """ +from typing import Optional, List, Union, Dict, Callable import copy import logging import time +from qiskit.providers import BaseBackend +from qiskit.transpiler import CouplingMap, PassManager +from qiskit.transpiler.layout import Layout from qiskit.assembler.run_config import RunConfig +from qiskit.circuit import QuantumCircuit +from qiskit.qobj import Qobj from qiskit import compiler +try: + from qiskit.providers.aer.noise import NoiseModel # pylint: disable=unused-import +except ImportError as ex: + pass + from .aqua_error import AquaError from .utils.backend_utils import (is_ibmq_provider, is_statevector_backend, is_simulator_backend, is_local_backend, is_aer_qasm, + is_basicaer_provider, support_backend_options) from .utils.circuit_utils import summarize_circuits @@ -35,7 +47,7 @@ class QuantumInstance: """Quantum Backend including execution setting.""" _BACKEND_CONFIG = ['basis_gates', 'coupling_map'] - _COMPILE_CONFIG = ['pass_manager', 'initial_layout', 'seed_transpiler', 'optimization_level'] + _COMPILE_CONFIG = ['initial_layout', 'seed_transpiler', 'optimization_level'] _RUN_CONFIG = ['shots', 'max_credits', 'memory', 'seed_simulator'] _QJOB_CONFIG = ['timeout', 'wait'] _NOISE_CONFIG = ['noise_model'] @@ -46,60 +58,68 @@ class QuantumInstance: "max_parallel_experiments", "statevector_parallel_threshold", "statevector_hpc_gate_opt"] + _BACKEND_OPTIONS_QASM_ONLY - def __init__(self, backend, + def __init__(self, + backend: BaseBackend, # run config - shots=1024, seed_simulator=None, max_credits=10, + shots: int = 1024, + seed_simulator: Optional[int] = None, + max_credits: int = 10, # backend properties - basis_gates=None, coupling_map=None, + basis_gates: Optional[List[str]] = None, + coupling_map: Optional[Union[CouplingMap, List[List]]] = None, # transpile - initial_layout=None, pass_manager=None, - seed_transpiler=None, optimization_level=None, + initial_layout: Optional[Union[Layout, Dict, List]] = None, + pass_manager: Optional[PassManager] = None, + seed_transpiler: Optional[int] = None, + optimization_level: Optional[int] = None, # simulation - backend_options=None, noise_model=None, + backend_options: Optional[Dict] = None, + noise_model: Optional['NoiseModel'] = None, # job - timeout=None, wait=5, + timeout: Optional[float] = None, + wait: float = 5., # others - skip_qobj_validation=True, - measurement_error_mitigation_cls=None, cals_matrix_refresh_period=30, - measurement_error_mitigation_shots=None, - job_callback=None): + skip_qobj_validation: bool = True, + measurement_error_mitigation_cls: Optional[Callable] = None, + cals_matrix_refresh_period: int = 30, + measurement_error_mitigation_shots: Optional[int] = None, + job_callback: Optional[Callable] = None) -> None: """ Quantum Instance holds a Qiskit Terra backend as well as configuration for circuit transpilation and execution. When provided to an Aqua algorithm the algorithm will execute the circuits it needs to run using the instance. Args: - backend (BaseBackend): Instance of selected backend - shots (int, optional): Number of repetitions of each circuit, for sampling - seed_simulator (int, optional): Random seed for simulators - max_credits (int, optional): Maximum credits to use - basis_gates (list[str], optional): List of basis gate names supported by the + backend: Instance of selected backend + shots: Number of repetitions of each circuit, for sampling + seed_simulator: Random seed for simulators + max_credits: Maximum credits to use + basis_gates: List of basis gate names supported by the target. Defaults to basis gates of the backend. - coupling_map (CouplingMap or list[list]): Coupling map (perhaps custom) to + coupling_map: Coupling map (perhaps custom) to target in mapping - initial_layout (Layout or dict or list, optional): Initial layout of qubits in mapping - pass_manager (PassManager, optional): Pass manager to handle how to compile the circuits - seed_transpiler (int, optional): The random seed for circuit mapper - optimization_level (int, optional): How much optimization to perform on the circuits. + initial_layout: Initial layout of qubits in mapping + pass_manager: Pass manager to handle how to compile the circuits + seed_transpiler: The random seed for circuit mapper + optimization_level: How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. - backend_options (dict, optional): All running options for backend, please refer + backend_options: All running options for backend, please refer to the provider of the backend for information as to what options it supports. - noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model - for simulator - timeout (float, optional): Seconds to wait for job. If None, wait indefinitely. - wait (float, optional): Seconds between queries for job result - skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease circuit + noise_model: noise model for simulator + timeout: Seconds to wait for job. If None, wait indefinitely. + wait: Seconds between queries for job result + skip_qobj_validation: Bypass Qobj validation to decrease circuit processing time during submission to backend. - measurement_error_mitigation_cls (Callable, optional): The approach to mitigate + measurement_error_mitigation_cls: The approach to mitigate measurement errors. Qiskit Ignis provides fitter classes for this functionality and CompleteMeasFitter from qiskit.ignis.mitigation.measurement module can be used here. (TensoredMeasFitter is not supported). - cals_matrix_refresh_period (int, optional): How often to refresh the calibration + cals_matrix_refresh_period: How often to refresh the calibration matrix in measurement mitigation. in minutes - measurement_error_mitigation_shots (int, optional): The number of shots number for + measurement_error_mitigation_shots: The number of shots number for building calibration matrix. If None, the main `shots` parameter value is used. - job_callback (Callable, optional): Optional user supplied callback which can be used + job_callback: Optional user supplied callback which can be used to monitor job progress as jobs are submitted for processing by an Aqua algorithm. The callback is provided the following arguments: `job_id, job_status, queue_position, job` @@ -110,6 +130,7 @@ def __init__(self, backend, AquaError: set backend_options but the backend does not support that """ self._backend = backend + self._pass_manager = pass_manager # setup run config if shots is not None: @@ -123,7 +144,7 @@ def __init__(self, backend, 'but you specified {}'.format(max_shots, shots)) run_config = RunConfig(shots=shots, max_credits=max_credits) - if seed_simulator: + if seed_simulator is not None: run_config.seed_simulator = seed_simulator self._run_config = run_config @@ -138,7 +159,6 @@ def __init__(self, backend, # setup compile config self._compile_config = { - 'pass_manager': pass_manager, 'initial_layout': initial_layout, 'seed_transpiler': seed_transpiler, 'optimization_level': optimization_level @@ -151,7 +171,7 @@ def __init__(self, backend, # setup noise config self._noise_config = {} if noise_model is not None: - if is_aer_qasm(self._backend): + if is_simulator_backend(self._backend) and not is_basicaer_provider(self._backend): self._noise_config = {'noise_model': noise_model} else: raise AquaError("The noise model is not supported on the selected backend {} ({}) " @@ -175,7 +195,7 @@ def __init__(self, backend, "with the statevector simulation.") else: self._meas_error_mitigation_cls = measurement_error_mitigation_cls - self._meas_error_mitigation_fitters = {} + self._meas_error_mitigation_fitters: Dict = {} # TODO: support different fitting method in error mitigation? self._meas_error_mitigation_method = 'least_squares' self._cals_matrix_refresh_period = cals_matrix_refresh_period @@ -219,17 +239,22 @@ def __str__(self) -> str: return info - def transpile(self, circuits): + def transpile(self, + circuits: Union[QuantumCircuit, List[QuantumCircuit]]) -> List[QuantumCircuit]: """ A wrapper to transpile circuits to allow algorithm access the transpiled circuits. Args: - circuits (QuantumCircuit or list[QuantumCircuit]): circuits to transpile + circuits: circuits to transpile Returns: - list[QuantumCircuit]: the transpiled circuits, it is always a list even though - the length is one. + The transpiled circuits, it is always a list even though the length is one. """ - transpiled_circuits = compiler.transpile(circuits, self._backend, **self._backend_config, - **self._compile_config) + if self._pass_manager is not None: + transpiled_circuits = self._pass_manager.run(circuits) + else: + transpiled_circuits = compiler.transpile(circuits, + self._backend, + **self._backend_config, + **self._compile_config) if not isinstance(transpiled_circuits, list): transpiled_circuits = [transpiled_circuits] @@ -242,20 +267,23 @@ def transpile(self, circuits): return transpiled_circuits - def assemble(self, circuits): + def assemble(self, + circuits: Union[QuantumCircuit, List[QuantumCircuit]]) -> Qobj: """ assemble circuits """ return compiler.assemble(circuits, **self._run_config.to_dict()) - def execute(self, circuits, had_transpiled=False): + def execute(self, + circuits: Union[QuantumCircuit, List[QuantumCircuit]], + had_transpiled: bool = False) -> Qobj: """ A wrapper to interface with quantum backend. Args: - circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute - had_transpiled (bool, optional): whether or not circuits had been transpiled + circuits: circuits to execute + had_transpiled: whether or not circuits had been transpiled Returns: - Result: Result object + Result object TODO: Maybe we can combine the circuits for the main ones and calibration circuits before assembling to the qobj. @@ -400,7 +428,7 @@ def set_config(self, **kwargs): self._backend_options['backend_options'] = {} self._backend_options['backend_options'][k] = v elif k in QuantumInstance._NOISE_CONFIG: - if not is_aer_qasm(self._backend): + if not is_simulator_backend(self._backend) or is_basicaer_provider(self._backend): raise AquaError( "The noise model is not supported on the selected backend {} ({}) " "only certain backends, such as Aer qasm support " diff --git a/qiskit/aqua/utils/qp_solver.py b/qiskit/aqua/utils/qp_solver.py index 4708ab86ac..c987427268 100644 --- a/qiskit/aqua/utils/qp_solver.py +++ b/qiskit/aqua/utils/qp_solver.py @@ -33,7 +33,8 @@ def optimize_svm(kernel_matrix: np.ndarray, scaling: Optional[float] = None, maxiter: int = 500, show_progress: bool = False, - max_iters: Optional[int] = None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + max_iters: Optional[int] = None, + lambda2: float = 0.001) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Solving quadratic programming problem for SVM; thus, some constraints are fixed. @@ -45,6 +46,7 @@ def optimize_svm(kernel_matrix: np.ndarray, maxiter: number of iterations for QP solver show_progress: showing the progress of QP solver max_iters: Deprecated, use maxiter. + lambda2: L2 Norm regularization factor Returns: np.ndarray: Sx1 array, where S is the number of supports @@ -81,12 +83,13 @@ def optimize_svm(kernel_matrix: np.ndarray, P = np.array(H) q = np.array(f) G = -np.eye(n) + I = np.eye(n) h = np.zeros(n) A = y.reshape(y.T.shape) b = np.zeros((1, 1)) x = cvxpy.Variable(n) prob = cvxpy.Problem( - cvxpy.Minimize((1 / 2) * cvxpy.quad_form(x, P) + q.T@x), + cvxpy.Minimize((1 / 2) * cvxpy.quad_form(x, P) + q.T@x + lambda2 * cvxpy.quad_form(x, I)), [G@x <= h, A@x == b]) prob.solve(verbose=show_progress, qcp=True) diff --git a/qiskit/optimization/algorithms/admm_optimizer.py b/qiskit/optimization/algorithms/admm_optimizer.py index 4566a00daf..a04018235c 100644 --- a/qiskit/optimization/algorithms/admm_optimizer.py +++ b/qiskit/optimization/algorithms/admm_optimizer.py @@ -286,7 +286,7 @@ def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult: # map integer variables to binary variables from ..converters.integer_to_binary import IntegerToBinary int2bin = IntegerToBinary() - original_variables = problem.variables + original_problem = problem problem = int2bin.convert(problem) # we deal with minimization in the optimizer, so turn the problem to minimization @@ -377,15 +377,16 @@ def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult: objective_value = objective_value * sense # convert back integer to binary - base_result = OptimizationResult(solution, objective_value, original_variables, + base_result = OptimizationResult(solution, objective_value, problem.variables, OptimizationResultStatus.SUCCESS) base_result = int2bin.interpret(base_result) # third parameter is our internal state of computations. result = ADMMOptimizationResult(x=base_result.x, fval=base_result.fval, - variables=base_result.variables, + variables=original_problem.variables, state=self._state, - status=self._get_feasibility_status(problem, base_result.x)) + status=self._get_feasibility_status(original_problem, + base_result.x)) # debug self._log.debug("solution=%s, objective=%s at iteration=%s", diff --git a/qiskit/optimization/problems/quadratic_program.py b/qiskit/optimization/problems/quadratic_program.py index 8c8eb3ffda..d756487016 100644 --- a/qiskit/optimization/problems/quadratic_program.py +++ b/qiskit/optimization/problems/quadratic_program.py @@ -29,6 +29,7 @@ from docplex.mp.model import Model from docplex.mp.model_reader import ModelReader from docplex.mp.quad import QuadExpr +from docplex.mp.vartype import ContinuousVarType, BinaryVarType, IntegerVarType from qiskit.aqua import MissingOptionalLibraryError from qiskit.aqua.operators import I, OperatorBase, PauliOp, WeightedPauliOperator, SummedOp, ListOp @@ -560,11 +561,11 @@ def from_docplex(self, model: Model) -> None: # keep track of names separately, since docplex allows to have None names. var_names = {} for x in model.iter_variables(): - if x.get_vartype().one_letter_symbol() == 'C': + if isinstance(x.get_vartype(), ContinuousVarType): x_new = self.continuous_var(x.lb, x.ub, x.name) - elif x.get_vartype().one_letter_symbol() == 'B': + elif isinstance(x.get_vartype(), BinaryVarType): x_new = self.binary_var(x.name) - elif x.get_vartype().one_letter_symbol() == 'I': + elif isinstance(x.get_vartype(), IntegerVarType): x_new = self.integer_var(x.lb, x.ub, x.name) else: raise QiskitOptimizationError( diff --git a/releasenotes/notes/P_BFGS-MacOS-4013becffcdf435a.yaml b/releasenotes/notes/0.8/P_BFGS-MacOS-4013becffcdf435a.yaml similarity index 100% rename from releasenotes/notes/P_BFGS-MacOS-4013becffcdf435a.yaml rename to releasenotes/notes/0.8/P_BFGS-MacOS-4013becffcdf435a.yaml diff --git a/releasenotes/notes/UCCSD-excitation-list-0fbb1af60f47192f.yaml b/releasenotes/notes/0.8/UCCSD-excitation-list-0fbb1af60f47192f.yaml similarity index 100% rename from releasenotes/notes/UCCSD-excitation-list-0fbb1af60f47192f.yaml rename to releasenotes/notes/0.8/UCCSD-excitation-list-0fbb1af60f47192f.yaml diff --git a/releasenotes/notes/admm-optimizer-d482b33f2474244e.yaml b/releasenotes/notes/0.8/admm-optimizer-d482b33f2474244e.yaml similarity index 100% rename from releasenotes/notes/admm-optimizer-d482b33f2474244e.yaml rename to releasenotes/notes/0.8/admm-optimizer-d482b33f2474244e.yaml diff --git a/releasenotes/notes/admm-warm-start-6f5b5c801bcdf78f.yaml b/releasenotes/notes/0.8/admm-warm-start-6f5b5c801bcdf78f.yaml similarity index 100% rename from releasenotes/notes/admm-warm-start-6f5b5c801bcdf78f.yaml rename to releasenotes/notes/0.8/admm-warm-start-6f5b5c801bcdf78f.yaml diff --git a/releasenotes/notes/ae-num-oracle-queries-a14bd74321768de3.yaml b/releasenotes/notes/0.8/ae-num-oracle-queries-a14bd74321768de3.yaml similarity index 100% rename from releasenotes/notes/ae-num-oracle-queries-a14bd74321768de3.yaml rename to releasenotes/notes/0.8/ae-num-oracle-queries-a14bd74321768de3.yaml diff --git a/releasenotes/notes/ae-on-circuit-ea1d914f91c571d2.yaml b/releasenotes/notes/0.8/ae-on-circuit-ea1d914f91c571d2.yaml similarity index 100% rename from releasenotes/notes/ae-on-circuit-ea1d914f91c571d2.yaml rename to releasenotes/notes/0.8/ae-on-circuit-ea1d914f91c571d2.yaml diff --git a/releasenotes/notes/aqgd-epochs-8e6ad87971e8e2db.yaml b/releasenotes/notes/0.8/aqgd-epochs-8e6ad87971e8e2db.yaml similarity index 100% rename from releasenotes/notes/aqgd-epochs-8e6ad87971e8e2db.yaml rename to releasenotes/notes/0.8/aqgd-epochs-8e6ad87971e8e2db.yaml diff --git a/releasenotes/notes/0.8/bopes-sampler-49f0ff70a438e6e0.yaml b/releasenotes/notes/0.8/bopes-sampler-49f0ff70a438e6e0.yaml new file mode 100644 index 0000000000..35bb29a332 --- /dev/null +++ b/releasenotes/notes/0.8/bopes-sampler-49f0ff70a438e6e0.yaml @@ -0,0 +1,7 @@ +--- +features: + - | + A new algorithm has been added: the Born Openheimer Potential Energy surface for the + calculation of potential energy surface along different degrees of freedom of the molecule. + The algorithm is called ``BOPESSampler``. It further provides functionalities of fitting the + potential energy surface to an analytic function of predefined potentials.some details. diff --git a/releasenotes/notes/0.8/bosonic_interface-3065369ddfe9a6e2.yaml b/releasenotes/notes/0.8/bosonic_interface-3065369ddfe9a6e2.yaml new file mode 100644 index 0000000000..d0e6047d35 --- /dev/null +++ b/releasenotes/notes/0.8/bosonic_interface-3065369ddfe9a6e2.yaml @@ -0,0 +1,9 @@ +--- +features: + - | + In addition to the workflows for solving Fermionic problems, interfaces for calculating + Bosonic ground and excited states have been added. In particular we introduced a full + interface for running vibronic structure calculations. +deprecations: + - TransformationType + - QubitMappingType diff --git a/releasenotes/notes/circs-bind-loses-meas-b11deaceefcf2178.yaml b/releasenotes/notes/0.8/circs-bind-loses-meas-b11deaceefcf2178.yaml similarity index 100% rename from releasenotes/notes/circs-bind-loses-meas-b11deaceefcf2178.yaml rename to releasenotes/notes/0.8/circs-bind-loses-meas-b11deaceefcf2178.yaml diff --git a/releasenotes/notes/circuit-op-compose-register-indep-5f3fd76dbb75c84e.yaml b/releasenotes/notes/0.8/circuit-op-compose-register-indep-5f3fd76dbb75c84e.yaml similarity index 100% rename from releasenotes/notes/circuit-op-compose-register-indep-5f3fd76dbb75c84e.yaml rename to releasenotes/notes/0.8/circuit-op-compose-register-indep-5f3fd76dbb75c84e.yaml diff --git a/releasenotes/notes/cvar-expectation-bbc2ccff95132b35.yaml b/releasenotes/notes/0.8/cvar-expectation-bbc2ccff95132b35.yaml similarity index 100% rename from releasenotes/notes/cvar-expectation-bbc2ccff95132b35.yaml rename to releasenotes/notes/0.8/cvar-expectation-bbc2ccff95132b35.yaml diff --git a/releasenotes/notes/cvx-optional-e44920f87cff5e8d.yaml b/releasenotes/notes/0.8/cvx-optional-e44920f87cff5e8d.yaml similarity index 100% rename from releasenotes/notes/cvx-optional-e44920f87cff5e8d.yaml rename to releasenotes/notes/0.8/cvx-optional-e44920f87cff5e8d.yaml diff --git a/releasenotes/notes/delete-deprecated-varforms-and-featmaps-0ab7bf477eeaa281.yaml b/releasenotes/notes/0.8/delete-deprecated-varforms-and-featmaps-0ab7bf477eeaa281.yaml similarity index 100% rename from releasenotes/notes/delete-deprecated-varforms-and-featmaps-0ab7bf477eeaa281.yaml rename to releasenotes/notes/0.8/delete-deprecated-varforms-and-featmaps-0ab7bf477eeaa281.yaml diff --git a/releasenotes/notes/deprecate-circuit-factories-3b9d85d07c07795b.yaml b/releasenotes/notes/0.8/deprecate-circuit-factories-3b9d85d07c07795b.yaml similarity index 100% rename from releasenotes/notes/deprecate-circuit-factories-3b9d85d07c07795b.yaml rename to releasenotes/notes/0.8/deprecate-circuit-factories-3b9d85d07c07795b.yaml diff --git a/releasenotes/notes/deprecate-ising-converter-classes-11749cdb6ac1bfaa.yaml b/releasenotes/notes/0.8/deprecate-ising-converter-classes-11749cdb6ac1bfaa.yaml similarity index 100% rename from releasenotes/notes/deprecate-ising-converter-classes-11749cdb6ac1bfaa.yaml rename to releasenotes/notes/0.8/deprecate-ising-converter-classes-11749cdb6ac1bfaa.yaml diff --git a/releasenotes/notes/deprecate-weighted-sum-op-9dc0eccac8e93963.yaml b/releasenotes/notes/0.8/deprecate-weighted-sum-op-9dc0eccac8e93963.yaml similarity index 100% rename from releasenotes/notes/deprecate-weighted-sum-op-9dc0eccac8e93963.yaml rename to releasenotes/notes/0.8/deprecate-weighted-sum-op-9dc0eccac8e93963.yaml diff --git a/releasenotes/notes/drop-py35-a1036a3d38f3d79a.yaml b/releasenotes/notes/0.8/drop-py35-a1036a3d38f3d79a.yaml similarity index 100% rename from releasenotes/notes/drop-py35-a1036a3d38f3d79a.yaml rename to releasenotes/notes/0.8/drop-py35-a1036a3d38f3d79a.yaml diff --git a/releasenotes/notes/efficient-summedop-tomatrix-op-b2650bccb5273d20.yaml b/releasenotes/notes/0.8/efficient-summedop-tomatrix-op-b2650bccb5273d20.yaml similarity index 100% rename from releasenotes/notes/efficient-summedop-tomatrix-op-b2650bccb5273d20.yaml rename to releasenotes/notes/0.8/efficient-summedop-tomatrix-op-b2650bccb5273d20.yaml diff --git a/releasenotes/notes/eingensolver-7adb5d4632706259.yaml b/releasenotes/notes/0.8/eingensolver-7adb5d4632706259.yaml similarity index 100% rename from releasenotes/notes/eingensolver-7adb5d4632706259.yaml rename to releasenotes/notes/0.8/eingensolver-7adb5d4632706259.yaml diff --git a/releasenotes/notes/0.8/excited-states-interface-a7ac8ae621b35daa.yaml b/releasenotes/notes/0.8/excited-states-interface-a7ac8ae621b35daa.yaml new file mode 100644 index 0000000000..415753f525 --- /dev/null +++ b/releasenotes/notes/0.8/excited-states-interface-a7ac8ae621b35daa.yaml @@ -0,0 +1,14 @@ +--- +features: + - | + An interface for excited states calculation has been added to the chemistry module. + It is now easier for the user to create a general excited states calculation. + This calculation is based on a ``Driver`` which provides the relevant information + about the molecule, a ``Transformation`` which provides the information about the + mapping of the problem into a qubit Hamiltonian, and finally a Solver. + The Solver is the specific way which the excited states calculation is done + (the algorithm). This structure follows the one of the ground state calculations. + The results are modified to take lists of expectation values instead of a single one. + The ``QEOM`` and ``NumpyEigensolver`` are adapted to the new structure. + A factory is introduced to run a numpy eigensolver with a specific filter + (to target states of specific symmetries). diff --git a/releasenotes/notes/expectation_change_backend-5483d30095f8bd82.yaml b/releasenotes/notes/0.8/expectation_change_backend-5483d30095f8bd82.yaml similarity index 100% rename from releasenotes/notes/expectation_change_backend-5483d30095f8bd82.yaml rename to releasenotes/notes/0.8/expectation_change_backend-5483d30095f8bd82.yaml diff --git a/releasenotes/notes/feasibility-check-b99605f771e745b7.yaml b/releasenotes/notes/0.8/feasibility-check-b99605f771e745b7.yaml similarity index 100% rename from releasenotes/notes/feasibility-check-b99605f771e745b7.yaml rename to releasenotes/notes/0.8/feasibility-check-b99605f771e745b7.yaml diff --git a/releasenotes/notes/finance-circuits-f39c12637226efd9.yaml b/releasenotes/notes/0.8/finance-circuits-f39c12637226efd9.yaml similarity index 100% rename from releasenotes/notes/finance-circuits-f39c12637226efd9.yaml rename to releasenotes/notes/0.8/finance-circuits-f39c12637226efd9.yaml diff --git a/releasenotes/notes/finance_data_providers-e2126f1e8cf076cd.yaml b/releasenotes/notes/0.8/finance_data_providers-e2126f1e8cf076cd.yaml similarity index 100% rename from releasenotes/notes/finance_data_providers-e2126f1e8cf076cd.yaml rename to releasenotes/notes/0.8/finance_data_providers-e2126f1e8cf076cd.yaml diff --git a/releasenotes/notes/fix-is-measurements-in-circuit-sampler-18679ad9bfe3f9cb.yaml b/releasenotes/notes/0.8/fix-is-measurements-in-circuit-sampler-18679ad9bfe3f9cb.yaml similarity index 100% rename from releasenotes/notes/fix-is-measurements-in-circuit-sampler-18679ad9bfe3f9cb.yaml rename to releasenotes/notes/0.8/fix-is-measurements-in-circuit-sampler-18679ad9bfe3f9cb.yaml diff --git a/releasenotes/notes/fix-to_circuit_op-914f9f68989b70f6.yaml b/releasenotes/notes/0.8/fix-to_circuit_op-914f9f68989b70f6.yaml similarity index 100% rename from releasenotes/notes/fix-to_circuit_op-914f9f68989b70f6.yaml rename to releasenotes/notes/0.8/fix-to_circuit_op-914f9f68989b70f6.yaml diff --git a/releasenotes/notes/fix-trotter-global-phase-eb86e17722b4d045.yaml b/releasenotes/notes/0.8/fix-trotter-global-phase-eb86e17722b4d045.yaml similarity index 100% rename from releasenotes/notes/fix-trotter-global-phase-eb86e17722b4d045.yaml rename to releasenotes/notes/0.8/fix-trotter-global-phase-eb86e17722b4d045.yaml diff --git a/releasenotes/notes/gradient_framework-df374d2929089bf1.yaml b/releasenotes/notes/0.8/gradient_framework-df374d2929089bf1.yaml similarity index 100% rename from releasenotes/notes/gradient_framework-df374d2929089bf1.yaml rename to releasenotes/notes/0.8/gradient_framework-df374d2929089bf1.yaml diff --git a/releasenotes/notes/ground_state_interface-42576cb6658a46e0.yaml b/releasenotes/notes/0.8/ground_state_interface-42576cb6658a46e0.yaml similarity index 100% rename from releasenotes/notes/ground_state_interface-42576cb6658a46e0.yaml rename to releasenotes/notes/0.8/ground_state_interface-42576cb6658a46e0.yaml diff --git a/releasenotes/notes/grover-qae-result-ca0764a8f755e4d0.yaml b/releasenotes/notes/0.8/grover-qae-result-ca0764a8f755e4d0.yaml similarity index 100% rename from releasenotes/notes/grover-qae-result-ca0764a8f755e4d0.yaml rename to releasenotes/notes/0.8/grover-qae-result-ca0764a8f755e4d0.yaml diff --git a/releasenotes/notes/listop-check-num-qubits-ce3a02fcc862771a.yaml b/releasenotes/notes/0.8/listop-check-num-qubits-ce3a02fcc862771a.yaml similarity index 100% rename from releasenotes/notes/listop-check-num-qubits-ce3a02fcc862771a.yaml rename to releasenotes/notes/0.8/listop-check-num-qubits-ce3a02fcc862771a.yaml diff --git a/releasenotes/notes/listop-combofn-ce0be39602f778a1.yaml b/releasenotes/notes/0.8/listop-combofn-ce0be39602f778a1.yaml similarity index 100% rename from releasenotes/notes/listop-combofn-ce0be39602f778a1.yaml rename to releasenotes/notes/0.8/listop-combofn-ce0be39602f778a1.yaml diff --git a/releasenotes/notes/ls-result-31d50f1cad95792b.yaml b/releasenotes/notes/0.8/ls-result-31d50f1cad95792b.yaml similarity index 100% rename from releasenotes/notes/ls-result-31d50f1cad95792b.yaml rename to releasenotes/notes/0.8/ls-result-31d50f1cad95792b.yaml diff --git a/releasenotes/notes/matrix-op-to-instruction-a990ec3a3db8ca8d.yaml b/releasenotes/notes/0.8/matrix-op-to-instruction-a990ec3a3db8ca8d.yaml similarity index 100% rename from releasenotes/notes/matrix-op-to-instruction-a990ec3a3db8ca8d.yaml rename to releasenotes/notes/0.8/matrix-op-to-instruction-a990ec3a3db8ca8d.yaml diff --git a/releasenotes/notes/oovqe-e8ff4f50f30687c3.yaml b/releasenotes/notes/0.8/oovqe-e8ff4f50f30687c3.yaml similarity index 100% rename from releasenotes/notes/oovqe-e8ff4f50f30687c3.yaml rename to releasenotes/notes/0.8/oovqe-e8ff4f50f30687c3.yaml diff --git a/releasenotes/notes/operator-coeff-eval-95efb26e95f6421a.yaml b/releasenotes/notes/0.8/operator-coeff-eval-95efb26e95f6421a.yaml similarity index 100% rename from releasenotes/notes/operator-coeff-eval-95efb26e95f6421a.yaml rename to releasenotes/notes/0.8/operator-coeff-eval-95efb26e95f6421a.yaml diff --git a/releasenotes/notes/opt-result-update-cdb157f6a67483bb.yaml b/releasenotes/notes/0.8/opt-result-update-cdb157f6a67483bb.yaml similarity index 100% rename from releasenotes/notes/opt-result-update-cdb157f6a67483bb.yaml rename to releasenotes/notes/0.8/opt-result-update-cdb157f6a67483bb.yaml diff --git a/releasenotes/notes/opt-result-validate-15fc0d66446701ae.yaml b/releasenotes/notes/0.8/opt-result-validate-15fc0d66446701ae.yaml similarity index 100% rename from releasenotes/notes/opt-result-validate-15fc0d66446701ae.yaml rename to releasenotes/notes/0.8/opt-result-validate-15fc0d66446701ae.yaml diff --git a/releasenotes/notes/optimization-supportlevel-d18e8dbced7172e0.yaml b/releasenotes/notes/0.8/optimization-supportlevel-d18e8dbced7172e0.yaml similarity index 100% rename from releasenotes/notes/optimization-supportlevel-d18e8dbced7172e0.yaml rename to releasenotes/notes/0.8/optimization-supportlevel-d18e8dbced7172e0.yaml diff --git a/releasenotes/notes/param-binding-opstatefn-44d6a3719c20263c.yaml b/releasenotes/notes/0.8/param-binding-opstatefn-44d6a3719c20263c.yaml similarity index 100% rename from releasenotes/notes/param-binding-opstatefn-44d6a3719c20263c.yaml rename to releasenotes/notes/0.8/param-binding-opstatefn-44d6a3719c20263c.yaml diff --git a/releasenotes/notes/pauli-expi-c0c97395190622c0.yaml b/releasenotes/notes/0.8/pauli-expi-c0c97395190622c0.yaml similarity index 100% rename from releasenotes/notes/pauli-expi-c0c97395190622c0.yaml rename to releasenotes/notes/0.8/pauli-expi-c0c97395190622c0.yaml diff --git a/releasenotes/notes/pauli-op-check-num-qubits-ab1a88ff3436b495.yaml b/releasenotes/notes/0.8/pauli-op-check-num-qubits-ab1a88ff3436b495.yaml similarity index 100% rename from releasenotes/notes/pauli-op-check-num-qubits-ab1a88ff3436b495.yaml rename to releasenotes/notes/0.8/pauli-op-check-num-qubits-ab1a88ff3436b495.yaml diff --git a/releasenotes/notes/pauli-op-hash-fix-c8f8bbc6fbccd04e.yaml b/releasenotes/notes/0.8/pauli-op-hash-fix-c8f8bbc6fbccd04e.yaml similarity index 100% rename from releasenotes/notes/pauli-op-hash-fix-c8f8bbc6fbccd04e.yaml rename to releasenotes/notes/0.8/pauli-op-hash-fix-c8f8bbc6fbccd04e.yaml diff --git a/releasenotes/notes/qgan-on-circuits-9bd57bd707b31897.yaml b/releasenotes/notes/0.8/qgan-on-circuits-9bd57bd707b31897.yaml similarity index 100% rename from releasenotes/notes/qgan-on-circuits-9bd57bd707b31897.yaml rename to releasenotes/notes/0.8/qgan-on-circuits-9bd57bd707b31897.yaml diff --git a/releasenotes/notes/redesigning-of-converters-5272a70d2e813057.yaml b/releasenotes/notes/0.8/redesigning-of-converters-5272a70d2e813057.yaml similarity index 100% rename from releasenotes/notes/redesigning-of-converters-5272a70d2e813057.yaml rename to releasenotes/notes/0.8/redesigning-of-converters-5272a70d2e813057.yaml diff --git a/releasenotes/notes/remove-circuitstatefn-restriction-9791b20efa26fd28.yaml b/releasenotes/notes/0.8/remove-circuitstatefn-restriction-9791b20efa26fd28.yaml similarity index 100% rename from releasenotes/notes/remove-circuitstatefn-restriction-9791b20efa26fd28.yaml rename to releasenotes/notes/0.8/remove-circuitstatefn-restriction-9791b20efa26fd28.yaml diff --git a/releasenotes/notes/rx-coloring-260d6439d39cbc2b.yaml b/releasenotes/notes/0.8/rx-coloring-260d6439d39cbc2b.yaml similarity index 100% rename from releasenotes/notes/rx-coloring-260d6439d39cbc2b.yaml rename to releasenotes/notes/0.8/rx-coloring-260d6439d39cbc2b.yaml diff --git a/releasenotes/notes/slsqp-optimizer-199a4694e480297e.yaml b/releasenotes/notes/0.8/slsqp-optimizer-199a4694e480297e.yaml similarity index 100% rename from releasenotes/notes/slsqp-optimizer-199a4694e480297e.yaml rename to releasenotes/notes/0.8/slsqp-optimizer-199a4694e480297e.yaml diff --git a/releasenotes/notes/statefn-eval-51ecf38a7a3cc087.yaml b/releasenotes/notes/0.8/statefn-eval-51ecf38a7a3cc087.yaml similarity index 100% rename from releasenotes/notes/statefn-eval-51ecf38a7a3cc087.yaml rename to releasenotes/notes/0.8/statefn-eval-51ecf38a7a3cc087.yaml diff --git a/releasenotes/notes/summed-op-compare-3df17046849af9a8.yaml b/releasenotes/notes/0.8/summed-op-compare-3df17046849af9a8.yaml similarity index 100% rename from releasenotes/notes/summed-op-compare-3df17046849af9a8.yaml rename to releasenotes/notes/0.8/summed-op-compare-3df17046849af9a8.yaml diff --git a/releasenotes/notes/unify-optimizer-params-a73247cd97065bc6.yaml b/releasenotes/notes/0.8/unify-optimizer-params-a73247cd97065bc6.yaml similarity index 100% rename from releasenotes/notes/unify-optimizer-params-a73247cd97065bc6.yaml rename to releasenotes/notes/0.8/unify-optimizer-params-a73247cd97065bc6.yaml diff --git a/releasenotes/notes/use-reno-99cd845ed7dc85ac.yaml b/releasenotes/notes/0.8/use-reno-99cd845ed7dc85ac.yaml similarity index 100% rename from releasenotes/notes/use-reno-99cd845ed7dc85ac.yaml rename to releasenotes/notes/0.8/use-reno-99cd845ed7dc85ac.yaml diff --git a/releasenotes/notes/vqe-adapt-fixes-8c584ab000ab5f8c.yaml b/releasenotes/notes/0.8/vqe-adapt-fixes-8c584ab000ab5f8c.yaml similarity index 100% rename from releasenotes/notes/vqe-adapt-fixes-8c584ab000ab5f8c.yaml rename to releasenotes/notes/0.8/vqe-adapt-fixes-8c584ab000ab5f8c.yaml diff --git a/releasenotes/notes/vqe-construct-circuit-cc30fbcc7a563474.yaml b/releasenotes/notes/0.8/vqe-construct-circuit-cc30fbcc7a563474.yaml similarity index 100% rename from releasenotes/notes/vqe-construct-circuit-cc30fbcc7a563474.yaml rename to releasenotes/notes/0.8/vqe-construct-circuit-cc30fbcc7a563474.yaml diff --git a/releasenotes/notes/vqe-expectation-122827ff3761537a.yaml b/releasenotes/notes/0.8/vqe-expectation-122827ff3761537a.yaml similarity index 100% rename from releasenotes/notes/vqe-expectation-122827ff3761537a.yaml rename to releasenotes/notes/0.8/vqe-expectation-122827ff3761537a.yaml diff --git a/releasenotes/notes/QSVM-L2-Norm-3382893ecafee124.yaml b/releasenotes/notes/QSVM-L2-Norm-3382893ecafee124.yaml new file mode 100644 index 0000000000..9198a85818 --- /dev/null +++ b/releasenotes/notes/QSVM-L2-Norm-3382893ecafee124.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + optimize_svm method of qp_solver would sometimes fail resulting in an error like this + `ValueError: cannot reshape array of size 1 into shape (200,1)` This addresses the issue + by adding an L2 norm parameter, lambda2, which defaults to 0.001 but can be changed via + the QSVM algorithm, as needed, to facilitate convergence. diff --git a/releasenotes/notes/bosonic_interface-3065369ddfe9a6e2.yaml b/releasenotes/notes/bosonic_interface-3065369ddfe9a6e2.yaml deleted file mode 100644 index 5aca5833f5..0000000000 --- a/releasenotes/notes/bosonic_interface-3065369ddfe9a6e2.yaml +++ /dev/null @@ -1,25 +0,0 @@ ---- -prelude: > - This release introduces an interface for running the available methods for - Bosonic problems. In particular we introduced a full interface for running - vibronic structure calculations. -features: - - BosonicOperator - - BosonicTransformation - - GaussianForcesDriver - - GaussianLogDriver - - GaussianLogResult - - VQEUVCCSDFactory - - BosonicBasis - - HarmonicBasis - - VSCF - - UVCC - - VibronicStructureResult - - WatsonHamiltonian - - FermionicQubitMappingType - - BosonicQubitMappingType - - FermionicTransformationType - - BosonicTransformationType -deprecations: - - TransformationType - - QubitMappingType diff --git a/releasenotes/notes/docplex-fix-e401d4b511ca5244.yaml b/releasenotes/notes/docplex-fix-e401d4b511ca5244.yaml new file mode 100644 index 0000000000..4294561755 --- /dev/null +++ b/releasenotes/notes/docplex-fix-e401d4b511ca5244.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + A method ``one_letter_symbol`` has been removed from the ``VarType`` in the latest + build of DOCplex making Aqua incompatible with this version. So instead of using this method + an explicit type check of variable types has been introduced in the Aqua optimization module. diff --git a/releasenotes/notes/excited-states-interface-a7ac8ae621b35daa.yaml b/releasenotes/notes/excited-states-interface-a7ac8ae621b35daa.yaml deleted file mode 100644 index c38d36d441..0000000000 --- a/releasenotes/notes/excited-states-interface-a7ac8ae621b35daa.yaml +++ /dev/null @@ -1,20 +0,0 @@ ---- -prelude: > - This release introduces an interface for excited states calculations. - It is now easier for the user to create a general excited states calculation. - This calculation is based on a Driver which provides the relevant information - about the molecule, a Transformation which provides the information about the - mapping of the problem into a qubit Hamiltonian, and finally a Solver. - The Solver is the specific way which the excited states calculation is done - (the algorithm). This structure follows the one of the ground state calculations. - The results are modified to take lists of expectation values instead of a single one. - The QEOM and NumpyEigensolver are adapted to the new structure. - A factory is introduced to run a numpy eigensolver with a specific filter - (to target states of specific symmetries). -features: - - ExcitedStateSolver - - ExcitedStateEigensolver - - QEOM - - EigensolverFactory - - NumPyEigenSolverFactory - - ElectronicStructureResult diff --git a/releasenotes/notes/fix-operator-flow-33a0bd315151562c.yaml b/releasenotes/notes/fix-operator-flow-33a0bd315151562c.yaml new file mode 100644 index 0000000000..b4e46623c3 --- /dev/null +++ b/releasenotes/notes/fix-operator-flow-33a0bd315151562c.yaml @@ -0,0 +1,17 @@ +--- +fixes: + - | + :meth`~qiskit.aqua.operators.state_fns.DictStateFn.sample()` could only handle + real amplitudes, but it is fixed to handle complex amplitudes. + `#1311 ` for more details. + - | + Trotter class did not use the reps argument in constructor. + `#1317 ` for more details. + - | + Raise an `AquaError` if :class`qiskit.aqua.operators.converters.CircuitSampler` + samples an empty operator. + `#1321 ` for more details. + - | + :meth:`~qiskit.aqua.operators.legacy.WeightedPauliOperator.to_opflow()` + returns a correct operator when coefficients are complex numbers. + `#1381 ` for more details. diff --git a/releasenotes/notes/noise_model-8e27eb648456f8a9.yaml b/releasenotes/notes/noise_model-8e27eb648456f8a9.yaml new file mode 100644 index 0000000000..5473786fe0 --- /dev/null +++ b/releasenotes/notes/noise_model-8e27eb648456f8a9.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Let backend simulators validate NoiseModel support instead of restricting to Aer only + in QuantumInstance. diff --git a/releasenotes/notes/pass_manager-c5e934ffc31addb0.yaml b/releasenotes/notes/pass_manager-c5e934ffc31addb0.yaml new file mode 100644 index 0000000000..e3d342686d --- /dev/null +++ b/releasenotes/notes/pass_manager-c5e934ffc31addb0.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Correctly handle PassManager on QuantumInstance ``transpile`` method by + calling its ``run`` method if it exists. diff --git a/releasenotes/notes/qaoa-initial-state-bugfix-a92b38b805f36209.yaml b/releasenotes/notes/qaoa-initial-state-bugfix-a92b38b805f36209.yaml new file mode 100644 index 0000000000..7ef1b1ba8a --- /dev/null +++ b/releasenotes/notes/qaoa-initial-state-bugfix-a92b38b805f36209.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + A bug that mixes custom ``initial_state`` in ``QAOA`` with Hadamard gates has been fixed. This doesn't change functionality of QAOA if no initial_state is provided by the user. Attention should be taken if your implementation uses QAOA with cusom ``initial_state`` parameter as the optimization results might differ. +critical: + - | + Be aware that ``initial_state`` parameter in ``QAOA`` has now different implementation as a result of a bug fix. The previous implementation wrongly mixed the user provided ``initial_state`` with Hadamard gates. The issue is fixed now. No attention needed if your code does not make use of the user provided ``initial_state`` parameter. diff --git a/releasenotes/notes/qi-seed-simulator-757f88ec183082f7.yaml b/releasenotes/notes/qi-seed-simulator-757f88ec183082f7.yaml new file mode 100644 index 0000000000..7115530a45 --- /dev/null +++ b/releasenotes/notes/qi-seed-simulator-757f88ec183082f7.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Previously, setting `seed_simulator=0` in the `QuantumInstance` did not set + any seed. This was only affecting the value 0. This has been fixed. diff --git a/test/aqua/operators/legacy/test_tpb_grouped_weighted_pauli_operator.py b/test/aqua/operators/legacy/test_tpb_grouped_weighted_pauli_operator.py index 125149187f..51f7cb7094 100644 --- a/test/aqua/operators/legacy/test_tpb_grouped_weighted_pauli_operator.py +++ b/test/aqua/operators/legacy/test_tpb_grouped_weighted_pauli_operator.py @@ -30,7 +30,7 @@ class TestTPBGroupedWeightedPauliOperator(QiskitAquaTestCase): def setUp(self): super().setUp() - seed = 0 + seed = 1 aqua_globals.random_seed = seed self.num_qubits = 3 diff --git a/test/aqua/operators/legacy/test_weighted_pauli_operator.py b/test/aqua/operators/legacy/test_weighted_pauli_operator.py index 09a78730fb..cb2e0d87e9 100644 --- a/test/aqua/operators/legacy/test_weighted_pauli_operator.py +++ b/test/aqua/operators/legacy/test_weighted_pauli_operator.py @@ -25,6 +25,7 @@ from qiskit.aqua.operators import WeightedPauliOperator from qiskit.aqua.operators.legacy import op_converter from qiskit.aqua.components.initial_states import Custom +from qiskit.aqua.operators import I, X, Y, Z @ddt @@ -33,7 +34,7 @@ class TestWeightedPauliOperator(QiskitAquaTestCase): def setUp(self): super().setUp() - seed = 0 + seed = 3 aqua_globals.random_seed = seed self.num_qubits = 3 @@ -610,6 +611,22 @@ def eval_op(op): expectation_value, _ = eval_op(wpo2) self.assertAlmostEqual(expectation_value, -3.0, places=2) + def test_to_opflow(self): + """Test for to_opflow() in WeightedPauliOperator""" + pauli_a = 'IXYZ' + pauli_b = 'ZYIX' + coeff_a = 0.5 + 1j + coeff_b = -0.5 - 1j + pauli_term_a = [coeff_a, Pauli.from_label(pauli_a)] + pauli_term_b = [coeff_b, Pauli.from_label(pauli_b)] + op_a = WeightedPauliOperator(paulis=[pauli_term_a]) + op_b = WeightedPauliOperator(paulis=[pauli_term_b]) + legacy_op = op_a + op_b + + op = coeff_a * (I ^ X ^ Y ^ Z) + coeff_b * (Z ^ Y ^ I ^ X) + + self.assertEqual(op, legacy_op.to_opflow()) + if __name__ == '__main__': unittest.main() diff --git a/test/aqua/operators/test_evolution.py b/test/aqua/operators/test_evolution.py index 92ffab0eea..a962739fa6 100644 --- a/test/aqua/operators/test_evolution.py +++ b/test/aqua/operators/test_evolution.py @@ -22,11 +22,11 @@ from qiskit.circuit import ParameterVector, Parameter from qiskit.aqua.operators import (X, Y, Z, I, CX, H, ListOp, CircuitOp, Zero, EvolutionFactory, - EvolvedOp, PauliTrotterEvolution, QDrift) - + EvolvedOp, PauliTrotterEvolution, QDrift, Trotter, Suzuki) # pylint: disable=invalid-name + class TestEvolution(QiskitAquaTestCase): """Evolution tests.""" @@ -255,6 +255,20 @@ def test_mixed_evolution(self): for p in thetas[1:]: self.assertNotIn(p, circuit_params) + def test_reps(self): + """Test reps and order params in Trotterization""" + reps = 7 + trotter = Trotter(reps=reps) + self.assertEqual(trotter.reps, reps) + + order = 5 + suzuki = Suzuki(reps=reps, order=order) + self.assertEqual(suzuki.reps, reps) + self.assertEqual(suzuki.order, order) + + qdrift = QDrift(reps=reps) + self.assertEqual(qdrift.reps, reps) + if __name__ == '__main__': unittest.main() diff --git a/test/aqua/operators/test_op_construction.py b/test/aqua/operators/test_op_construction.py index 054c4761be..d4b6215a0c 100644 --- a/test/aqua/operators/test_op_construction.py +++ b/test/aqua/operators/test_op_construction.py @@ -35,6 +35,7 @@ CircuitStateFn, VectorStateFn, DictStateFn, OperatorStateFn, ListOp, ComposedOp, TensoredOp, SummedOp ) +from qiskit.aqua.operators import MatrixOperator # pylint: disable=invalid-name @@ -909,6 +910,31 @@ def test_to_circuit_op(self): sfn.to_circuit_op().eval().primitive.data, vector ) + def test_invalid_primitive(self): + """Test invalid MatrixOp construction""" + msg = "MatrixOp can only be instantiated with " \ + "['list', 'ndarray', 'spmatrix', 'Operator'], not " + + with self.assertRaises(TypeError) as cm: + _ = MatrixOp('invalid') + + self.assertEqual(str(cm.exception), msg + "'str'") + + with self.assertRaises(TypeError) as cm: + _ = MatrixOp(MatrixOperator(np.eye(2))) + + self.assertEqual(str(cm.exception), msg + "'MatrixOperator'") + + with self.assertRaises(TypeError) as cm: + _ = MatrixOp(None) + + self.assertEqual(str(cm.exception), msg + "'NoneType'") + + with self.assertRaises(TypeError) as cm: + _ = MatrixOp(2.0) + + self.assertEqual(str(cm.exception), msg + "'float'") + class TestOpMethods(QiskitAquaTestCase): """Basic method tests.""" diff --git a/test/aqua/operators/test_state_construction.py b/test/aqua/operators/test_state_construction.py index fbb09e5adf..639fc6c25a 100644 --- a/test/aqua/operators/test_state_construction.py +++ b/test/aqua/operators/test_state_construction.py @@ -146,10 +146,10 @@ def test_circuit_state_fn_from_complex_vector_initialize(self): def test_sampling(self): """ state fn circuit from dict initialize test """ - statedict = {'101': .5, - '100': .1, - '000': .2, - '111': .5} + statedict = {'101': .5 + 1.j, + '100': .1 + 2.j, + '000': .2 + 0.j, + '111': .5 + 1.j} sfc = CircuitStateFn.from_dict(statedict) circ_samples = sfc.sample() dict_samples = StateFn(statedict).sample() diff --git a/test/aqua/test_bernstein_vazirani.py b/test/aqua/test_bernstein_vazirani.py index 7ea9283562..1faa5bf671 100644 --- a/test/aqua/test_bernstein_vazirani.py +++ b/test/aqua/test_bernstein_vazirani.py @@ -18,6 +18,8 @@ from test.aqua import QiskitAquaTestCase from ddt import ddt, idata, unpack from qiskit import BasicAer +from qiskit.transpiler import PassManagerConfig +from qiskit.transpiler.preset_passmanagers import level_0_pass_manager from qiskit.aqua import QuantumInstance from qiskit.aqua.components.oracles import TruthTableOracle from qiskit.aqua.algorithms import BernsteinVazirani @@ -34,7 +36,7 @@ class TestBernsteinVazirani(QiskitAquaTestCase): @idata(itertools.product(BITMAPS, MCT_MODES, OPTIMIZATIONS, SIMULATORS)) @unpack def test_bernstein_vazirani(self, bv_input, mct_mode, optimization, simulator): - """ Bernstein Vazirani test """ + """ Test Bernstein Vazirani """ nbits = int(math.log(len(bv_input), 2)) # compute the ground-truth classically parameter = "" @@ -50,6 +52,17 @@ def test_bernstein_vazirani(self, bv_input, mct_mode, optimization, simulator): # print(result['circuit'].draw(line_length=10000)) self.assertEqual(result['result'], parameter) + def test_with_pass_manager(self): + """ Test Bernstein Vazirani using PassManager """ + quantum_instance = QuantumInstance( + BasicAer.get_backend('qasm_simulator'), + pass_manager=level_0_pass_manager( + PassManagerConfig(basis_gates=['cx', 'u1', 'u2', 'u3']))) + alg = BernsteinVazirani(oracle=TruthTableOracle(bitmaps="01100110"), + quantum_instance=quantum_instance) + result = alg.run() + self.assertEqual(result['result'], '011') + if __name__ == '__main__': unittest.main() diff --git a/test/aqua/test_nlopt_optimizers.py b/test/aqua/test_nlopt_optimizers.py index b47a1f6fe1..81b445ea33 100644 --- a/test/aqua/test_nlopt_optimizers.py +++ b/test/aqua/test_nlopt_optimizers.py @@ -28,26 +28,29 @@ class TestNLOptOptimizers(QiskitAquaTestCase): """ Test NLOpt Optimizers """ - def _optimize(self, optimizer): + def _optimize(self, optimizer, use_bound): x_0 = [1.3, 0.7, 0.8, 1.9, 1.2] - bounds = [(-6, 6)] * len(x_0) + bounds = [(-6, 6)] * len(x_0) if use_bound else None res = optimizer.optimize(len(x_0), rosen, initial_point=x_0, variable_bounds=bounds) np.testing.assert_array_almost_equal(res[0], [1.0] * len(x_0), decimal=2) return res # ESCH and ISRES do not do well with rosen @idata([ - [CRS], - [DIRECT_L], - [DIRECT_L_RAND], + [CRS, True], + [DIRECT_L, True], + [DIRECT_L_RAND, True], + [CRS, False], + [DIRECT_L, False], + [DIRECT_L_RAND, False], ]) @unpack - def test_nlopt(self, optimizer_cls): + def test_nlopt(self, optimizer_cls, use_bound): """ NLopt test """ try: optimizer = optimizer_cls() optimizer.set_options(**{'max_evals': 50000}) - res = self._optimize(optimizer) + res = self._optimize(optimizer, use_bound) self.assertLessEqual(res[2], 50000) except MissingOptionalLibraryError as ex: self.skipTest(str(ex)) diff --git a/test/aqua/test_qsvm.py b/test/aqua/test_qsvm.py index 8f7768911a..a81051c43a 100644 --- a/test/aqua/test_qsvm.py +++ b/test/aqua/test_qsvm.py @@ -79,7 +79,7 @@ def test_binary(self, mode): else: data_preparation = self.data_preparation - svm = QSVM(data_preparation, self.training_data, self.testing_data, None) + svm = QSVM(data_preparation, self.training_data, self.testing_data, None, lambda2=0) try: result = svm.run(self.qasm_simulator) @@ -104,7 +104,7 @@ def test_binary_directly_statevector(self): Also tests saving and loading models.""" data_preparation = self.data_preparation - svm = QSVM(data_preparation, self.training_data, self.testing_data, None) + svm = QSVM(data_preparation, self.training_data, self.testing_data, None, lambda2=0) file_path = self.get_resource_path('qsvm_test.npz') try: @@ -213,7 +213,7 @@ def test_multiclass(self, multiclass_extension): data_preparation = self.data_preparation try: svm = QSVM(data_preparation, train_input, test_input, total_array, - multiclass_extension=method[multiclass_extension]) + multiclass_extension=method[multiclass_extension], lambda2=0) result = svm.run(self.qasm_simulator) self.assertAlmostEqual(result['testing_accuracy'], accuracy[multiclass_extension], places=4) @@ -252,7 +252,7 @@ def test_matrix_psd(self): seed_transpiler=seed) kernel_matrix = QSVM.get_kernel_matrix(quantum_instance, feature_map=feature_map, x1_vec=training_data, enforce_psd=False) - _ = optimize_svm(kernel_matrix, labels) + _ = optimize_svm(kernel_matrix, labels, lambda2=0) # This time we enforce that the matrix be positive semi-definite which runs logic to # make it so. @@ -261,7 +261,7 @@ def test_matrix_psd(self): seed_transpiler=seed) kernel_matrix = QSVM.get_kernel_matrix(quantum_instance, feature_map=feature_map, x1_vec=training_data, enforce_psd=True) - alpha, b, support = optimize_svm(kernel_matrix, labels) + alpha, b, support = optimize_svm(kernel_matrix, labels, lambda2=0) expected_alpha = [0.855861781, 2.59807482, 0, 0.962959215, 1.08141696, 0.217172547, 0, 0, diff --git a/test/aqua/test_skip_qobj_validation.py b/test/aqua/test_skip_qobj_validation.py index 0a4cb897ce..0e83cfec0f 100644 --- a/test/aqua/test_skip_qobj_validation.py +++ b/test/aqua/test_skip_qobj_validation.py @@ -16,7 +16,7 @@ from test.aqua import QiskitAquaTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer -from qiskit.aqua import QuantumInstance +from qiskit.aqua import QuantumInstance, AquaError def _compare_dict(dict1, dict2): @@ -103,6 +103,15 @@ def test_w_noise(self): res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation)) + # BasicAer should fail: + with self.assertRaises(AquaError): + _ = QuantumInstance(BasicAer.get_backend('qasm_simulator'), + noise_model=noise_model) + + with self.assertRaises(AquaError): + quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator')) + quantum_instance.set_config(noise_model=noise_model) + if __name__ == '__main__': unittest.main() diff --git a/test/optimization/test_admm.py b/test/optimization/test_admm.py index ddb4588804..8ee41fadd8 100644 --- a/test/optimization/test_admm.py +++ b/test/optimization/test_admm.py @@ -345,3 +345,26 @@ def test_admm_setters_getters(self): params = ADMMParameters(maxiter=12) optimizer.parameters = params self.assertEqual(optimizer.parameters.maxiter, 12) + + def test_integer_variables(self): + """Tests ADMM with integer variables.""" + mdl = Model('integer-variables') + + v = mdl.integer_var(lb=5, ub=20, name='v') + w = mdl.continuous_var(name='w', lb=0.) + + mdl.minimize(v + w) + op = QuadraticProgram() + op.from_docplex(mdl) + + solver = ADMMOptimizer() + solution = solver.solve(op) + + self.assertIsNotNone(solution) + self.assertIsInstance(solution, ADMMOptimizationResult) + self.assertIsNotNone(solution.x) + np.testing.assert_almost_equal([5., 0.], solution.x, 3) + self.assertIsNotNone(solution.fval) + np.testing.assert_almost_equal(5., solution.fval, 3) + self.assertIsNotNone(solution.state) + self.assertIsInstance(solution.state, ADMMState) diff --git a/test/optimization/test_qaoa.py b/test/optimization/test_qaoa.py index 6de119f6d0..3eb251fbbb 100755 --- a/test/optimization/test_qaoa.py +++ b/test/optimization/test_qaoa.py @@ -15,13 +15,15 @@ import unittest from test.optimization import QiskitOptimizationTestCase +import math import numpy as np from ddt import ddt, idata, unpack -from qiskit import BasicAer +from qiskit import BasicAer, QuantumCircuit, execute from qiskit.optimization.applications.ising import max_cut from qiskit.optimization.applications.ising.common import sample_most_likely from qiskit.aqua.components.optimizers import COBYLA +from qiskit.aqua.components.initial_states import Custom, Zero from qiskit.aqua.algorithms import QAOA from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.operators import X, I @@ -47,6 +49,8 @@ M2 = None S2 = {'1011', '0100'} +CUSTOM_SUPERPOSITION = [1/math.sqrt(15)] * 15 + [0] + @ddt class TestQAOA(QiskitOptimizationTestCase): @@ -161,6 +165,63 @@ def cb_callback(eval_count, parameters, mean, std): with self.subTest('Solution'): self.assertIn(''.join([str(int(i)) for i in graph_solution]), solutions) + @idata([ + [W2, None], + [W2, [1.0] + 15*[0.0]], + [W2, CUSTOM_SUPERPOSITION] + ]) + @unpack + def test_qaoa_initial_state(self, w, init_state): + """ QAOA initial state test """ + + optimizer = COBYLA() + qubit_op, _ = max_cut.get_operator(w) + + init_pt = [0.0, 0.0] # Avoid generating random initial point + + if init_state is None: + initial_state = None + else: + initial_state = Custom(num_qubits=4, state_vector=init_state) + + quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator')) + qaoa_zero_init_state = QAOA(qubit_op, optimizer, initial_point=init_pt, + initial_state=Zero(qubit_op.num_qubits), + quantum_instance=quantum_instance) + qaoa = QAOA(qubit_op, optimizer, initial_point=init_pt, + initial_state=initial_state, quantum_instance=quantum_instance) + + zero_circuits = qaoa_zero_init_state.construct_circuit(init_pt) + custom_circuits = qaoa.construct_circuit(init_pt) + + self.assertEqual(len(zero_circuits), len(custom_circuits)) + + backend = BasicAer.get_backend('statevector_simulator') + for zero_circ, custom_circ in zip(zero_circuits, custom_circuits): + + z_length = len(zero_circ.data) + c_length = len(custom_circ.data) + + self.assertGreaterEqual(c_length, z_length) + self.assertTrue(zero_circ.data == custom_circ.data[-z_length:]) + + custom_init_qc = custom_circ.copy() + custom_init_qc.data = custom_init_qc.data[0:c_length-z_length] + + if initial_state is None: + original_init_qc = QuantumCircuit(qubit_op.num_qubits) + original_init_qc.h(range(qubit_op.num_qubits)) + else: + original_init_qc = initial_state.construct_circuit() + + job_init_state = execute(original_init_qc, backend) + job_qaoa_init_state = execute(custom_init_qc, backend) + + statevector_original = job_init_state.result().get_statevector(original_init_qc) + statevector_custom = job_qaoa_init_state.result().get_statevector(custom_init_qc) + + self.assertEqual(statevector_original.tolist(), statevector_custom.tolist()) + if __name__ == '__main__': unittest.main()