Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modular Driver Result #263

Merged
merged 76 commits into from
Jul 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
76 commits
Select commit Hold shift + click to select a range
363af07
WIP: add initial (dumb) ElectronicDriverResult
mrossinek Jun 29, 2021
8992ea7
Extract IntegralProperty
mrossinek Jun 29, 2021
e45f7fe
WIP: ActiveSpaceTransformer migration
mrossinek Jul 1, 2021
075cb9f
More WIP stuff
mrossinek Jun 30, 2021
5288995
Simplify ElectronicIntegral juggling
mrossinek Jun 30, 2021
7cc1199
Pass list of active orbital indices to reduce_system_size method
mrossinek Jun 30, 2021
57ffae0
Improve property handling
mrossinek Jun 30, 2021
c677972
Improve electronic integral access
mrossinek Jul 2, 2021
5ad6cbb
Fix TotalDipoleMoment as Iterable Property
mrossinek Jul 2, 2021
57e6f48
Extract CompositeProperty
mrossinek Jul 2, 2021
26a3e08
Improve ASTrafo readability
mrossinek Jul 2, 2021
9f41cc3
Run black
mrossinek Jul 2, 2021
24ad01d
Docs/repr updates
mrossinek Jul 2, 2021
6e5a13e
Fix Property tests
mrossinek Jul 2, 2021
6263234
Add compose docs
mrossinek Jul 2, 2021
c2595f5
Integrate ElectronicDriverResult into ElectronicStructureProblem
mrossinek Jul 2, 2021
1791072
Fix linters
mrossinek Jul 2, 2021
5f4ec44
Fix mypy
mrossinek Jul 5, 2021
f4995b1
Extract DriverResult
mrossinek Jul 5, 2021
5976f06
Fix spell
mrossinek Jul 5, 2021
ad4df27
Fix lint
mrossinek Jul 5, 2021
a5c7781
Straight forward extraction of interpret methods
mrossinek Jul 5, 2021
f621ed4
Migrate FreezeCoreTransformer
mrossinek Jul 5, 2021
21467da
Fix tests
mrossinek Jul 5, 2021
587178c
More fixes
mrossinek Jul 5, 2021
17a4dea
Fix for pylint<2.9
mrossinek Jul 5, 2021
333fe53
Protect against None-cases
mrossinek Jul 5, 2021
cac1f89
Fix false positive under Python 3.6
mrossinek Jul 5, 2021
9cd9135
More None-safety
mrossinek Jul 5, 2021
e02e72a
Run black
mrossinek Jul 5, 2021
fc811a9
Fix mypy
mrossinek Jul 5, 2021
3ffedd3
Properly deprecate build_ferm_op_from_ints
mrossinek Jul 6, 2021
d52c647
Deprecate old Transformer interface
mrossinek Jul 6, 2021
7a906d6
Unittest + docs for electronic.integrals
mrossinek Jul 6, 2021
efda3d5
Unittests for CompositeProperty
mrossinek Jul 6, 2021
67b9fe2
More unittests
mrossinek Jul 6, 2021
b9f7066
More docs
mrossinek Jul 6, 2021
10eefcc
Remove unused import
mrossinek Jul 6, 2021
0d0def5
Merge branch 'main' into modular_driver_result
mrossinek Jul 12, 2021
9767aef
Commit review suggestion
mrossinek Jul 12, 2021
cf37d92
Join string representation only once
mrossinek Jul 12, 2021
ccab8a7
Extend __repr__ and flat internal integral storage to vibrational pro…
mrossinek Jul 12, 2021
0fff13d
Add error messages and warnings
mrossinek Jul 12, 2021
d310573
Fix args documentation
mrossinek Jul 12, 2021
35d1a94
Fix linters
mrossinek Jul 12, 2021
b3d82b9
Apply suggestions from code review
mrossinek Jul 15, 2021
b12bf72
Merge branch 'main' into modular_driver_result
mrossinek Jul 15, 2021
a6e7511
More suggestions from code review
mrossinek Jul 15, 2021
7fe9d33
Define __str__ instead of __repr__
mrossinek Jul 15, 2021
fa110d1
Fix lint
mrossinek Jul 15, 2021
c84e52e
Merge branch 'main' into modular_driver_result
manoelmarques Jul 15, 2021
5f6edf7
Add driver metadata
mrossinek Jul 20, 2021
38a879e
Rename CompositeProperty -> GroupedProperty
mrossinek Jul 20, 2021
6898c28
Move Molecule.count_orbitals to FreezeCoreTransformer.count_core_orbi…
mrossinek Jul 20, 2021
4fbd3e8
Document dual purpose of ParticleNumber property
mrossinek Jul 20, 2021
3b6e53c
Clarify distinction of electronic, nuclear and total energy/dipole co…
mrossinek Jul 20, 2021
ddcd5d1
Add additional (purely informational) data to ElectronicEnergy
mrossinek Jul 20, 2021
c242e08
Fix ParticleNumber.interpret method
mrossinek Jul 20, 2021
4aa816a
Merge branch 'main' into modular_driver_result
manoelmarques Jul 20, 2021
37c77f4
Merge branch 'main' into modular_driver_result
manoelmarques Jul 20, 2021
093881f
Merge branch 'main' into modular_driver_result
mrossinek Jul 23, 2021
1cbad1a
Merge branch 'main' into modular_driver_result
mrossinek Jul 26, 2021
f3d34fd
Fix transformer deprecation
mrossinek Jul 26, 2021
a88ae41
Review suggestions
mrossinek Jul 28, 2021
824ec56
Improved electronic/vibrational property subtyping
mrossinek Jul 28, 2021
3ffa152
Extend Transformer interface to GroupedProperty
mrossinek Jul 28, 2021
f593a63
Move reduce_system_size logic directly into Transformer
mrossinek Jul 28, 2021
3896739
Rename matrix_operator() -> integral_operator()
mrossinek Jul 28, 2021
b702920
Rename Electronic/Vibrational*DriverResult -> Electronic/Vibrational*…
mrossinek Jul 28, 2021
5376cea
Fix spelling
mrossinek Jul 28, 2021
865196f
Left over fixes
mrossinek Jul 28, 2021
d4e1c43
Fix astroid constraint
mrossinek Jul 29, 2021
9df1083
Fix docstring
mrossinek Jul 29, 2021
42493f6
Remove (so far) unused ElectronicEnergy.fock attr
mrossinek Jul 29, 2021
083f612
Fix lint
mrossinek Jul 29, 2021
38ed9ad
Merge branch 'main' into modular_driver_result
mrossinek Jul 30, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .pylintdict
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ dataset
dcx
debye
deepcopy
dft
diag
diagonalizes
diagonalizing
Expand All @@ -93,6 +94,7 @@ eigenstate
eigenstateresult
eigenstates
einact
einsum
endian
endif
enum
Expand Down Expand Up @@ -197,6 +199,7 @@ mcrz
mct
mcu
mcx
metadata
microsoft
minao
mixin
Expand Down Expand Up @@ -323,8 +326,10 @@ str
subcircuits
subclasses
submodules
subtype
succ
sudo
superpositions
sx
sxdg
symm
Expand Down Expand Up @@ -375,6 +380,7 @@ watson
wavefunction
whitespace
wigner
xcf
xcfun
xdata
xy
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ problem = ElectronicStructureProblem(driver)
second_q_ops = problem.second_q_ops()
main_op = second_q_ops[0]

