From 608aadeed059792f4f553b602ffbb1af90df2f9f Mon Sep 17 00:00:00 2001 From: Julien Gacon Date: Tue, 27 Oct 2020 16:13:45 +0100 Subject: [PATCH] move to circuit.lib and use tuple - move the initial state circuit to chemistry.circuit.library - globally replace num_particles by a tuple instead of list of integers --- README.md | 7 +- .../legacy/weighted_pauli_operator.py | 2 +- .../vqe_uccsd_factory.py | 2 +- .../molecular_ground_state_energy.py | 2 +- qiskit/chemistry/circuit/library/__init__.py | 39 ++++++ .../library/initial_states/__init__.py | 18 +++ .../library/initial_states/hartree_fock.py | 116 ++++++++++++++++++ .../circuit/library/initial_states/vscf.py | 60 +++++++++ .../components/initial_states/hartree_fock.py | 88 ++----------- .../components/initial_states/vscf.py | 42 ++----- .../components/variational_forms/uccsd.py | 8 +- qiskit/chemistry/core/hamiltonian.py | 14 +-- .../fermionic_transformation.py | 14 +-- .../circuit/library/test_hartree_fock.py | 62 ++++++++++ test/chemistry/circuit/library/test_vscf.py | 44 +++++++ test/chemistry/test_adapt_vqe.py | 2 +- test/chemistry/test_app_mgse.py | 2 +- test/chemistry/test_bopes_sampler.py | 5 +- test/chemistry/test_chc_vscf.py | 5 +- test/chemistry/test_core_hamiltonian.py | 2 +- .../test_core_hamiltonian_orb_reduce.py | 10 +- test/chemistry/test_end2end_with_iqpe.py | 2 +- test/chemistry/test_end2end_with_qpe.py | 2 +- .../test_fermionic_transformation.py | 2 +- ...est_fermionic_transformation_orb_reduce.py | 10 +- .../test_initial_state_hartree_fock.py | 41 ------- test/chemistry/test_initial_state_vscf.py | 25 +--- test/chemistry/test_qeom_vqe.py | 2 +- test/chemistry/test_readme_sample.py | 7 +- test/chemistry/test_swaprz.py | 5 +- test/chemistry/test_symmetries.py | 2 +- test/chemistry/test_uccsd_advanced.py | 2 +- test/chemistry/test_uccsd_hartree_fock.py | 5 +- test/chemistry/test_uvcc_vscf.py | 5 +- test/chemistry/test_vqe_uccsd_adapt.py | 2 +- 35 files changed, 431 insertions(+), 225 deletions(-) create mode 100644 qiskit/chemistry/circuit/library/__init__.py create mode 100644 qiskit/chemistry/circuit/library/initial_states/__init__.py create mode 100644 qiskit/chemistry/circuit/library/initial_states/hartree_fock.py create mode 100644 qiskit/chemistry/circuit/library/initial_states/vscf.py create mode 100644 test/chemistry/circuit/library/test_hartree_fock.py create mode 100644 test/chemistry/circuit/library/test_vscf.py diff --git a/README.md b/README.md index 12df2a29a7..5c9275036c 100644 --- a/README.md +++ b/README.md @@ -223,12 +223,15 @@ from qiskit.aqua.components.optimizers import L_BFGS_B optimizer = L_BFGS_B() # setup the initial state for the variational form -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock init_state = HartreeFock(num_spin_orbitals, num_particles) # setup the variational form for VQE from qiskit.circuit.library import TwoLocal -var_form = TwoLocal(num_qubits, ['ry', 'rz'], 'cz', initial_state=init_state) +var_form = TwoLocal(num_qubits, ['ry', 'rz'], 'cz') + +# add the initial state +var_form.compose(init_state, front=True) # setup and run VQE from qiskit.aqua.algorithms import VQE diff --git a/qiskit/aqua/operators/legacy/weighted_pauli_operator.py b/qiskit/aqua/operators/legacy/weighted_pauli_operator.py index 0893cbf863..4f1ab27649 100644 --- a/qiskit/aqua/operators/legacy/weighted_pauli_operator.py +++ b/qiskit/aqua/operators/legacy/weighted_pauli_operator.py @@ -1250,7 +1250,7 @@ def two_qubit_reduction(operator, num_particles): "Return the empty operator back.") return operator - if isinstance(num_particles, list): + if isinstance(num_particles, (tuple, list)): num_alpha = num_particles[0] num_beta = num_particles[1] else: diff --git a/qiskit/chemistry/algorithms/ground_state_solvers/minimum_eigensolver_factories/vqe_uccsd_factory.py b/qiskit/chemistry/algorithms/ground_state_solvers/minimum_eigensolver_factories/vqe_uccsd_factory.py index c1623f6d4c..eb430d20e3 100644 --- a/qiskit/chemistry/algorithms/ground_state_solvers/minimum_eigensolver_factories/vqe_uccsd_factory.py +++ b/qiskit/chemistry/algorithms/ground_state_solvers/minimum_eigensolver_factories/vqe_uccsd_factory.py @@ -22,7 +22,7 @@ from ....components.variational_forms import UCCSD from ....transformations import Transformation from ....transformations.fermionic_transformation import FermionicTransformation -from ....components.initial_states import HartreeFock +from ....circuit.library import HartreeFock from .minimum_eigensolver_factory import MinimumEigensolverFactory diff --git a/qiskit/chemistry/applications/molecular_ground_state_energy.py b/qiskit/chemistry/applications/molecular_ground_state_energy.py index eecec094e5..63521f284b 100644 --- a/qiskit/chemistry/applications/molecular_ground_state_energy.py +++ b/qiskit/chemistry/applications/molecular_ground_state_energy.py @@ -21,7 +21,7 @@ from qiskit.aqua.algorithms import MinimumEigensolver, VQE from qiskit.aqua.operators import Z2Symmetries from qiskit.chemistry import QiskitChemistryError -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.core import (Hamiltonian, TransformationType, QubitMappingType, ChemistryOperator, MolecularGroundStateResult) diff --git a/qiskit/chemistry/circuit/library/__init__.py b/qiskit/chemistry/circuit/library/__init__.py new file mode 100644 index 0000000000..036a8bee87 --- /dev/null +++ b/qiskit/chemistry/circuit/library/__init__.py @@ -0,0 +1,39 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2020. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +""" +=================================================================== +Chemistry Circuit Library (:mod:`qiskit.chemistry.circuit.library`) +=================================================================== + +A collection of circuits used as building blocks or inputs of algorithms in chemistry. + +.. currentmodule:: qiskit.chemistry.circuit.library + +Initial states +============== + +.. autosummary:: + :toctree: ../stubs/ + :nosignatures: + + HartreeFock + VSCF + +""" + +from .initial_states import ( + HartreeFock, + VSCF +) + +__all__ = ['HartreeFock', 'VSCF'] diff --git a/qiskit/chemistry/circuit/library/initial_states/__init__.py b/qiskit/chemistry/circuit/library/initial_states/__init__.py new file mode 100644 index 0000000000..82b47043a6 --- /dev/null +++ b/qiskit/chemistry/circuit/library/initial_states/__init__.py @@ -0,0 +1,18 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2020. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Initial state circuits.""" + +from .hartree_fock import HartreeFock +from .vscf import VSCF + +__all__ = ['HartreeFock', 'VSCF'] diff --git a/qiskit/chemistry/circuit/library/initial_states/hartree_fock.py b/qiskit/chemistry/circuit/library/initial_states/hartree_fock.py new file mode 100644 index 0000000000..c279a0f089 --- /dev/null +++ b/qiskit/chemistry/circuit/library/initial_states/hartree_fock.py @@ -0,0 +1,116 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2018, 2020. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Hartree-Fock initial state.""" + +import warnings +from typing import Optional, Union, List, Tuple +import logging +import numpy as np +from qiskit import QuantumRegister, QuantumCircuit +from qiskit.aqua.utils.validation import validate_min, validate_in_set + +logger = logging.getLogger(__name__) + + +class HartreeFock(QuantumCircuit): + """A Hartree-Fock initial state.""" + + def __init__(self, + num_orbitals: int, + num_particles: Union[Tuple[int, int], int], + qubit_mapping: str = 'parity', + two_qubit_reduction: bool = True, + sq_list: Optional[List[int]] = None) -> None: + """ + Args: + num_orbitals: number of spin orbitals, has a min. value of 1. + num_particles: number of particles, if it is a list, the first number + is alpha and the second number if beta. + qubit_mapping: mapping type for qubit operator + two_qubit_reduction: flag indicating whether or not two qubit is reduced + sq_list: position of the single-qubit operators that + anticommute with the cliffords + + Raises: + ValueError: wrong setting in num_particles and num_orbitals. + ValueError: wrong setting for computed num_qubits and supplied num_qubits. + """ + # validate the input + validate_min('num_orbitals', num_orbitals, 1) + validate_in_set('qubit_mapping', qubit_mapping, + {'jordan_wigner', 'parity', 'bravyi_kitaev'}) + + if qubit_mapping != 'parity' and two_qubit_reduction: + warnings.warn('two_qubit_reduction only works with parity qubit mapping ' + 'but you have %s. We switch two_qubit_reduction ' + 'to False.' % qubit_mapping) + two_qubit_reduction = False + + # get the bitstring encoding the Hartree Fock state + bitstr = _build_bitstr(num_orbitals, num_particles, qubit_mapping, + two_qubit_reduction, sq_list) + + # construct the circuit + qr = QuantumRegister(len(bitstr), 'q') + super().__init__(qr, name='HF') + + # add gates in the right positions + for i, bit in enumerate(reversed(bitstr)): + if bit: + self.x(i) + + +def _build_bitstr(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction=True, + sq_list=None): + if isinstance(num_particles, tuple): + num_alpha, num_beta = num_particles + else: + logger.info('We assume that the number of alphas and betas are the same.') + num_alpha = num_beta = num_particles // 2 + + num_particles = num_alpha + num_beta + + if num_particles > num_orbitals: + raise ValueError('# of particles must be less than or equal to # of orbitals.') + + half_orbitals = num_orbitals // 2 + bitstr = np.zeros(num_orbitals, np.bool) + bitstr[-num_alpha:] = True + bitstr[-(half_orbitals + num_beta):-half_orbitals] = True + + if qubit_mapping == 'parity': + new_bitstr = bitstr.copy() + + t_r = np.triu(np.ones((num_orbitals, num_orbitals))) + new_bitstr = t_r.dot(new_bitstr.astype(np.int)) % 2 # pylint: disable=no-member + + bitstr = np.append(new_bitstr[1:half_orbitals], new_bitstr[half_orbitals + 1:]) \ + if two_qubit_reduction else new_bitstr + + elif qubit_mapping == 'bravyi_kitaev': + binary_superset_size = int(np.ceil(np.log2(num_orbitals))) + beta = 1 + basis = np.asarray([[1, 0], [0, 1]]) + for _ in range(binary_superset_size): + beta = np.kron(basis, beta) + beta[0, :] = 1 + start_idx = beta.shape[0] - num_orbitals + beta = beta[start_idx:, start_idx:] + new_bitstr = beta.dot(bitstr.astype(int)) % 2 + bitstr = new_bitstr.astype(np.bool) + + if sq_list is not None: + sq_list = [len(bitstr) - 1 - position for position in sq_list] + bitstr = np.delete(bitstr, sq_list) + + return bitstr.astype(np.bool) diff --git a/qiskit/chemistry/circuit/library/initial_states/vscf.py b/qiskit/chemistry/circuit/library/initial_states/vscf.py new file mode 100644 index 0000000000..8a877e6edc --- /dev/null +++ b/qiskit/chemistry/circuit/library/initial_states/vscf.py @@ -0,0 +1,60 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2020. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Initial state for vibrational modes.""" + +from typing import List + +import numpy as np + +from qiskit import QuantumRegister, QuantumCircuit + + +class VSCF(QuantumCircuit): + r"""Initial state for vibrational modes. + + Creates an occupation number vector as defined in [1]. + As example, for 2 modes with 4 modals per mode it creates: :math:`|1000 1000\rangle`. + + References: + + [1] Ollitrault Pauline J., Chemical science 11 (2020): 6842-6855. + """ + + def __init__(self, basis: List[int]) -> None: + """ + Args: + basis: Is a list defining the number of modals per mode. E.g. for a 3 modes system + with 4 modals per mode basis = [4,4,4] + """ + # get the bitstring encoding initial state + bitstr = _build_bitstr(basis) + + # construct the circuit + qr = QuantumRegister(len(bitstr), 'q') + super().__init__(qr, name='VSCF') + + # add gates in the right positions + for i, bit in enumerate(reversed(bitstr)): + if bit: + self.x(i) + + +def _build_bitstr(basis): + num_qubits = sum(basis) + bitstr = np.zeros(num_qubits, np.bool) + count = 0 + for modal in basis: + bitstr[num_qubits - count - 1] = True + count += modal + + return bitstr diff --git a/qiskit/chemistry/components/initial_states/hartree_fock.py b/qiskit/chemistry/components/initial_states/hartree_fock.py index 63ab43b498..74579f0e00 100644 --- a/qiskit/chemistry/components/initial_states/hartree_fock.py +++ b/qiskit/chemistry/components/initial_states/hartree_fock.py @@ -13,22 +13,23 @@ """Hartree-Fock initial state.""" import warnings -from typing import Optional, Union, List, Tuple +from typing import Optional, Union, List import logging import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.utils.validation import validate_min, validate_in_set from qiskit.aqua.components.initial_states import InitialState +from qiskit.chemistry.circuit.library.initial_states.hartree_fock import _build_bitstr logger = logging.getLogger(__name__) -class HartreeFock(QuantumCircuit, InitialState): +class HartreeFock(InitialState): """A Hartree-Fock initial state.""" def __init__(self, num_orbitals: int, - num_particles: Union[Tuple[int, int], List[int], int], + num_particles: Union[List[int], int], qubit_mapping: str = 'parity', two_qubit_reduction: bool = True, sq_list: Optional[List[int]] = None) -> None: @@ -57,27 +58,16 @@ def __init__(self, 'to False.' % qubit_mapping) two_qubit_reduction = False - if isinstance(num_particles, list): - warnings.warn('The ``num_particles`` argument should either be a single integer or a ' - 'tuple of two integers, not a list. This behavious is deprecated as of ' - 'Aqua 0.9 and will be removed no earlier than 3 months after the ' - 'release.', DeprecationWarning, stacklevel=2) - num_particles = tuple(num_particles) # type: ignore + super().__init__() # get the bitstring encoding the Hartree Fock state + if isinstance(num_particles, list): + num_particles = tuple(num_particles) + bitstr = _build_bitstr(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, sq_list) self._bitstr = bitstr - # construct the circuit - qr = QuantumRegister(len(bitstr), 'q') - super().__init__(qr, name='HF') - - # add gates in the right positions - for i, bit in enumerate(reversed(bitstr)): - if bit: - self.x(i) - def construct_circuit(self, mode='circuit', register=None): """Construct the statevector of desired initial state. @@ -93,10 +83,6 @@ def construct_circuit(self, mode='circuit', register=None): Raises: ValueError: when mode is not 'vector' or 'circuit'. """ - warnings.warn('The HartreeFock.construct_circuit method is deprecated as of Aqua 0.9.0 and ' - 'will be removed no earlier than 3 months after the release. The HarteeFock ' - 'class is now a QuantumCircuit instance and can directly be used as such.', - DeprecationWarning, stacklevel=2) if mode == 'vector': state = 1.0 one = np.asarray([0.0, 1.0]) @@ -106,9 +92,11 @@ def construct_circuit(self, mode='circuit', register=None): return state elif mode == 'circuit': if register is None: - register = QuantumRegister(self.num_qubits, name='q') - quantum_circuit = QuantumCircuit(register) - quantum_circuit.compose(self, inplace=True) + register = QuantumRegister(len(self.bitstr), name='q') + quantum_circuit = QuantumCircuit(register, name='HF') + for i, bit in enumerate(reversed(self.bitstr)): + if bit: + quantum_circuit.x(i) return quantum_circuit else: raise ValueError('Mode should be either "vector" or "circuit"') @@ -116,54 +104,4 @@ def construct_circuit(self, mode='circuit', register=None): @property def bitstr(self): """Getter of the bit string represented the statevector.""" - warnings.warn('The HartreeFock.bitstr property is deprecated as of Aqua 0.9.0 and will be ' - 'removed no earlier than 3 months after the release. To get the bitstring ' - 'you can use the quantum_info.Statevector class and the probabilities_dict ' - 'method.', DeprecationWarning, stacklevel=2) return self._bitstr - - -def _build_bitstr(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction=True, - sq_list=None): - if isinstance(num_particles, tuple): - num_alpha, num_beta = num_particles - else: - logger.info('We assume that the number of alphas and betas are the same.') - num_alpha = num_beta = num_particles // 2 - - num_particles = num_alpha + num_beta - - if num_particles > num_orbitals: - raise ValueError('# of particles must be less than or equal to # of orbitals.') - - half_orbitals = num_orbitals // 2 - bitstr = np.zeros(num_orbitals, np.bool) - bitstr[-num_alpha:] = True - bitstr[-(half_orbitals + num_beta):-half_orbitals] = True - - if qubit_mapping == 'parity': - new_bitstr = bitstr.copy() - - t_r = np.triu(np.ones((num_orbitals, num_orbitals))) - new_bitstr = t_r.dot(new_bitstr.astype(np.int)) % 2 # pylint: disable=no-member - - bitstr = np.append(new_bitstr[1:half_orbitals], new_bitstr[half_orbitals + 1:]) \ - if two_qubit_reduction else new_bitstr - - elif qubit_mapping == 'bravyi_kitaev': - binary_superset_size = int(np.ceil(np.log2(num_orbitals))) - beta = 1 - basis = np.asarray([[1, 0], [0, 1]]) - for _ in range(binary_superset_size): - beta = np.kron(basis, beta) - beta[0, :] = 1 - start_idx = beta.shape[0] - num_orbitals - beta = beta[start_idx:, start_idx:] - new_bitstr = beta.dot(bitstr.astype(int)) % 2 - bitstr = new_bitstr.astype(np.bool) - - if sq_list is not None: - sq_list = [len(bitstr) - 1 - position for position in sq_list] - bitstr = np.delete(bitstr, sq_list) - - return bitstr.astype(np.bool) diff --git a/qiskit/chemistry/components/initial_states/vscf.py b/qiskit/chemistry/components/initial_states/vscf.py index 5893ed81dd..8a0b73b5ad 100644 --- a/qiskit/chemistry/components/initial_states/vscf.py +++ b/qiskit/chemistry/components/initial_states/vscf.py @@ -13,7 +13,6 @@ """ Initial state for vibrational modes. """ import logging -import warnings from typing import List import numpy as np @@ -21,10 +20,12 @@ from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.initial_states import InitialState +from qiskit.chemistry.circuit.library.initial_states.vscf import _build_bitstr + logger = logging.getLogger(__name__) -class VSCF(QuantumCircuit, InitialState): +class VSCF(InitialState): r"""Initial state for vibrational modes. Creates an occupation number vector as defined in @@ -42,14 +43,7 @@ def __init__(self, basis: List[int]) -> None: bitstr = _build_bitstr(basis) self._bitstr = bitstr - # construct the circuit - qr = QuantumRegister(len(bitstr), 'q') - super().__init__(qr, name='VSCF') - - # add gates in the right positions - for i, bit in enumerate(reversed(bitstr)): - if bit: - self.x(i) + super().__init__() def construct_circuit(self, mode='circuit', register=None): """Construct the statevector of desired initial state. @@ -66,10 +60,6 @@ def construct_circuit(self, mode='circuit', register=None): Raises: ValueError: when mode is not 'vector' or 'circuit'. """ - warnings.warn('The VSCF.construct_circuit method is deprecated as of Aqua 0.9.0 and ' - 'will be removed no earlier than 3 months after the release. The HarteeFock ' - 'class is now a QuantumCircuit instance and can directly be used as such.', - DeprecationWarning, stacklevel=2) if mode == 'vector': state = 1.0 one = np.asarray([0.0, 1.0]) @@ -79,9 +69,12 @@ def construct_circuit(self, mode='circuit', register=None): return state elif mode == 'circuit': if register is None: - register = QuantumRegister(self.num_qubits, name='q') - quantum_circuit = QuantumCircuit(register) - quantum_circuit.compose(self, inplace=True) + register = QuantumRegister(len(self.bitstr), name='q') + quantum_circuit = QuantumCircuit(register, name='VSCF') + for i, bit in enumerate(reversed(self.bitstr)): + if bit: + quantum_circuit.x(i) + return quantum_circuit else: raise ValueError('Mode should be either "vector" or "circuit"') @@ -89,19 +82,4 @@ def construct_circuit(self, mode='circuit', register=None): @property def bitstr(self): """Getter of the bit string represented the statevector.""" - warnings.warn('The VSCF.bitstr property is deprecated as of Aqua 0.9.0 and will be ' - 'removed no earlier than 3 months after the release. To get the bitstring ' - 'you can use the quantum_info.Statevector class and the probabilities_dict ' - 'method.', DeprecationWarning, stacklevel=2) return self._bitstr - - -def _build_bitstr(basis): - num_qubits = sum(basis) - bitstr = np.zeros(num_qubits, np.bool) - count = 0 - for modal in basis: - bitstr[num_qubits - count - 1] = True - count += modal - - return bitstr diff --git a/qiskit/chemistry/components/variational_forms/uccsd.py b/qiskit/chemistry/components/variational_forms/uccsd.py index db62590826..0ec88d8e08 100644 --- a/qiskit/chemistry/components/variational_forms/uccsd.py +++ b/qiskit/chemistry/components/variational_forms/uccsd.py @@ -17,7 +17,7 @@ And for singlet q-UCCD (full) and pair q-UCCD see: https://arxiv.org/abs/1911.10864 """ -from typing import Optional, Union, List +from typing import Optional, Union, List, Tuple import logging import sys import collections @@ -48,7 +48,7 @@ class UCCSD(VariationalForm): def __init__(self, num_orbitals: int, - num_particles: Union[List[int], int], + num_particles: Union[Tuple[int, int], List[int], int], reps: int = 1, active_occupied: Optional[List[int]] = None, active_unoccupied: Optional[List[int]] = None, @@ -118,7 +118,7 @@ def __init__(self, else self._num_qubits - len(self._z2_symmetries.sq_list) self._reps = reps self._num_orbitals = num_orbitals - if isinstance(num_particles, list): + if isinstance(num_particles, (tuple, list)): self._num_alpha = num_particles[0] self._num_beta = num_particles[1] else: @@ -490,7 +490,7 @@ def compute_excitation_lists(num_particles, num_orbitals, active_occ_list=None, ValueError: invalid setting of number of orbitals """ - if isinstance(num_particles, list): + if isinstance(num_particles, (tuple, list)): num_alpha = num_particles[0] num_beta = num_particles[1] else: diff --git a/qiskit/chemistry/core/hamiltonian.py b/qiskit/chemistry/core/hamiltonian.py index 847be15fcb..9fe48891cd 100644 --- a/qiskit/chemistry/core/hamiltonian.py +++ b/qiskit/chemistry/core/hamiltonian.py @@ -26,7 +26,6 @@ from .chemistry_operator import (ChemistryOperator, MolecularGroundStateResult, DipoleTuple) -from ..components.initial_states import HartreeFock logger = logging.getLogger(__name__) @@ -264,7 +263,7 @@ def _dipole_op(dipole_integrals, axis): logger.info('Molecule num spin orbitals: %s, remaining for processing: %s', nspinorbs, new_nspinorbs) - self._add_molecule_info(self.INFO_NUM_PARTICLES, [new_num_alpha, new_num_beta]) + self._add_molecule_info(self.INFO_NUM_PARTICLES, (new_num_alpha, new_num_beta)) self._add_molecule_info(self.INFO_NUM_ORBITALS, new_nspinorbs) self._add_molecule_info(self.INFO_TWO_QUBIT_REDUCTION, self._two_qubit_reduction @@ -306,11 +305,12 @@ def _process_z2symmetry_reduction(self, qubit_op, aux_ops): aux_ops[i] = None # Discard since no meaningful measurement can be done if self._z2symmetry_reduction == 'auto': - hf_state = HartreeFock(num_orbitals=self._molecule_info[self.INFO_NUM_ORBITALS], - qubit_mapping=self._qubit_mapping, - two_qubit_reduction=self._two_qubit_reduction, - num_particles=self._molecule_info[self.INFO_NUM_PARTICLES]) - z2_symmetries = Hamiltonian._pick_sector(z2_symmetries, hf_state.bitstr) + from ..circuit.library.initial_states.hartree_fock import _build_bitstr + hf_bitstr = _build_bitstr(num_orbitals=self._molecule_info['num_orbitals'], + qubit_mapping=self._qubit_mapping, + two_qubit_reduction=self._two_qubit_reduction, + num_particles=self._molecule_info['num_particles']) + z2_symmetries = Hamiltonian._pick_sector(z2_symmetries, hf_bitstr) else: if len(self._z2symmetry_reduction) != len(z2_symmetries.symmetries): raise QiskitChemistryError('z2symmetry_reduction tapering values list has ' diff --git a/qiskit/chemistry/transformations/fermionic_transformation.py b/qiskit/chemistry/transformations/fermionic_transformation.py index 36e39b718a..e16c04bc59 100644 --- a/qiskit/chemistry/transformations/fermionic_transformation.py +++ b/qiskit/chemistry/transformations/fermionic_transformation.py @@ -33,7 +33,6 @@ from qiskit.chemistry.components.variational_forms import UCCSD from .transformation import Transformation -from ..components.initial_states import HartreeFock logger = logging.getLogger(__name__) @@ -364,7 +363,7 @@ def _dipole_op(dipole_integrals: np.ndarray, axis: str) \ logger.info('Molecule num spin orbitals: %s, remaining for processing: %s', nspinorbs, new_nspinorbs) - self._molecule_info['num_particles'] = [new_num_alpha, new_num_beta] + self._molecule_info['num_particles'] = (new_num_alpha, new_num_beta) self._molecule_info['num_orbitals'] = new_nspinorbs reduction = self._two_qubit_reduction if self._qubit_mapping == 'parity' else False self._molecule_info['two_qubit_reduction'] = reduction @@ -425,11 +424,12 @@ def _process_z2symmetry_reduction(self, aux_ops[i] = None # Discard since no meaningful measurement can be done if self._z2symmetry_reduction == 'auto': - hf_state = HartreeFock(num_orbitals=self._molecule_info['num_orbitals'], - qubit_mapping=self._qubit_mapping, - two_qubit_reduction=self._two_qubit_reduction, - num_particles=self._molecule_info['num_particles']) - z2_symmetries = FermionicTransformation._pick_sector(z2_symmetries, hf_state.bitstr) + from ..circuit.library.initial_states.hartree_fock import _build_bitstr + hf_bitstr = _build_bitstr(num_orbitals=self._molecule_info['num_orbitals'], + qubit_mapping=self._qubit_mapping, + two_qubit_reduction=self._two_qubit_reduction, + num_particles=self._molecule_info['num_particles']) + z2_symmetries = FermionicTransformation._pick_sector(z2_symmetries, hf_bitstr) else: if len(self._z2symmetry_reduction) != len(z2_symmetries.symmetries): raise QiskitChemistryError('z2symmetry_reduction tapering values list has ' diff --git a/test/chemistry/circuit/library/test_hartree_fock.py b/test/chemistry/circuit/library/test_hartree_fock.py new file mode 100644 index 0000000000..c91aa3dc86 --- /dev/null +++ b/test/chemistry/circuit/library/test_hartree_fock.py @@ -0,0 +1,62 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2020. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Test Hartree Fock initial state circuit.""" + +import unittest +from test.chemistry import QiskitChemistryTestCase + +from qiskit import QuantumCircuit +from qiskit.chemistry.circuit.library import HartreeFock + + +class TestHartreeFock(QiskitChemistryTestCase): + """ Initial State HartreeFock tests """ + + def test_qubits_4_jw_h2(self): + """ qubits 4 jw h2 test """ + state = HartreeFock(4, (1, 1), 'jordan_wigner', False) + ref = QuantumCircuit(4) + ref.x([0, 2]) + self.assertEqual(state, ref) + + def test_qubits_4_py_h2(self): + """ qubits 4 py h2 test """ + state = HartreeFock(4, (1, 1), 'parity', False) + ref = QuantumCircuit(4) + ref.x([0, 1]) + self.assertEqual(state, ref) + + def test_qubits_4_bk_h2(self): + """ qubits 4 bk h2 test """ + state = HartreeFock(4, (1, 1), 'bravyi_kitaev', False) + ref = QuantumCircuit(4) + ref.x([0, 1, 2]) + self.assertEqual(state, ref) + + def test_qubits_2_py_h2(self): + """ qubits 2 py h2 test """ + state = HartreeFock(4, 2, 'parity', True) + ref = QuantumCircuit(2) + ref.x(0) + self.assertEqual(state, ref) + + def test_qubits_6_py_lih(self): + """ qubits 6 py lih test """ + state = HartreeFock(10, (1, 1), 'parity', True, [1, 2]) + ref = QuantumCircuit(6) + ref.x([0, 1]) + self.assertEqual(state, ref) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/chemistry/circuit/library/test_vscf.py b/test/chemistry/circuit/library/test_vscf.py new file mode 100644 index 0000000000..dbc4e38a30 --- /dev/null +++ b/test/chemistry/circuit/library/test_vscf.py @@ -0,0 +1,44 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2018, 2020. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Test the VSCF initial state.""" + +import unittest +from test.chemistry import QiskitChemistryTestCase +from qiskit import QuantumCircuit +from qiskit.chemistry.circuit.library import VSCF + + +class TestVSCF(QiskitChemistryTestCase): + """ Initial State vscf tests """ + + def test_qubits_4(self): + """Test 2 modes 2 modals.""" + basis = [2, 2] + vscf = VSCF(basis) + ref = QuantumCircuit(4) + ref.x([0, 2]) + + self.assertEqual(ref, vscf) + + def test_qubits_5(self): + """Test 2 modes 2 modals for the first mode and 3 modals for the second.""" + basis = [2, 3] + vscf = VSCF(basis) + ref = QuantumCircuit(5) + ref.x([0, 2]) + + self.assertEqual(ref, vscf) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/chemistry/test_adapt_vqe.py b/test/chemistry/test_adapt_vqe.py index eee14a0a64..abd9f47ee5 100644 --- a/test/chemistry/test_adapt_vqe.py +++ b/test/chemistry/test_adapt_vqe.py @@ -20,7 +20,7 @@ from qiskit.aqua.algorithms import VQE from qiskit.chemistry import QiskitChemistryError from qiskit.chemistry.components.variational_forms import UCCSD -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.aqua.components.optimizers import L_BFGS_B from qiskit.chemistry.algorithms.ground_state_solvers import AdaptVQE, VQEUCCSDFactory from qiskit.chemistry.transformations import FermionicTransformation diff --git a/test/chemistry/test_app_mgse.py b/test/chemistry/test_app_mgse.py index ed6823210f..1e1b08ea9c 100644 --- a/test/chemistry/test_app_mgse.py +++ b/test/chemistry/test_app_mgse.py @@ -25,7 +25,7 @@ from qiskit.aqua.components.optimizers import SLSQP from qiskit.chemistry import QiskitChemistryError from qiskit.chemistry.applications import MolecularGroundStateEnergy -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.core import QubitMappingType from qiskit.chemistry.drivers import PySCFDriver, UnitsType diff --git a/test/chemistry/test_bopes_sampler.py b/test/chemistry/test_bopes_sampler.py index 97a7ec183e..1ee2538a33 100644 --- a/test/chemistry/test_bopes_sampler.py +++ b/test/chemistry/test_bopes_sampler.py @@ -23,7 +23,7 @@ from qiskit.aqua.components.optimizers import AQGD from qiskit.aqua.operators import PauliExpectation from qiskit.chemistry.algorithms.pes_samplers.bopes_sampler import BOPESSampler -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.drivers import Molecule, PySCFDriver from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit.chemistry.algorithms.pes_samplers.potentials.morse_potential import MorsePotential @@ -65,7 +65,8 @@ def test_h2_bopes_sampler(self): sq_list=f_t._molecule_info['z2_symmetries'].sq_list ) var_form = RealAmplitudes(qubitop.num_qubits, reps=1, entanglement='full', - initial_state=i_state, skip_unentangled_qubits=False) + skip_unentangled_qubits=False) + var_form.compose(i_state, front=True) # Classical optimizer: # Analytic Quantum Gradient Descent (AQGD) (with Epochs) diff --git a/test/chemistry/test_chc_vscf.py b/test/chemistry/test_chc_vscf.py index 7bdfa9f421..bf26ef4219 100644 --- a/test/chemistry/test_chc_vscf.py +++ b/test/chemistry/test_chc_vscf.py @@ -13,6 +13,7 @@ """ Test of CHC and VSCF Aqua extensions """ import unittest +import warnings from test.chemistry import QiskitChemistryTestCase @@ -62,7 +63,9 @@ def test_chc_vscf(self): bosonic_op = BosonicOperator(co2_2modes_2modals_2body, basis) qubit_op = bosonic_op.mapping('direct', threshold=1e-5) - init_state = VSCF(basis) + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=DeprecationWarning) + init_state = VSCF(basis) num_qubits = sum(basis) uvcc_varform = UVCC(num_qubits, basis, [0, 1]) diff --git a/test/chemistry/test_core_hamiltonian.py b/test/chemistry/test_core_hamiltonian.py index 227ffa3f9c..23b3597a76 100644 --- a/test/chemistry/test_core_hamiltonian.py +++ b/test/chemistry/test_core_hamiltonian.py @@ -44,7 +44,7 @@ def _validate_vars(self, core, energy_shift=0.0, ph_energy_shift=0.0): def _validate_info(self, core, num_particles=None, num_orbitals=4, actual_two_qubit_reduction=False): - num_particles = num_particles if num_particles is not None else [1, 1] + num_particles = num_particles if num_particles is not None else (1, 1) z2symmetries = core.molecule_info.pop('z2symmetries') self.assertEqual(z2symmetries.is_empty(), True) self.assertEqual(core.molecule_info, {'num_particles': num_particles, diff --git a/test/chemistry/test_core_hamiltonian_orb_reduce.py b/test/chemistry/test_core_hamiltonian_orb_reduce.py index 8573c43d61..8bd066b97c 100644 --- a/test/chemistry/test_core_hamiltonian_orb_reduce.py +++ b/test/chemistry/test_core_hamiltonian_orb_reduce.py @@ -44,7 +44,7 @@ def _validate_vars(self, core, energy_shift=0.0, ph_energy_shift=0.0): def _validate_info(self, core, num_particles=None, num_orbitals=12, actual_two_qubit_reduction=False): - num_particles = num_particles if num_particles is not None else [2, 2] + num_particles = num_particles if num_particles is not None else (2, 2) z2symmetries = core.molecule_info.pop('z2symmetries') self.assertEqual(z2symmetries.is_empty(), True) self.assertEqual(core.molecule_info, {'num_particles': num_particles, @@ -96,7 +96,7 @@ def test_freeze_core(self): warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.qmolecule) self._validate_vars(core, energy_shift=-7.7962196) - self._validate_info(core, num_particles=[1, 1], num_orbitals=10) + self._validate_info(core, num_particles=(1, 1), num_orbitals=10) self._validate_input_object(qubit_op, num_qubits=10, num_paulis=276) def test_freeze_core_orb_reduction(self): @@ -110,7 +110,7 @@ def test_freeze_core_orb_reduction(self): warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.qmolecule) self._validate_vars(core, energy_shift=-7.7962196) - self._validate_info(core, num_particles=[1, 1], num_orbitals=6) + self._validate_info(core, num_particles=(1, 1), num_orbitals=6) self._validate_input_object(qubit_op, num_qubits=6, num_paulis=118) def test_freeze_core_all_reduction(self): @@ -124,7 +124,7 @@ def test_freeze_core_all_reduction(self): warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.qmolecule) self._validate_vars(core, energy_shift=-7.7962196) - self._validate_info(core, num_particles=[1, 1], num_orbitals=6, + self._validate_info(core, num_particles=(1, 1), num_orbitals=6, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=4, num_paulis=100) @@ -139,7 +139,7 @@ def test_freeze_core_all_reduction_ph(self): warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.qmolecule) self._validate_vars(core, energy_shift=-7.7962196, ph_energy_shift=-1.05785247) - self._validate_info(core, num_particles=[1, 1], num_orbitals=6, + self._validate_info(core, num_particles=(1, 1), num_orbitals=6, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=4, num_paulis=52) diff --git a/test/chemistry/test_end2end_with_iqpe.py b/test/chemistry/test_end2end_with_iqpe.py index 459224563e..9441e4fc18 100644 --- a/test/chemistry/test_end2end_with_iqpe.py +++ b/test/chemistry/test_end2end_with_iqpe.py @@ -23,7 +23,7 @@ from qiskit.aqua.operators import Z2Symmetries from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator, QiskitChemistryError -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock @ddt diff --git a/test/chemistry/test_end2end_with_qpe.py b/test/chemistry/test_end2end_with_qpe.py index f990dfdc50..0261d54691 100644 --- a/test/chemistry/test_end2end_with_qpe.py +++ b/test/chemistry/test_end2end_with_qpe.py @@ -24,7 +24,7 @@ from qiskit.aqua.operators import Z2Symmetries from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator, QiskitChemistryError -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock @ddt diff --git a/test/chemistry/test_fermionic_transformation.py b/test/chemistry/test_fermionic_transformation.py index 0c5345f826..82ad8663ba 100644 --- a/test/chemistry/test_fermionic_transformation.py +++ b/test/chemistry/test_fermionic_transformation.py @@ -44,7 +44,7 @@ def _validate_vars(self, fermionic_transformation, energy_shift=0.0, ph_energy_s def _validate_info(self, fermionic_transformation, num_particles=None, num_orbitals=4, actual_two_qubit_reduction=False): - num_particles = num_particles if num_particles is not None else [1, 1] + num_particles = num_particles if num_particles is not None else (1, 1) z2symmetries = fermionic_transformation.molecule_info.pop('z2_symmetries') self.assertEqual(z2symmetries.is_empty(), True) self.assertEqual(fermionic_transformation.molecule_info, diff --git a/test/chemistry/test_fermionic_transformation_orb_reduce.py b/test/chemistry/test_fermionic_transformation_orb_reduce.py index 8a95edea1f..4d7f7ea635 100644 --- a/test/chemistry/test_fermionic_transformation_orb_reduce.py +++ b/test/chemistry/test_fermionic_transformation_orb_reduce.py @@ -43,7 +43,7 @@ def _validate_vars(self, fermionic_transformation, energy_shift=0.0, ph_energy_s def _validate_info(self, fermionic_transformation, num_particles=None, num_orbitals=12, actual_two_qubit_reduction=False): - num_particles = num_particles if num_particles is not None else [2, 2] + num_particles = num_particles if num_particles is not None else (2, 2) z2symmetries = fermionic_transformation.molecule_info.pop('z2_symmetries') self.assertEqual(z2symmetries.is_empty(), True) self.assertEqual(fermionic_transformation.molecule_info, @@ -96,7 +96,7 @@ def test_freeze_core(self): qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196) - self._validate_info(fermionic_transformation, num_particles=[1, 1], num_orbitals=10) + self._validate_info(fermionic_transformation, num_particles=(1, 1), num_orbitals=10) self._validate_input_object(qubit_op, num_qubits=10, num_paulis=276) def test_freeze_core_orb_reduction(self): @@ -110,7 +110,7 @@ def test_freeze_core_orb_reduction(self): qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196) - self._validate_info(fermionic_transformation, num_particles=[1, 1], num_orbitals=6) + self._validate_info(fermionic_transformation, num_particles=(1, 1), num_orbitals=6) self._validate_input_object(qubit_op, num_qubits=6, num_paulis=118) def test_freeze_core_all_reduction(self): @@ -124,7 +124,7 @@ def test_freeze_core_all_reduction(self): qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196) - self._validate_info(fermionic_transformation, num_particles=[1, 1], num_orbitals=6, + self._validate_info(fermionic_transformation, num_particles=(1, 1), num_orbitals=6, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=4, num_paulis=100) @@ -140,7 +140,7 @@ def test_freeze_core_all_reduction_ph(self): qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196, ph_energy_shift=-1.05785247) - self._validate_info(fermionic_transformation, num_particles=[1, 1], num_orbitals=6, + self._validate_info(fermionic_transformation, num_particles=(1, 1), num_orbitals=6, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=4, num_paulis=52) diff --git a/test/chemistry/test_initial_state_hartree_fock.py b/test/chemistry/test_initial_state_hartree_fock.py index 4186d3854b..df8e9dccaa 100644 --- a/test/chemistry/test_initial_state_hartree_fock.py +++ b/test/chemistry/test_initial_state_hartree_fock.py @@ -18,7 +18,6 @@ import numpy as np from ddt import ddt, idata, unpack -from qiskit import QuantumCircuit from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.aqua.operators import StateFn from qiskit.chemistry import QiskitChemistryError @@ -126,45 +125,5 @@ def test_hf_value(self, mapping): self.assertAlmostEqual(fermionic_transformation._hf_energy, hf_energy, places=6) -@ddt -class TestHartreeFock(QiskitChemistryTestCase): - """ Initial State HartreeFock tests """ - - def test_qubits_4_jw_h2(self): - """ qubits 4 jw h2 test """ - state = HartreeFock(4, (1, 1), 'jordan_wigner', False) - ref = QuantumCircuit(4) - ref.x([0, 2]) - self.assertEqual(state, ref) - - def test_qubits_4_py_h2(self): - """ qubits 4 py h2 test """ - state = HartreeFock(4, (1, 1), 'parity', False) - ref = QuantumCircuit(4) - ref.x([0, 1]) - self.assertEqual(state, ref) - - def test_qubits_4_bk_h2(self): - """ qubits 4 bk h2 test """ - state = HartreeFock(4, (1, 1), 'bravyi_kitaev', False) - ref = QuantumCircuit(4) - ref.x([0, 1, 2]) - self.assertEqual(state, ref) - - def test_qubits_2_py_h2(self): - """ qubits 2 py h2 test """ - state = HartreeFock(4, 2, 'parity', True) - ref = QuantumCircuit(2) - ref.x(0) - self.assertEqual(state, ref) - - def test_qubits_6_py_lih(self): - """ qubits 6 py lih test """ - state = HartreeFock(10, (1, 1), 'parity', True, [1, 2]) - ref = QuantumCircuit(6) - ref.x([0, 1]) - self.assertEqual(state, ref) - - if __name__ == '__main__': unittest.main() diff --git a/test/chemistry/test_initial_state_vscf.py b/test/chemistry/test_initial_state_vscf.py index 0d579135d0..8e51ddaa58 100644 --- a/test/chemistry/test_initial_state_vscf.py +++ b/test/chemistry/test_initial_state_vscf.py @@ -10,13 +10,12 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -""" Test Initial State HartreeFock """ +""" Test Initial State VSCF """ import unittest import warnings from test.chemistry import QiskitChemistryTestCase import numpy as np -from qiskit import QuantumCircuit from qiskit.chemistry.components.initial_states import VSCF @@ -50,27 +49,5 @@ def test_qubits_5(self): 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) -class TestVSCF(QiskitChemistryTestCase): - """ Initial State vscf tests """ - - def test_qubits_4(self): - """ 2 modes 2 modals - test """ - basis = [2, 2] - vscf = VSCF(basis) - ref = QuantumCircuit(4) - ref.x([0, 2]) - - self.assertEqual(ref, vscf) - - def test_qubits_5(self): - """ 2 modes 2 modals for the first mode and 3 modals for the second - test """ - basis = [2, 3] - vscf = VSCF(basis) - ref = QuantumCircuit(5) - ref.x([0, 2]) - - self.assertEqual(ref, vscf) - - if __name__ == '__main__': unittest.main() diff --git a/test/chemistry/test_qeom_vqe.py b/test/chemistry/test_qeom_vqe.py index d17cfc147a..ae0777fdf8 100644 --- a/test/chemistry/test_qeom_vqe.py +++ b/test/chemistry/test_qeom_vqe.py @@ -29,7 +29,7 @@ from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.core import Hamiltonian, TransformationType, QubitMappingType from qiskit.chemistry.components.variational_forms import UCCSD -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock class TestEomVQE(QiskitAquaTestCase): diff --git a/test/chemistry/test_readme_sample.py b/test/chemistry/test_readme_sample.py index 485aec03e0..6840b0fc49 100644 --- a/test/chemistry/test_readme_sample.py +++ b/test/chemistry/test_readme_sample.py @@ -79,12 +79,15 @@ def print(*args): optimizer = L_BFGS_B() # setup the initial state for the variational form - from qiskit.chemistry.components.initial_states import HartreeFock + from qiskit.chemistry.circuit.library import HartreeFock init_state = HartreeFock(num_spin_orbitals, num_particles) # setup the variational form for VQE from qiskit.circuit.library import TwoLocal - var_form = TwoLocal(num_qubits, ['ry', 'rz'], 'cz', initial_state=init_state) + var_form = TwoLocal(num_qubits, ['ry', 'rz'], 'cz') + + # add the initial state + var_form.compose(init_state, front=True) # setup and run VQE from qiskit.aqua.algorithms import VQE diff --git a/test/chemistry/test_swaprz.py b/test/chemistry/test_swaprz.py index 76febe3a42..199d35fe52 100644 --- a/test/chemistry/test_swaprz.py +++ b/test/chemistry/test_swaprz.py @@ -19,7 +19,7 @@ from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE from qiskit.aqua.components.optimizers import SLSQP -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.core import QubitMappingType from qiskit.chemistry.drivers import HDF5Driver from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver @@ -57,7 +57,8 @@ def test_excitation_preserving(self): qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction) - wavefunction = ExcitationPreserving(qubit_op.num_qubits, initial_state=initial_state) + wavefunction = ExcitationPreserving(qubit_op.num_qubits) + wavefunction.compose(initial_state, front=True, inplace=True) solver = VQE(var_form=wavefunction, optimizer=optimizer, quantum_instance=QuantumInstance(BasicAer.get_backend('statevector_simulator'), diff --git a/test/chemistry/test_symmetries.py b/test/chemistry/test_symmetries.py index 930907aaf0..a4c2513349 100644 --- a/test/chemistry/test_symmetries.py +++ b/test/chemistry/test_symmetries.py @@ -22,7 +22,7 @@ from qiskit.chemistry import QiskitChemistryError from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver from qiskit.chemistry.core import TransformationType, QubitMappingType from qiskit.chemistry.transformations import FermionicTransformation diff --git a/test/chemistry/test_uccsd_advanced.py b/test/chemistry/test_uccsd_advanced.py index e85699c9c9..ad03a0e29a 100644 --- a/test/chemistry/test_uccsd_advanced.py +++ b/test/chemistry/test_uccsd_advanced.py @@ -20,7 +20,7 @@ from qiskit.aqua.algorithms import VQE from qiskit.aqua.components.optimizers import SLSQP from qiskit.chemistry import QiskitChemistryError -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.algorithms.ground_state_solvers import GroundStateEigensolver diff --git a/test/chemistry/test_uccsd_hartree_fock.py b/test/chemistry/test_uccsd_hartree_fock.py index 426658b55c..90fc260955 100644 --- a/test/chemistry/test_uccsd_hartree_fock.py +++ b/test/chemistry/test_uccsd_hartree_fock.py @@ -19,7 +19,8 @@ from qiskit.aqua.algorithms import VQE from qiskit.aqua.components.optimizers import SLSQP, SPSA from qiskit.aqua.operators import AerPauliExpectation, PauliExpectation -from qiskit.chemistry.components.initial_states import HartreeFock + +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.core import QubitMappingType from qiskit.chemistry.drivers import HDF5Driver @@ -48,7 +49,7 @@ def setUp(self): self.optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( fermionic_transformation.molecule_info['num_orbitals'], - tuple(fermionic_transformation.molecule_info['num_particles']), + fermionic_transformation.molecule_info['num_particles'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction) self.var_form = UCCSD( diff --git a/test/chemistry/test_uvcc_vscf.py b/test/chemistry/test_uvcc_vscf.py index 8f75f31e3d..b723a428ef 100644 --- a/test/chemistry/test_uvcc_vscf.py +++ b/test/chemistry/test_uvcc_vscf.py @@ -12,6 +12,7 @@ """ Test of UVCC and VSCF Aqua extensions """ +import warnings from test.chemistry import QiskitChemistryTestCase from qiskit import BasicAer @@ -61,7 +62,9 @@ def test_uvcc_vscf(self): bosonic_op = BosonicOperator(co2_2modes_2modals_2body, basis) qubit_op = bosonic_op.mapping('direct', threshold=1e-5) - init_state = VSCF(basis) + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=DeprecationWarning) + init_state = VSCF(basis) num_qubits = sum(basis) uvcc_varform = UVCC(num_qubits, basis, [0, 1], initial_state=init_state) diff --git a/test/chemistry/test_vqe_uccsd_adapt.py b/test/chemistry/test_vqe_uccsd_adapt.py index af2eee5387..2fa846ab9f 100644 --- a/test/chemistry/test_vqe_uccsd_adapt.py +++ b/test/chemistry/test_vqe_uccsd_adapt.py @@ -22,7 +22,7 @@ from qiskit.aqua.operators.legacy.weighted_pauli_operator import Z2Symmetries from qiskit.chemistry import FermionicOperator from qiskit.chemistry.algorithms import VQEAdapt -from qiskit.chemistry.components.initial_states import HartreeFock +from qiskit.chemistry.circuit.library import HartreeFock from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import QiskitChemistryError