Line data Source code
1 : # SPDX-FileCopyrightText: 2024 PairInteraction Developers
2 : # SPDX-License-Identifier: LGPL-3.0-or-later
3 1 : from __future__ import annotations
4 :
5 1 : from collections.abc import Iterable, Sequence
6 1 : from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, Union
7 :
8 1 : import numpy as np
9 1 : import pint
10 1 : from pint import UnitRegistry
11 1 : from pint.facets.plain import PlainQuantity
12 1 : from scipy.sparse import csr_matrix
13 :
14 : if TYPE_CHECKING:
15 : from typing import TypeAlias
16 :
17 : import numpy.typing as npt
18 : from pint.facets.plain import PlainUnit
19 : from typing_extensions import Self
20 :
21 : NDArray: TypeAlias = "npt.NDArray[Any]"
22 : ArrayLike: TypeAlias = "npt.NDArray[Any] | Sequence[float]"
23 : PintFloat: TypeAlias = "PlainQuantity[float]"
24 : PintArray: TypeAlias = "PlainQuantity[NDArray]"
25 : PintArrayLike: TypeAlias = "PintArray | Sequence[float | PintFloat]"
26 : # type ignore here and also below for PlainQuantity[ValueType] because pint has no type support for scipy.csr_matrix
27 : PintSparse: TypeAlias = "PlainQuantity[csr_matrix]"
28 : # and also for complex
29 : PintComplex: TypeAlias = "PlainQuantity[complex]"
30 :
31 1 : ureg = UnitRegistry(system="atomic")
32 :
33 1 : Dimension = Literal[
34 : "electric_field",
35 : "magnetic_field",
36 : "distance",
37 : "inverse_distance",
38 : "energy",
39 : "charge",
40 : "velocity",
41 : "temperature",
42 : "time",
43 : "transition_rate",
44 : "electric_monopole",
45 : "electric_dipole",
46 : "electric_quadrupole",
47 : "electric_quadrupole_zero",
48 : "electric_octupole",
49 : "magnetic_dipole",
50 : "c3",
51 : "c6",
52 : "green_tensor_00",
53 : "scaled_green_tensor_00",
54 : "identity",
55 : "arbitrary",
56 : "zero",
57 : ]
58 1 : DimensionLike = Dimension | Iterable[Dimension]
59 :
60 : # some abbreviations: au_time: atomic_unit_of_time; au_current: atomic_unit_of_current; m_e: electron_mass
61 1 : _CommonUnits: dict[Dimension, str] = {
62 : "electric_field": "V/cm", # 1 V/cm = 1.9446903811524456e-10 bohr * m_e / au_current / au_time ** 3
63 : "magnetic_field": "T", # 1 T = 4.254382157342044e-06 m_e / au_current / au_time ** 2
64 : "distance": "micrometer", # 1 mum = 18897.26124622279 bohr
65 : "inverse_distance": "1 / micrometer",
66 : "energy": "hartree", # 1 hartree = 1 bohr ** 2 * m_e / au_time ** 2
67 : "charge": "e", # 1 e = 1 au_current * au_time
68 : "velocity": "speed_of_light", # 1 c = 137.03599908356244 bohr / au_time
69 : "temperature": "K", # 1 K = 3.1668115634555572e-06 atomic_unit_of_temperature
70 : "time": "s", # 1 s = 4.134137333518244e+16 au_time
71 : "transition_rate": "1/s", # 1 / s = 2.4188843265856806e-17 * 1 / au_time
72 : "electric_monopole": "e", # 1 e = 1 au_current * au_time # the monopole is -e for a positive Rydberg ion
73 : "electric_dipole": "e * a0", # 1 e * a0 = 1 au_current * au_time * bohr
74 : "electric_quadrupole": "e * a0^2", # 1 e * a0^2 = 1 au_current * au_time * bohr ** 2
75 : "electric_quadrupole_zero": "e * a0^2", # 1 e * a0^2 = 1 au_current * au_time * bohr ** 2
76 : "electric_octupole": "e * a0^3", # 1 e * a0^3 = 1 au_current * au_time * bohr ** 3
77 : "magnetic_dipole": "hbar e / m_e", # 1 hbar e / m_e = 1 au_current * bohr ** 2
78 : "c3": "hartree * bohr^3", # 1 hartree * bohr^3 = 1 bohr ** 3 * m_e / au_time ** 2
79 : "c6": "hartree * bohr^6", # 1 hartree * bohr^6 = 1 bohr ** 6 * m_e / au_time ** 2
80 : "green_tensor_00": "meter", # unit for green tensor with kappa1 = kappa2 = 0
81 : "scaled_green_tensor_00": "hartree / e^2", # unit for scaled green tensor with kappa1 = kappa2 = 1
82 : "identity": "", # 1 dimensionless
83 : "arbitrary": "", # 1 dimensionless
84 : "zero": "", # 1 dimensionless
85 : }
86 1 : AtomicUnits: dict[Dimension, PlainUnit] = {
87 : k: ureg.Quantity(1, unit).to_base_units().units for k, unit in _CommonUnits.items()
88 : }
89 :
90 1 : Context = Literal["spectroscopy", "Gaussian"]
91 1 : BaseContexts: dict[Dimension, Context] = {
92 : "magnetic_field": "Gaussian",
93 : "energy": "spectroscopy",
94 : "c3": "spectroscopy",
95 : "c6": "spectroscopy",
96 : }
97 :
98 1 : ValueType = TypeVar("ValueType", bound=Union[float, "NDArray", "csr_matrix"])
99 1 : ValueTypeLike = TypeVar("ValueTypeLike", bound=Union[float, "ArrayLike", "csr_matrix"])
100 :
101 :
102 1 : class QuantityAbstract(Generic[ValueTypeLike, ValueType]):
103 1 : def __init__(self, pint_qty: PlainQuantity[ValueType], dimension: DimensionLike) -> None: # type: ignore [type-var]
104 1 : if not isinstance(pint_qty, ureg.Quantity):
105 0 : raise TypeError(f"pint_qty must be a ureg.Quantity, not {type(pint_qty)}")
106 1 : self._quantity = pint_qty
107 1 : self.dimension: DimensionLike = dimension
108 1 : self.check_value_type()
109 :
110 1 : def check_value_type(self) -> None:
111 0 : raise NotImplementedError("This method must be implemented in the derived classes.")
112 :
113 1 : @classmethod
114 1 : def get_atomic_unit(cls, dimension: DimensionLike) -> str:
115 1 : if isinstance(dimension, str):
116 1 : return str(AtomicUnits[dimension])
117 : # dimension isinstance Iterable[Dimension]
118 1 : return " * ".join(str(AtomicUnits[d]) for d in dimension)
119 :
120 1 : @classmethod
121 1 : def get_contexts(cls, dimension: DimensionLike) -> list[Context]:
122 1 : if isinstance(dimension, str):
123 1 : return [BaseContexts[dimension]] if dimension in BaseContexts else []
124 1 : contexts: set[Context] = {BaseContexts[d] for d in dimension if d in BaseContexts}
125 1 : return list(contexts)
126 :
127 1 : @classmethod
128 1 : def from_pint(
129 : cls: type[Self],
130 : value: PlainQuantity[ValueType], # type: ignore [type-var]
131 : dimension: DimensionLike,
132 : ) -> Self:
133 : """Initialize a Quantity from a ureg.Quantity."""
134 1 : if isinstance(value, ureg.Quantity):
135 1 : return cls(value, dimension)
136 0 : if isinstance(value, PlainQuantity):
137 0 : raise TypeError(
138 : "Only use pint quantities genereated by pairinteraction.ureg and not by a different pint.UnitRegistry."
139 : )
140 0 : raise ValueError("method from_pint: value must be a pint.Quantity")
141 :
142 1 : @classmethod
143 1 : def from_unit(
144 : cls: type[Self],
145 : value: ValueTypeLike,
146 : unit: str,
147 : dimension: DimensionLike,
148 : ) -> Self:
149 : """Initialize a Quantity from a value and a unit given as string."""
150 1 : if isinstance(value, PlainQuantity):
151 0 : raise TypeError("method from_unit: value must be a scalar or an array, not a pint.Quantity")
152 1 : return cls(ureg.Quantity(value, unit), dimension) # type: ignore [arg-type] # pint typing does not support generic magnitudes
153 :
154 1 : @classmethod
155 1 : def from_au(
156 : cls: type[Self],
157 : value: ValueTypeLike,
158 : dimension: DimensionLike,
159 : ) -> Self:
160 : """Initialize a Quantity from a value in atomic units (a.u.) and a (list of) dimension(s)."""
161 1 : unit = cls.get_atomic_unit(dimension)
162 1 : return cls(ureg.Quantity(value, unit), dimension) # type: ignore [arg-type] # pint typing does not support generic magnitudes
163 :
164 1 : @classmethod
165 1 : def from_pint_or_unit(
166 : cls: type[Self],
167 : value: PlainQuantity[ValueType] | ValueTypeLike, # type: ignore [type-var]
168 : unit: str | None,
169 : dimension: DimensionLike,
170 : ) -> Self:
171 1 : if unit is None:
172 1 : if isinstance(value, PlainQuantity):
173 1 : return cls.from_pint(value, dimension)
174 1 : if np.all(value == 0):
175 1 : return cls.from_au(value, dimension)
176 0 : raise ValueError("unit must be given if value is not a pint.Quantity")
177 1 : assert not isinstance(value, PlainQuantity)
178 1 : return cls.from_unit(value, unit, dimension)
179 :
180 1 : def to_pint(self) -> PlainQuantity[ValueType]: # type: ignore [type-var]
181 : """Return the pint.Quantity object."""
182 1 : contexts = self.get_contexts(self.dimension)
183 1 : atomic_unit = self.get_atomic_unit(self.dimension)
184 1 : return self._quantity.to(atomic_unit, *contexts)
185 :
186 1 : def to_unit(
187 : self,
188 : unit: str,
189 : ) -> ValueType:
190 : """Return the value of the quantity in the given unit."""
191 1 : contexts = self.get_contexts(self.dimension)
192 1 : try:
193 1 : return self._quantity.to(unit, *contexts).magnitude # type: ignore [no-any-return] # also a problem with pint with sparse matrix
194 1 : except pint.errors.DimensionalityError:
195 : # pint uses e.g. the context "spectroscopy" to convert "hartree" -> "GHz"
196 : # however, something like "hartree * bohr^3" -> "GHz * bohr^3" does not work
197 : # the following is a workaround for this kind of conversions
198 1 : if "spectroscopy" in contexts:
199 1 : q: PlainQuantity[ValueType] = ( # type: ignore [type-var]
200 : self._quantity * ureg.Quantity(1, "GHz") / ureg.Quantity(1, "GHz").to("hartree", "spectroscopy")
201 : )
202 1 : return q.to(unit, *contexts).magnitude
203 0 : raise
204 :
205 1 : def to_au(self) -> ValueType:
206 : """Return the value of the quantity in atomic units (a.u.)."""
207 1 : value = self.to_pint().to_base_units()
208 1 : return value.magnitude
209 :
210 1 : def to_pint_or_unit(self, unit: str | None) -> ValueType | PlainQuantity[ValueType]: # type: ignore [type-var]
211 1 : if unit is None:
212 1 : return self.to_pint()
213 1 : return self.to_unit(unit)
214 :
215 1 : @classmethod
216 1 : def convert_user_to_au(
217 : cls,
218 : value: PlainQuantity[ValueType] | ValueTypeLike, # type: ignore [type-var]
219 : unit: str | None,
220 : dimension: DimensionLike,
221 : ) -> ValueType:
222 1 : return cls.from_pint_or_unit(value, unit, dimension).to_au()
223 :
224 1 : @classmethod
225 1 : def convert_user_to_pint(
226 : cls,
227 : value: PlainQuantity[ValueType] | ValueTypeLike, # type: ignore [type-var]
228 : unit: str | None,
229 : dimension: DimensionLike,
230 : ) -> PlainQuantity[ValueType]: # type: ignore [type-var]
231 1 : return cls.from_pint_or_unit(value, unit, dimension).to_pint()
232 :
233 1 : @classmethod
234 1 : def convert_au_to_user(
235 : cls,
236 : values_au: ValueTypeLike,
237 : dimension: DimensionLike,
238 : unit: str | None,
239 : ) -> ValueType | PlainQuantity[ValueType]: # type: ignore [type-var]
240 1 : return cls.from_au(values_au, dimension).to_pint_or_unit(unit)
241 :
242 1 : @classmethod
243 1 : def convert_pint_to_user(
244 : cls,
245 : value_pint: PlainQuantity[ValueType], # type: ignore [type-var]
246 : dimension: DimensionLike,
247 : unit: str | None,
248 : ) -> ValueType | PlainQuantity[ValueType]: # type: ignore [type-var]
249 1 : return cls.from_pint(value_pint, dimension).to_pint_or_unit(unit)
250 :
251 :
252 1 : class QuantityScalar(QuantityAbstract[float, float]):
253 1 : def check_value_type(self) -> None:
254 1 : magnitude = self._quantity.magnitude
255 1 : if not np.isscalar(magnitude):
256 0 : raise TypeError(f"value must be a scalar, not {type(magnitude)}")
257 :
258 :
259 1 : class QuantityArray(QuantityAbstract["ArrayLike", "NDArray"]):
260 1 : def check_value_type(self) -> None:
261 1 : magnitude = self._quantity.magnitude
262 1 : if not isinstance(magnitude, Sequence) and not isinstance(magnitude, np.ndarray):
263 0 : raise TypeError(f"value must be an np.ndarray (or a Sequence), not {type(magnitude)}")
264 :
265 :
266 1 : class QuantitySparse(QuantityAbstract["csr_matrix", "csr_matrix"]):
267 1 : def check_value_type(self) -> None:
268 1 : magnitude = self._quantity.magnitude
269 1 : if not isinstance(magnitude, csr_matrix):
270 0 : raise TypeError(f"value must be a scipy.sparse.csr_matrix, not {type(magnitude)}")
|