num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
particle_number = problem.properties_transformed.get_property("ParticleNumber")

num_spin_orbitals = 2 * problem.molecule_data.num_molecular_orbitals
num_particles = (particle_number.num_alpha, particle_number.num_beta)
num_spin_orbitals = particle_number.num_spin_orbitals

# setup the classical optimizer for VQE
from qiskit.algorithms.optimizers import L_BFGS_B
Expand Down
4 changes: 2 additions & 2 deletions constraints.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
astroid==2.5.6
pylint==2.8.3
astroid==2.6.1
pylint==2.9.0
numpy>=1.20.0 ; python_version>'3.6'

Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
from qiskit.utils import QuantumInstance

from qiskit_nature.circuit.library import HartreeFock, UCC, UCCSD
from qiskit_nature.drivers.second_quantization import QMolecule
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.problems.second_quantization.electronic import (
ElectronicStructureProblem,
)
from qiskit_nature.properties.second_quantization.electronic import (
ParticleNumber,
)
from .minimum_eigensolver_factory import MinimumEigensolverFactory


Expand Down Expand Up @@ -188,13 +190,10 @@ def get_solver( # type: ignore[override]
A VQE suitable to compute the ground state of the molecule transformed
by ``transformation``.
"""
q_molecule_transformed = cast(QMolecule, problem.molecule_data_transformed)
num_molecular_orbitals = q_molecule_transformed.num_molecular_orbitals
num_particles = (
q_molecule_transformed.num_alpha,
q_molecule_transformed.num_beta,
)
num_spin_orbitals = 2 * num_molecular_orbitals
driver_result = problem.properties_transformed
particle_number = cast(ParticleNumber, driver_result.get_property(ParticleNumber))
num_spin_orbitals = particle_number.num_spin_orbitals
num_particles = particle_number.num_alpha, particle_number.num_beta

initial_state = self.initial_state
if initial_state is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@
from qiskit.opflow.gradients import GradientBase
from qiskit.utils import QuantumInstance
from qiskit_nature.circuit.library import UVCC, UVCCSD, VSCF
from qiskit_nature.drivers.second_quantization import WatsonHamiltonian
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.problems.second_quantization.vibrational import (
VibrationalStructureProblem,
)
from qiskit_nature.properties.second_quantization.vibrational import (
VibrationalStructureDriverResult,
)

from .minimum_eigensolver_factory import MinimumEigensolverFactory

Expand Down Expand Up @@ -189,9 +191,9 @@ def get_solver( # type: ignore[override]
by ``transformation``.
"""

watson_hamiltonian_transformed = cast(WatsonHamiltonian, problem.molecule_data_transformed)
num_modals = problem.num_modals
num_modes = watson_hamiltonian_transformed.num_modes
basis = cast(VibrationalStructureDriverResult, problem.properties_transformed).basis
num_modals = basis.num_modals_per_mode
num_modes = len(num_modals)

if isinstance(num_modals, int):
num_modals = [num_modals] * num_modes
Expand Down
2 changes: 2 additions & 0 deletions qiskit_nature/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,5 @@
HBAR_J_S = 1.054571800e-34 # note this is h/2Pi
H_J_S = 6.62607015e-34
KB_J_PER_K = 1.3806488e-23
BOHR = 0.52917721092 # No of Angstroms in Bohr (from 2010 CODATA)
DEBYE = 0.393430307 # No ea0 in Debye. Use to convert our dipole moment numbers to Debye
5 changes: 5 additions & 0 deletions qiskit_nature/drivers/molecule.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,11 @@ def units(self):
"""The geometry coordinate units"""
return UnitsType.ANGSTROM

@property
def atoms(self) -> List[str]:
"""Get the list of atoms"""
return [atom for atom, _ in self._geometry]

@property
def geometry(self) -> List[Tuple[str, List[float]]]:
"""Get geometry accounting for any perturbations"""
Expand Down
31 changes: 30 additions & 1 deletion qiskit_nature/problems/second_quantization/base_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,53 @@

from qiskit.opflow import PauliSumOp, Z2Symmetries

from qiskit_nature import QiskitNatureError
from qiskit_nature.drivers.second_quantization import BaseDriver, QMolecule, WatsonHamiltonian
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.properties.second_quantization import GroupedSecondQuantizedProperty
from qiskit_nature.results import EigenstateResult
from qiskit_nature.transformers import BaseTransformer as LegacyBaseTransformer
from qiskit_nature.transformers.second_quantization import BaseTransformer


class BaseProblem(ABC):
"""Base Problem"""

def __init__(self, driver: BaseDriver, transformers: Optional[List[BaseTransformer]] = None):
def __init__(
self,
driver: BaseDriver,
transformers: Optional[List[Union[LegacyBaseTransformer, BaseTransformer]]] = None,
):
"""

Args:
driver: A driver encoding the molecule information.
transformers: A list of transformations to be applied to the molecule.

Raises:
QiskitNatureError: if new and legacy transformer instances are mixed.
"""

self.driver = driver
self.transformers = transformers or []

self._legacy_transform = False
new_transformers = False
for trafo in self.transformers:
if isinstance(trafo, LegacyBaseTransformer):
self._legacy_transform = True
elif isinstance(trafo, BaseTransformer):
new_transformers = True
if self._legacy_transform and new_transformers:
raise QiskitNatureError(
"A mix of current and deprecated transformers is not supported!"
)

self._molecule_data: Union[QMolecule, WatsonHamiltonian] = None
self._molecule_data_transformed: Union[QMolecule, WatsonHamiltonian] = None

self._properties_transformed: GroupedSecondQuantizedProperty = None

@property
def molecule_data(self) -> Union[QMolecule, WatsonHamiltonian]:
"""Returns the raw molecule data object."""
Expand All @@ -52,6 +76,11 @@ def molecule_data_transformed(self) -> Union[QMolecule, WatsonHamiltonian]:
"""Returns the raw transformed molecule data object."""
return self._molecule_data_transformed

@property
def properties_transformed(self) -> GroupedSecondQuantizedProperty:
"""Returns the transformed GroupedSecondQuantizedProperty object."""
return self._properties_transformed

@property
def num_particles(self) -> Optional[Tuple[int, int]]:
"""Returns the number of particles, if available."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# 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.

""" Fermionic operator builder. """

from typing import List

import numpy as np

from qiskit_nature.deprecation import DeprecatedType, deprecate_function
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit_nature.properties.second_quantization.electronic.bases import ElectronicBasis
from qiskit_nature.properties.second_quantization.electronic.integrals import (
ElectronicIntegrals,
IntegralProperty,
OneBodyElectronicIntegrals,
TwoBodyElectronicIntegrals,
)


@deprecate_function(
"0.2.0",
DeprecatedType.CLASS,
"IntegralProperty",
"from qiskit_nature.properties.second_quantization.electronic.integrals in combination with the"
" more versatile ElectronicIntegrals containers",
)
mrossinek marked this conversation as resolved.
Show resolved Hide resolved
def build_ferm_op_from_ints(
one_body_integrals: np.ndarray, two_body_integrals: np.ndarray = None
) -> FermionicOp:
"""**DEPRECATED!**
Builds a fermionic operator based on 1- and/or 2-body integrals. Integral values are used for
the coefficients of the second-quantized Hamiltonian that is built. If integrals are stored
in the '*chemist*' notation
h2(i,j,k,l) --> adag_i adag_k a_l a_j
they are required to be in block spin format and also have indices reordered as follows
'ijkl->ljik'.
There is another popular notation, the '*physicist*' notation
h2(i,j,k,l) --> adag_i adag_j a_k a_l
If you are using the '*physicist*' notation, you need to convert it to
the '*chemist*' notation. E.g. h2=numpy.einsum('ikmj->ijkm', h2)
The :class:`~qiskit_nature.drivers.second_quantization.QMolecule` class has
:attr:`~qiskit_nature.drivers.second_quantization.QMolecule.one_body_integrals` and
:attr:`~qiskit_nature.drivers.second_quantization.QMolecule.two_body_integrals` properties that
can be directly supplied to the `h1` and `h2` parameters here respectively.

Args:
one_body_integrals (numpy.ndarray): One-body integrals stored in the chemist notation.
two_body_integrals (numpy.ndarray): Two-body integrals stored in the chemist notation.

Returns:
FermionicOp: FermionicOp built from 1- and/or 2-body integrals.
"""
integrals: List[ElectronicIntegrals] = []
integrals.append(OneBodyElectronicIntegrals(ElectronicBasis.SO, one_body_integrals))
if two_body_integrals is not None:
integrals.append(TwoBodyElectronicIntegrals(ElectronicBasis.SO, two_body_integrals))

prop = IntegralProperty("", integrals)

fermionic_op = prop.second_q_ops()[0]

return fermionic_op
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

"""Utility methods to build fermionic hopping operators."""

# TODO: re-implement these as properties?

from typing import cast, Callable, Dict, List, Tuple, Union

from qiskit.opflow import PauliSumOp
Expand Down
Loading