VibrationalIntegrals#
- class VibrationalIntegrals(data, *, validate=True)[source]#
Bases:
PolynomialTensor
A container class for vibrational operator coefficients (a.k.a. vibrational integrals).
This class simply derives the
qiskit_nature.second_q.operators.PolynomialTensor
implementation and provides an efficient factory method from a raw set of integrals. Being a subclass of thePolynomialTensor
, the same arithmetic operations are supported as by that class.- Parameters:
data (Mapping[str, np.ndarray | SparseArray | complex | Tensor]) – mapping of string-based operator keys to coefficient tensor values. If the values are not already of type
Tensor
, they will automatically be wrapped into one.validate (bool) – when set to False the
data
will not be validated. Disable this setting with care!
- Raises:
ValueError – when length of operator key does not match dimensions of value matrix.
ValueError – when value matrix does not have consistent dimensions.
ValueError – when some or all value matrices in
data
have different dimensions.
Attributes
- atol = 1e-08#
- register_length#
- rtol = 1e-05#
Methods
- classmethod apply(function, *operands, multi=False, validate=True)#
Applies the provided function to the common set of keys of the provided tensors.
The usage of this method is best explained by some examples:
import numpy as np from qiskit_nature.second_q.opertors import PolynomialTensor rand_a = np.random.random((2, 2)) rand_b = np.random.random((2, 2)) a = PolynomialTensor({"+-": rand_a}) b = PolynomialTensor({"+": np.random.random(2), "+-": rand_b}) # transpose a_transpose = PolynomialTensor.apply(np.transpose, a) print(a_transpose == PolynomialTensor({"+-": rand_a.transpose()})) # True # conjugate a_complex = 1j * a a_conjugate = PolynomialTensor.apply(np.conjugate, a_complex) print(a_conjugate == PolynomialTensor({"+-": -1j * rand_a})) # True # kronecker product ab_kron = PolynomialTensor.apply(np.kron, a, b) print(ab_kron == PolynomialTensor({"+-": np.kron(rand_a, rand_b)})) # True # Note: that ab_kron does NOT contain the "+" and "+-+" keys although b contained the # "+" key. That is because the function only gets applied to the keys which are common # to all tensors passed to it. # computing eigenvectors hermi_a = np.array([[1, -2j], [2j, 5]]) a = PolynomialTensor({"+-": hermi_a}) _, eigenvectors = PolynomialTensor.apply(np.linalg.eigh, a, multi=True, validate=False) print(eigenvectors == PolynomialTensor({"+-": np.eigh(hermi_a)[1]})) # True
Note
The provided function will only be applied to the internal arrays of the common keys of all provided
PolynomialTensor
instances. That means, that no cross-products will be generated.- Parameters:
function (Callable[..., np.ndarray | SparseArray | complex]) – the function to apply to the internal arrays of the provided operands. This function must take numpy (or sparse) arrays as its positional arguments. The number of arguments must match the number of provided operands.
operands (PolynomialTensor) – a sequence of
PolynomialTensor
instances on which to operate.multi (bool) – when set to True this indicates that the provided numpy function will return multiple new numpy arrays which will each be wrapped into a
PolynomialTensor
instance separately.validate (bool) – when set to False the
data
will not be validated. Disable this setting with care!
- Returns:
A new
PolynomialTensor
instance with the resulting arrays.- Return type:
- compose(other, qargs=None, front=False)#
Returns the matrix multiplication with another
PolynomialTensor
.- Parameters:
other (PolynomialTensor) – the other PolynomialTensor.
qargs (None) – UNUSED.
front (bool) – If
True
, composition uses right matrix multiplication, otherwise left multiplication is used (the default).
- Raises:
NotImplementedError – when the two tensors do not have the same
register_length
.- Returns:
The tensor resulting from the composition.
- Return type:
Note
Composition (
&
) by default is defined as left matrix multiplication for operators, while@
(equivalent todot()
) is defined as right matrix multiplication. This means thatA & B == A.compose(B)
is equivalent toB @ A == B.dot(A)
whenA
andB
are of the same type.Setting the
front=True
keyword argument changes this to right matrix multiplication which is equivalent to thedot()
methodA.dot(B) == A.compose(B, front=True)
.
- dot(other, qargs=None)#
Return the right multiplied operator self * other.
- Parameters:
other (Operator) – an operator object.
qargs (list or None) – Optional, a list of subsystem positions to apply other on. If None apply on all subsystems (default: None).
- Returns:
The right matrix multiplied Operator.
- Return type:
Operator
Note
The dot product can be obtained using the
@
binary operator. Hencea.dot(b)
is equivalent toa @ b
.
- classmethod einsum(einsum_map, *operands, validate=True)#
Applies the various Einsum convention operations to the provided tensors.
This method wraps the
numpy.einsum()
function, allowing very complex operations to be applied efficiently to the matrices stored inside the providedPolynomialTensor
operands.As an example, let us compute the exact exchange term of an
qiskit_nature.second_q.hamiltonians.ElectronicEnergy
hamiltonian:# a PolynomialTensor containing the two-body terms of an ElectronicEnergy hamiltonian two_body = PolynomialTensor({"++--": ...}) # an electronic density: density = PolynomialTensor({"+-": ...}) # computes the ElectronicEnergy.exchange operator exchange = PolynomialTensor.einsum( {"pqrs,qs->pr": ("++--", "+-", "+-")}, two_body, density, ) # result will be contained in exchange["+-"]
Another example is the mapping from the AO to MO basis, as implemented by the
qiskit_nature.second_q.transformers.BasisTransformer
.# the one- and two-body integrals of a hamiltonian hamiltonian = PolynomialTensor({"+-": ..., "++--": ...}) # the AO-to-MO transformation coefficients mo_coeff = PolynomialTensor({"+-": ...}) einsum_map = { "jk,ji,kl->il": ("+-", "+-", "+-", "+-"), "prsq,pi,qj,rk,sl->iklj": ("++--", "+-", "+-", "+-", "+-", "++--"), } transformed = PolynomialTensor.einsum( einsum_map, hamiltonian, mo_coeff, mo_coeff, mo_coeff, mo_coeff ) # results will be contained in transformed["+-"] and transformed["++--"], respectively
Note
sparse.SparseArray
supportsopt_einsum.contract` if ``opt_einsum
is installed. It does not supportnumpy.einsum
. In this case, the resultantPolynomialTensor
will contain all dense numpy arrays. If a user would like to work with a sparse array instead, they should installopt_einsum
or they should convert it explicitly using theto_sparse()
method.- Parameters:
einsum_map (dict[str, tuple[str, ...]]) – a dictionary, mapping from
numpy.einsum()
subscripts to a tuple of strings. These strings correspond to the keys of matrices to be extracted from the providedPolynomialTensor
operands. The last string in this tuple indicates the key under which to store the result in the returnedPolynomialTensor
.operands (PolynomialTensor) – a sequence of
PolynomialTensor
instances on which to operate.validate (bool) – when set to False the
data
will not be validated. Disable this setting with care!
- Returns:
A new
PolynomialTensor
.- Return type:
- classmethod empty()#
Constructs an empty tensor.
- Returns:
The empty tensor.
- Return type:
- equiv(other)#
Check equivalence of
PolynomialTensor
instances.Note
This check only asserts the internal matrix elements for equivalence but ignores the type of the matrices. As such, it will indicate equivalence of two
PolynomialTensor
instances even if one contains sparse and the other dense numpy arrays, as long as their elements match.
- expand(other)#
Returns the reverse-order tensor product with another
PolynomialTensor
.- Parameters:
other (PolynomialTensor) – the other PolynomialTensor.
- Raises:
NotImplementedError – when the two tensors do not have the same
register_length
.- Returns:
The tensor resulting from the tensor product, \(other \otimes self\).
- Return type:
Note
Expand is the opposite operator ordering to
tensor()
. For two tensors of the same typea.expand(b) = b.tensor(a)
.
- classmethod from_raw_integrals(integrals)[source]#
Constructs a
VibrationalIntegrals
instance from the provided coefficients.The provided coefficients must already be mapped to a second-quantization basis. See the documentation of
qiskit_nature.second_q.problems.VibrationalBasis
for more details.- Parameters:
integrals (Mapping[tuple[int, ...], complex]) – a mapping of matrix index tuples to coefficients. This is effectively a sparse representation of the coefficients. Each key in the mapping should be a tuple of integers of the form
(mode, modal_1, modal_2, ...)
. That means that each key is expected to have its length be a multiple of three. See also the documentation ofqiskit_nature.second_q.problems.VibrationalBasis.map()
for more details.- Returns:
The constructed instance.
- Return type:
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- items() a set-like object providing a view on D's items #
- keys() a set-like object providing a view on D's keys #
- power(n)#
Return the compose of a operator with itself n times.
- Parameters:
n (int) – the number of times to compose with self (n>0).
- Returns:
the n-times composed operator.
- Return type:
Clifford
- Raises:
QiskitError – if the input and output dimensions of the operator are not equal, or the power is not a positive integer.
- split(function, indices_or_sections, *, validate=True)#
Splits the acted on tensor instance using the given numpy splitting function.
The usage of this method is best explained by some examples:
import numpy as np from qiskit_nature.second_q.opertors import PolynomialTensor rand_ab = np.random.random((4, 4)) ab = PolynomialTensor({"+-": rand_ab}) # np.hsplit a, b = ab.split(np.hsplit, [2], validate=False) print(a == PolynomialTensor({"+-": np.hsplit(ab, [2])[0], validate=False)})) # True print(b == PolynomialTensor({"+-": np.hsplit(ab, [2])[1], validate=False)})) # True # np.vsplit a, b = ab.split(np.vsplit, [2], validate=False) print(a == PolynomialTensor({"+-": np.vsplit(ab, [2])[0], validate=False)})) # True print(b == PolynomialTensor({"+-": np.vsplit(ab, [2])[1], validate=False)})) # True
Note
When splitting arrays this will likely lead to array shapes which would fail the shape validation check (as you can see from the examples above where we explicitly disable them). This is considered an advanced use case which is why the user is left to disable this check themselves, to ensure they know what they are doing.
- Parameters:
function (Callable[..., np.ndarray | SparseArray | Number]) – the splitting function to use. This function must take a single numpy (or sparse) array as its first input followed by a sequence of indices to split on. You should use
functools.partial
if you need to provide keyword arguments (e.g.partial(np.split, axis=-1)
). Common methods to use here arenumpy.hsplit()
andnumpy.vsplit()
.indices_or_sections (int | Sequence[int]) – a single index or sequence of indices to split on.
validate (bool) – when set to False the
data
will not be validated. Disable this setting with care!
- Returns:
New
PolynomialTensor
instances containing the split arrays.- Return type:
- classmethod stack(function, operands, *, validate=True)#
Stacks the provided sequence of tensors using the given numpy stacking function.
The usage of this method is best explained by some examples:
import numpy as np from qiskit_nature.second_q.opertors import PolynomialTensor rand_a = np.random.random((2, 2)) rand_b = np.random.random((2, 2)) a = PolynomialTensor({"+-": rand_a}) b = PolynomialTensor({"+": np.random.random(2), "+-": rand_b}) # np.hstack ab_hstack = PolynomialTensor.stack(np.hstack, [a, b], validate=False) print(ab_hstack == PolynomialTensor({"+-": np.hstack([a, b], validate=False)})) # True # np.vstack ab_vstack = PolynomialTensor.stack(np.vstack, [a, b], validate=False) print(ab_vstack == PolynomialTensor({"+-": np.vstack([a, b], validate=False)})) # True
Note
The provided function will only be applied to the internal arrays of the common keys of all provided
PolynomialTensor
instances. That means, that no cross-products will be generated.Note
When stacking arrays this will likely lead to array shapes which would fail the shape validation check (as you can see from the examples above where we explicitly disable them). This is considered an advanced use case which is why the user is left to disable this check themselves, to ensure they know what they are doing.
- Parameters:
function (Callable[..., np.ndarray | SparseArray | Number]) – the stacking function to apply to the internal arrays of the provided operands. This function must take a sequence of numpy (or sparse) arrays as its first argument. You should use
functools.partial
if you need to provide keyword arguments (e.g.partial(np.stack, axis=-1)
). Common methods to use here arenumpy.hstack()
andnumpy.vstack()
.operands (Sequence[PolynomialTensor]) – a sequence of
PolynomialTensor
instances on which to operate.validate (bool) – when set to False the
data
will not be validated. Disable this setting with care!
- Returns:
A new
PolynomialTensor
instance with the resulting arrays.- Return type:
- tensor(other)#
Returns the tensor product with another
PolynomialTensor
.- Parameters:
other (PolynomialTensor) – the other PolynomialTensor.
- Raises:
NotImplementedError – when the two tensors do not have the same
register_length
.- Returns:
The tensor resulting from the tensor product, \(self \otimes other\).
- Return type:
Note
The tensor product can be obtained using the
^
binary operator. Hencea.tensor(b)
is equivalent toa ^ b
.Note
Tensor uses reversed operator ordering to
expand()
. For two tensors of the same typea.tensor(b) = b.expand(a)
.
- to_dense()#
Returns a new instance where all matrices are now dense tensors.
If the instance on which this method was called already fulfilled this requirement, it is returned unchanged.
- Return type:
- to_sparse(*, sparse_type=<class 'sparse._coo.core.COO'>)#
Returns a new instance where all matrices are now sparse tensors.
If the instance on which this method was called already fulfilled this requirement, it is returned unchanged.
- Parameters:
sparse_type (Type[COO] | Type[DOK] | Type[GCXS]) – the type to use for the conversion to sparse matrices. Note, that this will only be applied to matrices which were previously dense tensors. Sparse arrays of another type will not be explicitly converted.
- Returns:
A new
PolynomialTensor
with all its matrices converted to the requested sparse array type.- Return type:
- values() an object providing a view on D's values #