Skip to content

qten.geometries.spatials

Module reference for qten.geometries.spatials.

spatials

Geometry primitives for real-space and reciprocal-space coordinates.

This module defines the coordinate objects that the rest of QTen uses to talk about positions on a finite lattice and momenta on the corresponding sampled reciprocal grid.

The central convention is:

  • An AffineSpace stores a basis matrix whose columns are the primitive vectors of some coordinate frame.
  • An Offset stores coordinates rep relative to basis; in code this is basis @ rep, mathematically \(A r\).
  • A Lattice is an affine space together with a periodic identification of cells and an optional multi-site unit cell.
  • A ReciprocalLattice is the dual momentum-space lattice with basis \(2\pi(A^{-1})^{\mathsf{T}}\), so plane-wave phases can be evaluated directly as \(\exp(-\mathrm{i}\, k\cdot r)\) in Cartesian coordinates. In code, this basis is built from the direct lattice as 2 * sy.pi * basis.inv().T.

With direct basis matrix \(A\), fractional coordinates \(r\), and reciprocal basis \(G = 2\pi(A^{-1})^{\mathsf{T}}\), the core coordinate convention is \(x = A r\), with plane-wave phases written as \(\exp(-\mathrm{i}\, k \cdot x)\) for Cartesian positions \(x\) and Cartesian reciprocal vectors \(k\). The corresponding code expression for the coordinate map is basis @ rep.

Throughout the module, "fractional coordinates" means coefficients in the primitive basis, not Cartesian coordinates. Integer parts label unit-cell translations, while fractional parts label positions inside a unit cell or inside the first reciprocal cell.

OffsetType module-attribute

OffsetType = TypeVar('OffsetType', bound='Offset[Any]')

Type variable for spatial point-like coordinates such as Offset and Momentum.

Spatial dataclass

Spatial()

Bases: Operable, Plottable, ABC

Abstract base class for geometry objects with a well-defined spatial dimension.

Physically, subclasses represent either coordinate systems (AffineSpace, Lattice, ReciprocalLattice) or vectors/points expressed in those systems (Offset, Momentum).

dim abstractmethod property

dim: int

Return the dimension of the spatial object.

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

AffineSpace dataclass

AffineSpace(basis: ImmutableDenseMatrix)

Bases: Spatial

Affine coordinate system described by a basis matrix.

Mathematically, if the basis matrix is \(A = [a_1,\ldots,a_d]\), then a column of coordinates \(r\) represents the Cartesian vector

\(x = A r = \sum_j r_j a_j\).

This class does not by itself impose periodicity or discreteness. It is the ambient continuous coordinate frame in which lattice vectors and unit-cell positions are expressed.

String representations
  • str(space) returns AffineSpace(basis=...), where basis is shown as a nested Python list of stringified SymPy entries.
  • repr(space) is identical to str(space).

The output is intended to expose the basis matrix directly and does not add any extra constructor metadata beyond that basis.

Attributes:

Name Type Description
basis ImmutableDenseMatrix

Basis matrix whose columns span the affine coordinate system.

basis instance-attribute

basis: ImmutableDenseMatrix

Basis matrix whose columns span the affine coordinate system. Coordinate columns \(r\) in this space represent Cartesian vectors through basis @ r in code, mathematically \(A r\).

dim property

dim: int

Return the geometric dimension of the affine space.

This is the number of primitive basis vectors, equivalently the number of rows of basis and the number of coordinates needed to specify a point/vector in this frame.

origin

origin() -> Offset[AffineSpace]

Return the zero vector of this affine space.

Physically this is the chosen coordinate origin. In fractional coordinates it is the column of all zeros, and in Cartesian coordinates it maps to the zero displacement.

Source code in src/qten/geometries/spatials.py
139
140
141
142
143
144
145
146
147
def origin(self) -> "Offset":
    """
    Return the zero vector of this affine space.

    Physically this is the chosen coordinate origin. In fractional
    coordinates it is the column of all zeros, and in Cartesian coordinates
    it maps to the zero displacement.
    """
    return Offset(rep=ImmutableDenseMatrix([0] * self.dim), space=self)

__str__

__str__()

Return AffineSpace(basis=...) with the basis shown entry-by-entry.

Source code in src/qten/geometries/spatials.py
149
150
151
152
def __str__(self):
    """Return `AffineSpace(basis=...)` with the basis shown entry-by-entry."""
    data = [[str(sympify(x)) for x in row] for row in self.basis.tolist()]
    return f"AffineSpace(basis={data})"

__repr__

__repr__()

Return the same display string as __str__().

Source code in src/qten/geometries/spatials.py
154
155
156
def __repr__(self):
    """Return the same display string as [`__str__()`][qten.geometries.spatials.AffineSpace.__str__]."""
    return str(self)

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

AbstractLattice dataclass

AbstractLattice(basis: ImmutableDenseMatrix)

Bases: Generic[_O], AffineSpace, HasDual

Common interface for direct and reciprocal lattices.

Both share the same structure: an affine basis plus a finite set of canonical representatives obtained from periodic identifications. The type parameter distinguishes whether those representatives are Offset objects in real space or Momentum objects in reciprocal space.

affine property

affine: AffineSpace

Return the underlying continuous affine space.

This forgets the discrete sampled set and keeps only the basis. It is useful when you want to talk about arbitrary vectors in the same frame, not only allowed lattice sites or sampled momentum points.

dual abstractmethod property

dual

Return the dual object associated with this instance.

Returns:

Type Description
Any

Dual representation of this object. Concrete subclasses should return a value of the domain-specific dual type.

dim property

dim: int

Return the geometric dimension of the affine space.

This is the number of primitive basis vectors, equivalently the number of rows of basis and the number of coordinates needed to specify a point/vector in this frame.

basis instance-attribute

basis: ImmutableDenseMatrix

Basis matrix whose columns span the affine coordinate system. Coordinate columns \(r\) in this space represent Cartesian vectors through basis @ r in code, mathematically \(A r\).

cartes abstractmethod

cartes(
    T: type[_O]
    | type[Tensor]
    | type[ndarray]
    | None = None,
    *,
    device: Optional[Device] = None,
) -> tuple[_O, ...] | torch.Tensor | np.ndarray

Enumerate the canonical representatives of the finite lattice.

For a direct lattice this means one representative for every site in the finite periodic supercell. For a reciprocal lattice it means one representative for every sampled momentum point in the discrete Brillouin-zone grid.

Source code in src/qten/geometries/spatials.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
@abstractmethod
def cartes(
    self,
    T: Type[Union[_O, torch.Tensor, np.ndarray]] | None = None,
    *,
    device: Optional[Device] = None,
) -> Union[Tuple[_O, ...], torch.Tensor, np.ndarray]:
    """
    Enumerate the canonical representatives of the finite lattice.

    For a direct lattice this means one representative for every site in
    the finite periodic supercell. For a reciprocal lattice it means one
    representative for every sampled momentum point in the discrete
    Brillouin-zone grid.
    """
    raise NotImplementedError()

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

origin

origin() -> Offset[AffineSpace]

Return the zero vector of this affine space.

Physically this is the chosen coordinate origin. In fractional coordinates it is the column of all zeros, and in Cartesian coordinates it maps to the zero displacement.

Source code in src/qten/geometries/spatials.py
139
140
141
142
143
144
145
146
147
def origin(self) -> "Offset":
    """
    Return the zero vector of this affine space.

    Physically this is the chosen coordinate origin. In fractional
    coordinates it is the column of all zeros, and in Cartesian coordinates
    it maps to the zero displacement.
    """
    return Offset(rep=ImmutableDenseMatrix([0] * self.dim), space=self)

__str__

__str__()

Return AffineSpace(basis=...) with the basis shown entry-by-entry.

Source code in src/qten/geometries/spatials.py
149
150
151
152
def __str__(self):
    """Return `AffineSpace(basis=...)` with the basis shown entry-by-entry."""
    data = [[str(sympify(x)) for x in row] for row in self.basis.tolist()]
    return f"AffineSpace(basis={data})"

__repr__

__repr__()

Return the same display string as __str__().

Source code in src/qten/geometries/spatials.py
154
155
156
def __repr__(self):
    """Return the same display string as [`__str__()`][qten.geometries.spatials.AffineSpace.__str__]."""
    return str(self)

Lattice dataclass

Lattice(
    basis: ImmutableDenseMatrix,
    boundaries: BoundaryCondition | None = None,
    unit_cell: Mapping[str, ImmutableDenseMatrix]
    | None = None,
    shape: Sequence[int] | None = None,
)

Bases: AbstractLattice['Offset']

Periodic real-space lattice with an optional multi-site unit cell.

A Lattice combines three ingredients:

  • basis, whose columns are the primitive real-space lattice vectors.
  • boundaries, which identify lattice translations related by the finite periodic supercell.
  • unit_cell, which places one or more orbitals/sites inside each primitive cell using fractional coordinates.

If the primitive basis is \(A\) and a site has fractional coordinates \(r = n + \tau\), with integer cell index \(n\) and intra-cell offset \(\tau\), then its physical Cartesian position is \(x = A(n + \tau)\). In code, this is the same basis @ rep convention.

Registered operations

The inherited operator dunders from Operable are hidden from the generated API page. For Lattice, the concrete multimethod behavior defined in this module is:

  • offset in lattice: membership test for Offset values. The queried offset is first rebased into this lattice, then its fractional part is compared against the set of unit-cell site positions. Equivalently, this asks whether the point is a lattice site modulo lattice translations.

No arithmetic operators are registered directly on Lattice.

String representations
  • str(lattice) returns Lattice(basis=..., boundaries=...).
  • The basis part is shown as a nested list of stringified SymPy entries.
  • The boundaries part uses the boundary object's own str(...) representation.
  • repr(lattice) is identical to str(lattice).

This representation is meant to show the real-space primitive vectors and the finite periodic boundary data, but it does not expand the unit cell.

Attributes:

Name Type Description
basis ImmutableDenseMatrix

Real-space basis matrix of the lattice.

boundaries BoundaryCondition

Boundary condition defining the finite periodic region.

_unit_cell_fractional FrozenDict

Mapping from unit-cell Offset representatives to their canonical wrapped fractional coordinates.

Construct a lattice from a basis, boundary condition, and unit cell.

Parameters:

Name Type Description Default
basis ImmutableDenseMatrix

Real-space basis matrix.

required
boundaries BoundaryCondition | None

Boundary condition defining the periodic region. If omitted, shape is used to build a PeriodicBoundary.

None
unit_cell Mapping[str, ImmutableDenseMatrix] | None

Mapping from site labels to site positions in fractional coordinates.

None
shape Sequence[int] | None

Legacy shorthand for a diagonal periodic boundary.

None
Notes

The unit_cell positions are stored in fractional lattice coordinates. An entry such as (1/2, 0) means "halfway along the first primitive vector inside the cell", not Cartesian coordinates.

Source code in src/qten/geometries/spatials.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def __init__(
    self,
    basis: ImmutableDenseMatrix,
    boundaries: BoundaryCondition | None = None,
    unit_cell: Mapping[str, ImmutableDenseMatrix] | None = None,
    shape: Sequence[int] | None = None,
):
    """
    Construct a lattice from a basis, boundary condition, and unit cell.

    Parameters
    ----------
    basis : ImmutableDenseMatrix
        Real-space basis matrix.
    boundaries : BoundaryCondition | None
        Boundary condition defining the periodic region. If omitted,
        `shape` is used to build a [`PeriodicBoundary`][qten.geometries.boundary.PeriodicBoundary].
    unit_cell : Mapping[str, ImmutableDenseMatrix] | None
        Mapping from site labels to site positions in fractional coordinates.
    shape : Sequence[int] | None
        Legacy shorthand for a diagonal periodic boundary.

    Notes
    -----
    The `unit_cell` positions are stored in fractional lattice
    coordinates. An entry such as `(1/2, 0)` means "halfway along the first
    primitive vector inside the cell", not Cartesian coordinates.
    """
    object.__setattr__(self, "basis", basis)

    if boundaries is None:
        if shape is None:
            raise TypeError(
                "Lattice requires either `boundaries` or legacy `shape`."
            )
        if len(shape) != self.dim:
            raise ValueError(
                f"shape must have length {self.dim}, got {len(shape)}."
            )
        if any(int(n) <= 0 for n in shape):
            raise ValueError(f"shape entries must be positive, got {tuple(shape)}.")
        boundaries = PeriodicBoundary(ImmutableDenseMatrix.diag(*map(int, shape)))
    elif shape is not None and tuple(map(int, shape)) != tuple(
        int(n) for n in smith_normal_form(boundaries.basis, domain=sy.ZZ).diagonal()
    ):
        raise ValueError(
            "`shape` and `boundaries` are inconsistent; provide only one "
            "or ensure they represent the same periodic extents."
        )
    object.__setattr__(self, "boundaries", boundaries)

    if unit_cell is None:
        unit_cell = {"r": ImmutableDenseMatrix([0] * self.dim)}

    if len(unit_cell) == 0:
        raise ValueError(
            "unit_cell is empty; define at least one site in unit_cell."
        )

    processed_cell: dict[str, ImmutableDenseMatrix] = {}
    for site, offset in unit_cell.items():
        if not isinstance(offset, ImmutableDenseMatrix):
            raise TypeError(
                f"unit_cell['{site}'] must be ImmutableDenseMatrix, got {type(offset).__name__}."
            )
        if offset.shape != (self.dim, 1):
            try:
                offset = offset.reshape(self.dim, 1)
            except Exception as e:
                raise ValueError(
                    f"unit_cell['{site}'] has shape {offset.shape}; expected ({self.dim}, 1)."
                ) from e
        processed_cell[site] = offset
    object.__setattr__(self, "_unit_cell_fractional", FrozenDict(processed_cell))

boundaries instance-attribute

boundaries: BoundaryCondition

Boundary condition defining the finite periodic region and canonical representative choice for lattice coordinates.

shape cached property

shape: tuple[int, ...]

Return the finite lattice periods along independent primitive directions.

This is extracted from the Smith normal form of the boundary matrix, so it describes the invariant factors of the quotient group of lattice translations. For diagonal boundaries it reduces to the familiar system size (L_1, ..., L_d).

unit_cell cached property

unit_cell: FrozenDict

Return the basis sites/orbitals of one primitive cell.

Each value is an Offset whose fractional part specifies the site position τ inside the unit cell. Physically, these are the inequivalent basis positions that are repeated by all lattice translations.

dual cached property

dual: ReciprocalLattice

Return the reciprocal lattice dual to this real-space lattice.

If the direct basis is A, the reciprocal basis is \(G = 2\pi (A^{-1})^{\mathsf{T}}\). This convention ensures

\(\exp(\mathrm{i}\, G_j \cdot A_k) = 1\) for primitive direct/reciprocal basis pairs and lets Fourier phases be written directly as \(\exp(-\mathrm{i}\, k \cdot r)\).

dim property

dim: int

Return the geometric dimension of the affine space.

This is the number of primitive basis vectors, equivalently the number of rows of basis and the number of coordinates needed to specify a point/vector in this frame.

basis instance-attribute

basis: ImmutableDenseMatrix

Basis matrix whose columns span the affine coordinate system. Coordinate columns \(r\) in this space represent Cartesian vectors through basis @ r in code, mathematically \(A r\).

affine property

affine: AffineSpace

Return the underlying continuous affine space.

This forgets the discrete sampled set and keeps only the basis. It is useful when you want to talk about arbitrary vectors in the same frame, not only allowed lattice sites or sampled momentum points.

__str__

__str__()

Return Lattice(basis=..., boundaries=...) using readable symbolic entries.

Source code in src/qten/geometries/spatials.py
277
278
279
280
def __str__(self):
    """Return `Lattice(basis=..., boundaries=...)` using readable symbolic entries."""
    basis_data = [[str(sympify(x)) for x in row] for row in self.basis.tolist()]
    return f"Lattice(basis={basis_data}, boundaries={self.boundaries})"

__repr__

__repr__()

Return the same display string as __str__().

Source code in src/qten/geometries/spatials.py
282
283
284
def __repr__(self):
    """Return the same display string as [`__str__()`][qten.geometries.spatials.Lattice.__str__]."""
    return str(self)

cartes cached

cartes(
    T: type[Offset[Any]]
    | type[Tensor]
    | type[ndarray]
    | None = None,
    *,
    device: Optional[Device] = None,
) -> tuple[Offset[Any], ...] | torch.Tensor | np.ndarray

Enumerate every site in the finite lattice.

Parameters:

Name Type Description Default
T Type[Union[Offset, Tensor, ndarray]]

Requested return type. Offset returns lattice-site objects, while torch.Tensor and np.ndarray return Cartesian coordinates with shape (n_sites, dim).

None
Notes

The enumeration consists of one wrapped representative for every periodic cell in boundaries, combined with every site in unit_cell. In tensor/array form, the output is already converted to Cartesian coordinates with basis @ rep, mathematically \(A r\).

Source code in src/qten/geometries/spatials.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
@lru_cache
@override
def cartes(
    self,
    T: Type[Union["Offset", torch.Tensor, np.ndarray]] | None = None,
    *,
    device: Optional[Device] = None,
) -> Union[Tuple["Offset", ...], torch.Tensor, np.ndarray]:
    r"""
    Enumerate every site in the finite lattice.

    Parameters
    ----------
    T : Type[Union[Offset, torch.Tensor, np.ndarray]]
        Requested return type. [`Offset`][qten.geometries.spatials.Offset] returns lattice-site objects,
        while `torch.Tensor` and `np.ndarray` return Cartesian coordinates
        with shape `(n_sites, dim)`.

    Notes
    -----
    The enumeration consists of one wrapped representative for every
    periodic cell in `boundaries`, combined with every site in `unit_cell`.
    In tensor/array form, the output is already converted to Cartesian
    coordinates with `basis @ rep`, mathematically \(A r\).
    """
    if T == torch.Tensor:
        return _lattice_coords(self, device=device)
    if T == np.ndarray:
        return cast(np.ndarray, _lattice_coords(self).detach().cpu().numpy())
    if T not in (None, Offset):
        raise TypeError(
            f"Unsupported type {T} for cartes. Supported types: Offset, torch.Tensor, np.ndarray"
        )

    elements = self.boundaries.representatives()
    unit_cell_sites = tuple(self.unit_cell.values())
    return tuple(
        Offset(rep=ImmutableDenseMatrix(element + site.rep), space=self)
        for element in elements
        for site in unit_cell_sites
    )

basis_vectors cached

basis_vectors() -> tuple[Offset, ...]

Return the primitive basis vectors as spatial Offsets.

If a primitive vector coincides with a valid lattice site modulo unit-cell offsets, it is returned in self. Otherwise it is returned in self.affine, since the translation vector is still a valid spatial vector even when it is not itself a site of the lattice.

Physically, these vectors generate translations from one primitive cell to neighboring primitive cells. Whether they are also valid "sites" depends on the chosen unit-cell basis positions.

Source code in src/qten/geometries/spatials.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
@lru_cache
def basis_vectors(self) -> Tuple["Offset", ...]:
    """
    Return the primitive basis vectors as spatial [`Offset`][qten.geometries.spatials.Offset]s.

    If a primitive vector coincides with a valid lattice site modulo unit-cell
    offsets, it is returned in `self`. Otherwise it is returned in
    `self.affine`, since the translation vector is still a valid spatial
    vector even when it is not itself a site of the lattice.

    Physically, these vectors generate translations from one primitive cell
    to neighboring primitive cells. Whether they are also valid "sites"
    depends on the chosen unit-cell basis positions.
    """
    vectors = []
    for j in range(self.dim):
        rep = ImmutableDenseMatrix(
            [sy.Integer(1) if i == j else sy.Integer(0) for i in range(self.dim)]
        )
        candidate = Offset(rep=rep, space=self.affine)
        vectors.append(candidate.rebase(self) if candidate in self else candidate)
    return tuple(vectors)

at

at(
    unit_cell: str = "r",
    cell_offset: Sequence[int] | None = None,
) -> Offset[Lattice]

Create a lattice offset from a unit-cell site and an integer cell offset.

Parameters:

Name Type Description Default
unit_cell str

Label of the site within the unit cell.

'r'
cell_offset Sequence[int] | None

Integer translation in lattice coordinates. If omitted, the origin cell is used.

None

Returns:

Type Description
Offset[Lattice]

The site with fractional coordinates n + τ, where n is the integer cell_offset and τ is the selected unit-cell position.

Physically this picks a specific basis site in a specific translated
unit cell, then wraps it into the canonical representative of the
finite periodic lattice.
Source code in src/qten/geometries/spatials.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def at(
    self, unit_cell: str = "r", cell_offset: Sequence[int] | None = None
) -> "Offset[Lattice]":
    """
    Create a lattice offset from a unit-cell site and an integer cell offset.

    Parameters
    ----------
    unit_cell : str
        Label of the site within the unit cell.
    cell_offset : Sequence[int] | None
        Integer translation in lattice coordinates. If omitted, the origin
        cell is used.

    Returns
    -------
    Offset[Lattice]
        The site with fractional coordinates `n + τ`, where `n` is the
        integer `cell_offset` and `τ` is the selected unit-cell position.

    Physically this picks a specific basis site in a specific translated
    unit cell, then wraps it into the canonical representative of the
    finite periodic lattice.
    """
    try:
        site = self.unit_cell[unit_cell]
    except KeyError as e:
        raise KeyError(f"Unknown unit-cell site {unit_cell!r}.") from e

    if cell_offset is None:
        cell_offset = (0,) * self.dim
    elif len(cell_offset) != self.dim:
        raise ValueError(
            f"cell_offset must have length {self.dim}, got {len(cell_offset)}."
        )

    rep = ImmutableDenseMatrix(tuple(cell_offset)) + site.rep
    return Offset(rep=ImmutableDenseMatrix(rep), space=self)

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

origin

origin() -> Offset[AffineSpace]

Return the zero vector of this affine space.

Physically this is the chosen coordinate origin. In fractional coordinates it is the column of all zeros, and in Cartesian coordinates it maps to the zero displacement.

Source code in src/qten/geometries/spatials.py
139
140
141
142
143
144
145
146
147
def origin(self) -> "Offset":
    """
    Return the zero vector of this affine space.

    Physically this is the chosen coordinate origin. In fractional
    coordinates it is the column of all zeros, and in Cartesian coordinates
    it maps to the zero displacement.
    """
    return Offset(rep=ImmutableDenseMatrix([0] * self.dim), space=self)

ReciprocalLattice dataclass

ReciprocalLattice(
    basis: ImmutableDenseMatrix, lattice: Lattice
)

Bases: AbstractLattice['Momentum']

Reciprocal-space lattice dual to a real-space Lattice.

This object represents the finite set of crystal momenta compatible with the periodic real-space lattice. Its basis vectors are the reciprocal primitive vectors, and its canonical points are the sampled momenta of the discrete Brillouin-zone mesh induced by the real-space supercell.

Registered operations

The inherited operator dunders from Operable are hidden from the generated API page. For ReciprocalLattice, the concrete multimethod behavior defined in this module is:

  • momentum in reciprocal_lattice: membership test for Momentum values. This checks that the queried point belongs to the same reciprocal lattice and lies on the sampled discrete momentum grid modulo reciprocal lattice vectors.

No arithmetic operators are registered directly on ReciprocalLattice.

String representations
  • str(reciprocal) returns ReciprocalLattice(basis=..., shape=...).
  • basis is shown as a nested list of stringified SymPy entries.
  • shape is the canonical finite reciprocal-grid shape derived from the dual direct lattice.
  • repr(reciprocal) is identical to str(reciprocal).

The display emphasizes the reciprocal primitive vectors and the sampled grid size rather than printing the full underlying direct lattice.

Attributes:

Name Type Description
basis ImmutableDenseMatrix

Reciprocal basis matrix including the conventional \(2\pi\) factor.

lattice Lattice

Real-space lattice from which this reciprocal lattice is derived.

lattice instance-attribute

lattice: Lattice

Real-space lattice from which this reciprocal lattice is derived. Its boundary data determines the discrete Brillouin-zone sampling shape.

shape cached property

shape: tuple[int, ...]

Return the reciprocal-grid periods.

These match the invariant factors of the direct finite lattice. In a finite periodic system, the number of allowed momentum samples along each independent reciprocal direction is therefore the same as the number of real-space periods along the dual direct direction.

size cached property

size: int

Return the number of distinct sampled momentum points.

For a finite periodic lattice, this equals the number of unit-cell translation sectors in real space, i.e. the size of the discrete translation group.

dual cached property

dual: Lattice

Return the underlying direct-space lattice whose Fourier dual this is.

dim property

dim: int

Return the geometric dimension of the affine space.

This is the number of primitive basis vectors, equivalently the number of rows of basis and the number of coordinates needed to specify a point/vector in this frame.

basis instance-attribute

basis: ImmutableDenseMatrix

Basis matrix whose columns span the affine coordinate system. Coordinate columns \(r\) in this space represent Cartesian vectors through basis @ r in code, mathematically \(A r\).

affine property

affine: AffineSpace

Return the underlying continuous affine space.

This forgets the discrete sampled set and keeps only the basis. It is useful when you want to talk about arbitrary vectors in the same frame, not only allowed lattice sites or sampled momentum points.

__str__

__str__()

Return ReciprocalLattice(basis=..., shape=...) for readable inspection.

Source code in src/qten/geometries/spatials.py
610
611
612
613
def __str__(self):
    """Return `ReciprocalLattice(basis=..., shape=...)` for readable inspection."""
    basis_data = [[str(sympify(x)) for x in row] for row in self.basis.tolist()]
    return f"ReciprocalLattice(basis={basis_data}, shape={self.shape})"

__repr__

__repr__()

Return the same display string as __str__().

Source code in src/qten/geometries/spatials.py
615
616
617
def __repr__(self):
    """Return the same display string as [`__str__()`][qten.geometries.spatials.ReciprocalLattice.__str__]."""
    return str(self)

cartes cached

cartes(
    T: type[Momentum]
    | type[Tensor]
    | type[ndarray]
    | None = None,
    *,
    device: Optional[Device] = None,
) -> tuple[Momentum, ...] | torch.Tensor | np.ndarray

Enumerate canonical momentum points.

Parameters:

Name Type Description Default
T Type[Union[Momentum, Tensor, ndarray]]

Requested return type. Momentum returns momentum-point objects, while torch.Tensor and np.ndarray return Cartesian coordinates with shape (n_points, dim).

None
Notes

The allowed points are representatives of the quotient \(\mathbb{Z}^d / N^{\mathsf{T}}\mathbb{Z}^d\), where \(N\) is the direct-lattice boundary matrix. In fractional reciprocal coordinates this means points of the form \(\kappa = N^{-\mathsf{T}}m\) modulo integers, which are then wrapped into the first reciprocal cell.

Source code in src/qten/geometries/spatials.py
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
@lru_cache
@override
def cartes(
    self,
    T: Type[Union["Momentum", torch.Tensor, np.ndarray]] | None = None,
    *,
    device: Optional[Device] = None,
) -> Union[Tuple["Momentum", ...], torch.Tensor, np.ndarray]:
    r"""
    Enumerate canonical momentum points.

    Parameters
    ----------
    T : Type[Union[Momentum, torch.Tensor, np.ndarray]]
        Requested return type. [`Momentum`][qten.geometries.spatials.Momentum] returns momentum-point objects, while
        `torch.Tensor` and `np.ndarray` return Cartesian coordinates with
        shape `(n_points, dim)`.

    Notes
    -----
    The allowed points are representatives of the quotient
    \(\mathbb{Z}^d / N^{\mathsf{T}}\mathbb{Z}^d\), where \(N\) is the
    direct-lattice boundary matrix. In fractional reciprocal coordinates
    this means points of the form
    \(\kappa = N^{-\mathsf{T}}m\) modulo integers, which are then wrapped
    into the first reciprocal cell.
    """
    torch_device = device.torch_device() if device is not None else None
    # Enumerate one representative per class in Z^d / N^T Z^d, where N is
    # the direct-lattice boundary basis. Allowed fractional reciprocal
    # coordinates are then N^{-T} m modulo Z^d.
    direct_boundary = self.lattice.boundaries.basis
    dual_boundary = PeriodicBoundary(ImmutableDenseMatrix(direct_boundary.T))
    integer_reps = dual_boundary.representatives()
    dual_transform = ImmutableDenseMatrix(direct_boundary.inv().T)
    momenta = tuple(
        Momentum(
            rep=ImmutableDenseMatrix(dual_transform @ rep), space=self
        ).fractional()
        for rep in integer_reps
    )
    if T in (None, Momentum):
        return momenta
    if T == np.ndarray:
        precision = get_precision_config()
        return np.stack(
            [
                np.array(momentum.to_vec(np.ndarray), dtype=precision.np_float)
                for momentum in momenta
            ]
        )
    if T == torch.Tensor:
        precision = get_precision_config()
        return torch.tensor(
            self.cartes(np.ndarray),
            dtype=precision.torch_float,
            device=torch_device,
        )
    raise TypeError(
        f"Unsupported type {T} for cartes. Supported types: Momentum, torch.Tensor, np.ndarray"
    )

basis_vectors cached

basis_vectors() -> tuple[Offset[Any], ...]

Return the primitive reciprocal basis vectors as spatial objects.

If a primitive reciprocal vector coincides with a sampled momentum point, it is returned as a Momentum in self. Otherwise it is returned as an Offset in self.affine.

Physically, these are the reciprocal vectors that generate translations in momentum space by one reciprocal lattice period. A primitive reciprocal vector need not itself be one of the finite sampled momenta of the discrete grid.

Source code in src/qten/geometries/spatials.py
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
@lru_cache
def basis_vectors(self) -> Tuple["Offset", ...]:
    """
    Return the primitive reciprocal basis vectors as spatial objects.

    If a primitive reciprocal vector coincides with a sampled momentum point,
    it is returned as a [`Momentum`][qten.geometries.spatials.Momentum] in `self`. Otherwise it is returned as an
    [`Offset`][qten.geometries.spatials.Offset] in `self.affine`.

    Physically, these are the reciprocal vectors that generate translations
    in momentum space by one reciprocal lattice period. A primitive
    reciprocal vector need not itself be one of the finite sampled momenta
    of the discrete grid.
    """
    vectors = []
    for j in range(self.dim):
        rep = ImmutableDenseMatrix(
            [sy.Integer(1) if i == j else sy.Integer(0) for i in range(self.dim)]
        )
        candidate = Offset(rep=rep, space=self.affine)
        momentum_candidate = Momentum(rep=rep, space=self)
        vectors.append(
            momentum_candidate
            if _is_reciprocal_grid_point(self, momentum_candidate, canonical=True)
            else candidate
        )
    return tuple(vectors)

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

origin

origin() -> Offset[AffineSpace]

Return the zero vector of this affine space.

Physically this is the chosen coordinate origin. In fractional coordinates it is the column of all zeros, and in Cartesian coordinates it maps to the zero displacement.

Source code in src/qten/geometries/spatials.py
139
140
141
142
143
144
145
146
147
def origin(self) -> "Offset":
    """
    Return the zero vector of this affine space.

    Physically this is the chosen coordinate origin. In fractional
    coordinates it is the column of all zeros, and in Cartesian coordinates
    it maps to the zero displacement.
    """
    return Offset(rep=ImmutableDenseMatrix([0] * self.dim), space=self)

Offset dataclass

Offset(rep: ImmutableDenseMatrix, space: S)

Bases: Generic[S], Spatial, HasBase[S]

Offset vector in an affine basis.

An Offset stores coordinates in the basis of some AffineSpace. It can represent a displacement, a point relative to an origin, or a lattice site position, depending on the surrounding context. The physically meaningful Cartesian vector is always \(A r\), where \(A\) is space.basis and \(r\) is rep.

Registered operations

The public arithmetic and comparison operators for Offset are implemented by multimethod registrations on Operable. Those inherited __xxx__ members are hidden from the generated API page, so this section is the canonical reference for Offset-specific operator behavior.

Addition, subtraction, and negation
  • x + y: add two offsets. If they are expressed in different affine spaces, y is first rebased into x.space; the result is returned in x.space.
  • x - y: subtract two offsets via x + (-y), again rebasing the right-hand operand when needed.
  • -x: negate the coordinates while preserving the ambient space.

These operations preserve the represented geometric vector, up to the periodic wrapping rules of a finite Lattice.

Scalar multiplication
  • c * x and x * c are registered for numeric scalars (numbers.Number).
  • expr * x and x * expr are also registered for non-numeric sympy.Expr values.

In all four cases, the coordinates are scaled symbolically and the result stays in the same ambient space. When that space is a finite lattice, the result is normalized to the canonical wrapped representative by Offset.__post_init__().

Ordered comparisons
  • x < y
  • x > y

These are registered only for offset-offset comparisons. If dimensions differ, comparison is by dimension. If dimensions match, both operands are converted to Cartesian vectors and compared lexicographically. This gives a deterministic ordering useful for sorting and tie-breaking, not a physical partial order.

Unsupported operators

The following Operable operators have no registrations for Offset in this module and therefore raise NotImplementedError when dispatched:

  • containment as the queried object, e.g. offset in something unless that container type registers support,
  • <=, >=,
  • matrix multiplication @,
  • true division / and reflected true division,
  • floor division //,
  • exponentiation **,
  • logical & and |.
String representations
  • str(offset) returns Offset(rep ∈ basis) in a compact symbolic form.
  • If rep is a column vector, it is flattened and shown as a one-dimensional Python list like ['1/2', '0'].
  • If rep is not a single column, it is shown as a nested list preserving its matrix shape.
  • The ambient-space basis is always shown as a nested list of stringified SymPy entries after the symbol.
  • repr(offset) is identical to str(offset).

This means the string form shows the coordinate representation and the basis it lives in, not the Cartesian vector space.basis @ rep (mathematically \(A r\)).

Let \(x = (r_x, S_x)\) and \(y = (r_y, S_y)\), where \(r_x, r_y \in \mathbb{R}^{d \times 1}\) are coordinate columns and \(S_x, S_y\) are affine spaces with basis matrices \(B_x, B_y\).

Algebra

Negation is \(-x = (-r_x, S_x)\).

Addition is \(x + y = (r_x + \tilde r_y, S_x)\), where \(\tilde r_y = B_x^{-1} B_y r_y\) if \(S_x \ne S_y\) (equivalently, rebase \(y\) into \(S_x\) first).

Subtraction is \(x - y = x + (-y)\).

Equality

Equality is \(x = y \iff (r_x = r_y) \land (S_x = S_y)\). This is exact structural equality; no implicit rebasing is applied.

Order

For \(x < y\) and \(x > y\): compare \(d_x\) and \(d_y\) first. If \(d_x = d_y\), compare Cartesian tuples \(\mathrm{tuple}(B_x r_x)\) and \(\mathrm{tuple}(B_y r_y)\) lexicographically.

Attributes:

Name Type Description
rep ImmutableDenseMatrix

Column vector of coordinates expressed in space.

space AffineSpace

Affine space that defines the coordinate basis for rep.

rep instance-attribute

rep: ImmutableDenseMatrix

Column vector of coordinates expressed in space. The physically represented Cartesian vector is obtained from \(A r\), using space.basis as \(A\) and rep as \(r\).

space instance-attribute

space: S

Affine space that defines the coordinate basis for rep, including how those coordinates should be interpreted and rebased.

dim property

dim: int

Return the coordinate dimension of this offset.

This equals the dimension of the ambient space, not the number of physically distinct periodic images.

fractional

fractional() -> Offset[S]
Source code in src/qten/geometries/spatials.py
121
basis: ImmutableDenseMatrix

__post_init__

__post_init__() -> None

Normalize lattice offsets into the canonical wrapped representative.

When space is a finite Lattice, positions related by the boundary condition are physically equivalent. This hook stores the canonical representative chosen by space.boundaries.wrap.

Source code in src/qten/geometries/spatials.py
919
920
921
922
923
924
925
926
927
928
929
930
def __post_init__(self):
    """
    Normalize lattice offsets into the canonical wrapped representative.

    When `space` is a finite [`Lattice`][qten.geometries.spatials.Lattice],
    positions related by the boundary condition are physically equivalent.
    This hook stores the canonical representative chosen by
    `space.boundaries.wrap`.
    """
    if isinstance(self.space, Lattice):
        wrapped = self.space.boundaries.wrap(self.rep)
        object.__setattr__(self, "rep", ImmutableDenseMatrix(wrapped))

base

base() -> S

Return the affine space whose basis defines these coordinates.

Mathematically, this is the object that supplies the matrix \(A\) in the Cartesian embedding \(x = A\,\mathrm{rep}\). In code, this is space.basis @ rep.

Source code in src/qten/geometries/spatials.py
958
959
960
961
962
963
964
965
966
def base(self) -> S:
    r"""
    Return the affine space whose basis defines these coordinates.

    Mathematically, this is the object that supplies the matrix \(A\) in the
    Cartesian embedding \(x = A\,\mathrm{rep}\). In code, this is
    `space.basis @ rep`.
    """
    return self.space

rebase

rebase(space: S) -> Offset[S]

Re-express this Offset in a different AffineSpace.

Parameters:

Name Type Description Default
space AffineSpace

The new affine space to express this Offset in.

required

Returns:

Type Description
Offset

New Offset expressed in the given affine space.

Notes

Rebasing changes only the coordinates, not the physical vector. If \(x = A_{\mathrm{old}}r_{\mathrm{old}} = A_{\mathrm{new}}r_{\mathrm{new}}\), this method computes \(r_{\mathrm{new}} = A_{\mathrm{new}}^{-1}A_{\mathrm{old}}r_{\mathrm{old}}\). In code, the transform matrix is space.basis.inv() @ self.space.basis.

Source code in src/qten/geometries/spatials.py
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def rebase(self, space: S) -> "Offset[S]":
    r"""
    Re-express this Offset in a different AffineSpace.

    Parameters
    ----------
    space : AffineSpace
        The new affine space to express this Offset in.

    Returns
    -------
    Offset
        New Offset expressed in the given affine space.

    Notes
    -----
    Rebasing changes only the coordinates, not the physical vector. If
    \(x = A_{\mathrm{old}}r_{\mathrm{old}} =
    A_{\mathrm{new}}r_{\mathrm{new}}\), this method computes
    \(r_{\mathrm{new}} =
    A_{\mathrm{new}}^{-1}A_{\mathrm{old}}r_{\mathrm{old}}\). In code,
    the transform matrix is `space.basis.inv() @ self.space.basis`.
    """
    rebase_transform_mat = _rebase_transform_matrix(self.space, space)
    new_rep = rebase_transform_mat @ self.rep
    return Offset(rep=ImmutableDenseMatrix(new_rep), space=space)

to_vec

to_vec(T: type[_VecType] = sy.ImmutableMatrix) -> _VecType

Convert this offset from basis coordinates to Cartesian coordinates.

If rep stores coefficients in the primitive basis, this method returns the physical vector \(A r\), using space.basis as \(A\) and rep as \(r\). This is the quantity that should be used in Euclidean geometry and Fourier phases.

Returns:

Type Description
ImmutableDenseMatrix

The Cartesian coordinate vector corresponding to this offset.

Source code in src/qten/geometries/spatials.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def to_vec(self, T: Type[_VecType] = sy.ImmutableMatrix) -> _VecType:
    r"""
    Convert this offset from basis coordinates to Cartesian coordinates.

    If `rep` stores coefficients in the primitive basis, this method returns
    the physical vector \(A r\), using `space.basis` as \(A\) and `rep` as
    \(r\). This is the quantity that should be used in Euclidean geometry
    and Fourier phases.

    Returns
    -------
    ImmutableDenseMatrix
        The Cartesian coordinate vector corresponding to this offset.
    """
    vec = self.space.basis @ self.rep
    if T == ImmutableDenseMatrix:
        return vec
    elif T == np.ndarray:
        precision = get_precision_config()
        return cast(
            _VecType, np.array(vec.evalf(), dtype=precision.np_float).reshape(-1)
        )
    else:
        raise TypeError(
            f"Unsupported type {T} for to_vec. Supported types: np.ndarray, ImmutableDenseMatrix"
        )

distance

distance(r: Offset[Any]) -> float

Return the geometric distance to another offset.

If either offset is expressed on a lattice with periodic boundary conditions, the distance is computed using the nearest periodic image of the displacement in that lattice. Otherwise, the plain Euclidean norm of the displacement in the current affine space is returned.

Physically, for lattice points this is the minimum-image distance on the torus defined by the finite supercell, not the naive distance between two unwrapped representatives.

Source code in src/qten/geometries/spatials.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
def distance(self, r: "Offset") -> float:
    """
    Return the geometric distance to another offset.

    If either offset is expressed on a lattice with periodic boundary
    conditions, the distance is computed using the nearest periodic image
    of the displacement in that lattice. Otherwise, the plain Euclidean
    norm of the displacement in the current affine space is returned.

    Physically, for lattice points this is the minimum-image distance on the
    torus defined by the finite supercell, not the naive distance between
    two unwrapped representatives.
    """
    if isinstance(self.space, Lattice):
        delta = self - r.rebase(self.space)
        return self.space.boundaries.distance(delta.rep, self.space.basis)

    if isinstance(r.space, Lattice):
        delta = r - self.rebase(r.space)
        return r.space.boundaries.distance(delta.rep, r.space.basis)

    target_space = self.space
    delta_cart = _cartesian_delta(self, r, target_space)
    return float(np.linalg.norm(delta_cart.reshape(-1)))

__str__

__str__()

Return a symbolic display of the stored coordinates and ambient basis.

Column-vector coordinates are flattened for readability; higher-rank matrix representations keep their nested-list structure. The basis of space is always included so the printed coordinates remain unambiguous.

Source code in src/qten/geometries/spatials.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
def __str__(self):
    """
    Return a symbolic display of the stored coordinates and ambient basis.

    Column-vector coordinates are flattened for readability; higher-rank
    matrix representations keep their nested-list structure. The basis of
    `space` is always included so the printed coordinates remain
    unambiguous.
    """
    # If it's a column vector, flatten to 1D python list
    if self.rep.shape[1] == 1:
        vec = [str(sympify(v)) for v in list(self.rep)]
    else:
        vec = [[str(sympify(x)) for x in row] for row in self.rep.tolist()]
    basis = [[str(sympify(x)) for x in row] for row in self.space.basis.tolist()]
    return f"Offset({vec}{basis})"

__repr__

__repr__()

Return the same display string as __str__().

Source code in src/qten/geometries/spatials.py
1064
1065
1066
def __repr__(self):
    """Return the same display string as [`__str__()`][qten.geometries.spatials.Offset.__str__]."""
    return str(self)

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

Momentum dataclass

Momentum(rep: ImmutableDenseMatrix, space: S)

Bases: Offset[ReciprocalLattice], Convertible

Reciprocal-space coordinate expressed in a ReciprocalLattice.

A Momentum is the reciprocal-space analogue of Offset. Its fractional coordinates are coefficients in the reciprocal basis vectors. Because the reciprocal basis already contains the conventional \(2\pi\), the Cartesian vector returned by to_vec() can be inserted directly into phases such as \(\exp(-\mathrm{i}\, k\cdot r)\). In code, that Cartesian vector is computed from space.basis @ rep.

Registered operations

Momentum overrides the Offset arithmetic registrations with momentum-preserving versions where appropriate.

Addition, subtraction, and negation
  • k + q: add two momenta. If they are expressed in different reciprocal lattices, the right-hand operand is first rebased into the left-hand space. The result is a Momentum.
  • k - q: subtract two momenta via k + (-q).
  • -k: negate the momentum coordinates and return a Momentum.

These operations preserve the interpretation as reciprocal-space vectors instead of falling back to plain Offset results.

Scalar multiplication

Momentum does not define separate multiplication registrations in this module. It inherits the Offset registrations, and those dispatch through type(r)(...), so both numeric and symbolic scalar multiplication still return a Momentum:

  • c * k, k * c for numeric scalars,
  • expr * k, k * expr for non-numeric sympy.Expr scalars.
Containment and unsupported operators

Momentum itself is the queried value in momentum in reciprocal_lattice; the actual membership registration lives on ReciprocalLattice.

As for Offset, there are no registrations here for <=, >=, @, /, reflected /, //, **, &, or |.

String representations

Momentum inherits Offset.__str__() and Offset.__repr__(). Concretely:

  • str(momentum) prints Offset(rep ∈ basis), not a separate Momentum(...) wrapper.
  • rep is the reciprocal-coordinate column, flattened when it is a single column.
  • basis is the reciprocal-lattice basis, so the display still makes it clear that the object lives in momentum space.
  • repr(momentum) is identical to str(momentum).

This is intentionally representation-centric: it shows the stored reciprocal coordinates and reciprocal basis directly.

Attributes:

Name Type Description
rep ImmutableDenseMatrix

Column vector of reciprocal coordinates in fractional form.

space ReciprocalLattice

Reciprocal lattice that defines the basis for rep.

dim property

dim: int

Return the coordinate dimension of this offset.

This equals the dimension of the ambient space, not the number of physically distinct periodic images.

rep instance-attribute

rep: ImmutableDenseMatrix

Column vector of coordinates expressed in space. The physically represented Cartesian vector is obtained from \(A r\), using space.basis as \(A\) and rep as \(r\).

space instance-attribute

space: S

Affine space that defines the coordinate basis for rep, including how those coordinates should be interpreted and rebased.

fractional

fractional() -> Momentum
Source code in src/qten/geometries/spatials.py
134
135
of rows of `basis` and the number of coordinates needed to specify a
point/vector in this frame.

base

base() -> ReciprocalLattice

Return the reciprocal lattice whose basis defines these coordinates.

This is the momentum-space frame supplying the reciprocal basis vectors in which rep is expanded.

Source code in src/qten/geometries/spatials.py
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
def base(self) -> ReciprocalLattice:  # type: ignore[override]
    """
    Return the reciprocal lattice whose basis defines these coordinates.

    This is the momentum-space frame supplying the reciprocal basis vectors
    in which `rep` is expanded.
    """
    assert isinstance(self.space, ReciprocalLattice), (
        "Momentum.space must be a ReciprocalLattice"
    )
    return self.space

rebase

rebase(space: ReciprocalLattice) -> Momentum

Re-express this Momentum in a different ReciprocalLattice.

Parameters:

Name Type Description Default
space AffineSpace

The new affine space (must be a ReciprocalLattice) to express this Momentum in.

required

Returns:

Type Description
Momentum

New Momentum expressed in the given reciprocal lattice.

Notes

As with Offset.rebase(), this preserves the physical Cartesian wavevector and only changes the coordinate description.

Source code in src/qten/geometries/spatials.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
def rebase(self, space: ReciprocalLattice) -> "Momentum":  # type: ignore[override]
    """
    Re-express this Momentum in a different ReciprocalLattice.

    Parameters
    ----------
    space : AffineSpace
        The new affine space (must be a ReciprocalLattice) to express this Momentum in.

    Returns
    -------
    Momentum
        New Momentum expressed in the given reciprocal lattice.

    Notes
    -----
    As with [`Offset.rebase()`][qten.geometries.spatials.Offset.rebase],
    this preserves the physical Cartesian wavevector and only changes the
    coordinate description.
    """
    rebase_transform_mat = _rebase_transform_matrix(self.space, space)
    new_rep = rebase_transform_mat @ self.rep
    return Momentum(rep=ImmutableDenseMatrix(new_rep), space=space)

add_conversion classmethod

add_conversion(
    T: type[B],
) -> Callable[[Callable[[A], B]], Callable[[A], B]]

Register a conversion from cls to T.

The decorated function is stored under (cls, T). When an instance of cls later calls convert(T), that function is used to produce the converted object.

Parameters:

Name Type Description Default
T Type[B]

Destination type produced by the registered conversion function.

required

Returns:

Type Description
Callable[[Callable[[A], B]], Callable[[A], B]]

Decorator that stores the conversion function and returns it unchanged.

Examples:

@MyType.add_conversion(TargetType)
def to_target(x: MyType) -> TargetType:
    ...
Source code in src/qten/abstracts.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
@classmethod
def add_conversion(
    cls: Type[A], T: Type[B]
) -> Callable[[Callable[[A], B]], Callable[[A], B]]:
    """
    Register a conversion from `cls` to `T`.

    The decorated function is stored under `(cls, T)`. When an instance of
    `cls` later calls [`convert(T)`][qten.abstracts.Convertible.convert],
    that function is used to produce the converted object.

    Parameters
    ----------
    T : Type[B]
        Destination type produced by the registered conversion function.

    Returns
    -------
    Callable[[Callable[[A], B]], Callable[[A], B]]
        Decorator that stores the conversion function and returns it
        unchanged.

    Examples
    --------
    ```python
    @MyType.add_conversion(TargetType)
    def to_target(x: MyType) -> TargetType:
        ...
    ```
    """

    def decorator(func: Callable[[A], B]) -> Callable[[A], B]:
        _type_conversion_table[(cls, T)] = cast(Callable[[Any], Any], func)
        return func

    return decorator

convert

convert(T: type[B]) -> B

Convert this instance to the requested target type.

Parameters:

Name Type Description Default
T Type[B]

Destination type to convert into.

required

Returns:

Type Description
B

Converted object produced by the registered conversion function.

Raises:

Type Description
NotImplementedError

If no conversion function has been registered for (type(self), T) or any source supertype via add_conversion().

Source code in src/qten/abstracts.py
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
@final
def convert(self, T: Type[B]) -> B:
    """
    Convert this instance to the requested target type.

    Parameters
    ----------
    T : Type[B]
        Destination type to convert into.

    Returns
    -------
    B
        Converted object produced by the registered conversion function.

    Raises
    ------
    NotImplementedError
        If no conversion function has been registered for
        `(type(self), T)` or any source supertype via
        [`add_conversion()`][qten.abstracts.Convertible.add_conversion].
    """
    source_type = type(self)
    table_get = _type_conversion_table.get

    convertor = table_get((source_type, T))
    if convertor is None:
        for super_type in source_type.__mro__[1:]:
            convertor = table_get((super_type, T))
            if convertor is not None:
                # Cache resolved parent conversion under the concrete source type.
                _type_conversion_table[(source_type, T)] = convertor
                break

    if convertor is None:
        raise NotImplementedError(
            f"No conversion from {source_type.__name__} to {T.__name__}!"
        )
    return cast(Callable[["Convertible"], B], convertor)(self)

register_plot_method classmethod

register_plot_method(name: str, backend: str = 'plotly')

Register a backend plotting function for this plottable class.

The returned decorator stores the function in the global plotting registry. Registered functions receive the object being plotted as their first argument, followed by any extra positional and keyword arguments supplied to plot().

Parameters:

Name Type Description Default
name str

User-facing plot method name, such as scatter, structure, or heatmap.

required
backend str

Backend name that selects the implementation. The qten-plots extension currently uses plotly and matplotlib.

'plotly'

Returns:

Type Description
Callable

Decorator that registers the provided plotting function and returns it unchanged.

Source code in src/qten/plottings/_plottings.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def register_plot_method(cls, name: str, backend: str = "plotly"):
    """
    Register a backend plotting function for this plottable class.

    The returned decorator stores the function in the global plotting
    registry. Registered functions receive the object being plotted as their
    first argument, followed by any extra positional and keyword arguments
    supplied to [`plot()`][qten.plottings.Plottable.plot].

    Parameters
    ----------
    name : str
        User-facing plot method name, such as `scatter`, `structure`, or
        `heatmap`.
    backend : str
        Backend name that selects the implementation. The `qten-plots`
        extension currently uses `plotly` and `matplotlib`.

    Returns
    -------
    Callable
        Decorator that registers the provided plotting function and returns
        it unchanged.
    """

    def decorator(func: Callable):
        # We register against 'cls' - the class this method was called on.
        Plottable._registry[(cls, name, backend)] = func
        return func

    return decorator

plot

plot(method: str, backend: str = 'plotly', *args, **kwargs)

Dispatch a named plot method to a registered backend implementation.

The dispatcher first loads plotting entry points, then searches the instance type and its base classes for a matching (type, method, backend) registration. Additional arguments are forwarded unchanged to the selected backend function.

Parameters:

Name Type Description Default
method str

Plot method name registered for this object's type.

required
backend str

Backend implementation to use. The qten-plots extension currently registers plotly and matplotlib.

'plotly'
args

Positional arguments forwarded to the registered plotting function.

()
kwargs

Keyword arguments forwarded to the registered plotting function.

{}

Returns:

Type Description
object

Backend-specific figure object returned by the registered plotting function, such as a Plotly or Matplotlib figure.

Raises:

Type Description
ValueError

If no plotting function is registered for the requested method and backend on this object.

See Also

qten_plots.plottables.PointCloud Public plottable helper object provided by the plotting extension.

Source code in src/qten/plottings/_plottings.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def plot(self, method: str, backend: str = "plotly", *args, **kwargs):
    """
    Dispatch a named plot method to a registered backend implementation.

    The dispatcher first loads plotting entry points, then searches the
    instance type and its base classes for a matching `(type, method,
    backend)` registration. Additional arguments are forwarded unchanged to
    the selected backend function.

    Parameters
    ----------
    method : str
        Plot method name registered for this object's type.
    backend : str
        Backend implementation to use. The `qten-plots` extension currently
        registers `plotly` and `matplotlib`.
    args
        Positional arguments forwarded to the registered plotting function.
    kwargs
        Keyword arguments forwarded to the registered plotting function.

    Returns
    -------
    object
        Backend-specific figure object returned by the registered plotting
        function, such as a Plotly or Matplotlib figure.

    Raises
    ------
    ValueError
        If no plotting function is registered for the requested method and
        backend on this object.

    See Also
    --------
    qten_plots.plottables.PointCloud
        Public plottable helper object provided by the plotting extension.
    """
    Plottable._ensure_backends_loaded()

    # Iterate over the MRO (Method Resolution Order) of the instance
    for class_in_hierarchy in type(self).__mro__:
        key = (class_in_hierarchy, method, backend)

        # Check the central registry
        if key in Plottable._registry:
            plot_func = Plottable._registry[key]
            return plot_func(self, *args, **kwargs)

    # If we reach here, no method was found. Provide a helpful error.
    self._raise_method_not_found(method, backend)

__post_init__

__post_init__() -> None

Normalize lattice offsets into the canonical wrapped representative.

When space is a finite Lattice, positions related by the boundary condition are physically equivalent. This hook stores the canonical representative chosen by space.boundaries.wrap.

Source code in src/qten/geometries/spatials.py
919
920
921
922
923
924
925
926
927
928
929
930
def __post_init__(self):
    """
    Normalize lattice offsets into the canonical wrapped representative.

    When `space` is a finite [`Lattice`][qten.geometries.spatials.Lattice],
    positions related by the boundary condition are physically equivalent.
    This hook stores the canonical representative chosen by
    `space.boundaries.wrap`.
    """
    if isinstance(self.space, Lattice):
        wrapped = self.space.boundaries.wrap(self.rep)
        object.__setattr__(self, "rep", ImmutableDenseMatrix(wrapped))

to_vec

to_vec(T: type[_VecType] = sy.ImmutableMatrix) -> _VecType

Convert this offset from basis coordinates to Cartesian coordinates.

If rep stores coefficients in the primitive basis, this method returns the physical vector \(A r\), using space.basis as \(A\) and rep as \(r\). This is the quantity that should be used in Euclidean geometry and Fourier phases.

Returns:

Type Description
ImmutableDenseMatrix

The Cartesian coordinate vector corresponding to this offset.

Source code in src/qten/geometries/spatials.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def to_vec(self, T: Type[_VecType] = sy.ImmutableMatrix) -> _VecType:
    r"""
    Convert this offset from basis coordinates to Cartesian coordinates.

    If `rep` stores coefficients in the primitive basis, this method returns
    the physical vector \(A r\), using `space.basis` as \(A\) and `rep` as
    \(r\). This is the quantity that should be used in Euclidean geometry
    and Fourier phases.

    Returns
    -------
    ImmutableDenseMatrix
        The Cartesian coordinate vector corresponding to this offset.
    """
    vec = self.space.basis @ self.rep
    if T == ImmutableDenseMatrix:
        return vec
    elif T == np.ndarray:
        precision = get_precision_config()
        return cast(
            _VecType, np.array(vec.evalf(), dtype=precision.np_float).reshape(-1)
        )
    else:
        raise TypeError(
            f"Unsupported type {T} for to_vec. Supported types: np.ndarray, ImmutableDenseMatrix"
        )

distance

distance(r: Offset[Any]) -> float

Return the geometric distance to another offset.

If either offset is expressed on a lattice with periodic boundary conditions, the distance is computed using the nearest periodic image of the displacement in that lattice. Otherwise, the plain Euclidean norm of the displacement in the current affine space is returned.

Physically, for lattice points this is the minimum-image distance on the torus defined by the finite supercell, not the naive distance between two unwrapped representatives.

Source code in src/qten/geometries/spatials.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
def distance(self, r: "Offset") -> float:
    """
    Return the geometric distance to another offset.

    If either offset is expressed on a lattice with periodic boundary
    conditions, the distance is computed using the nearest periodic image
    of the displacement in that lattice. Otherwise, the plain Euclidean
    norm of the displacement in the current affine space is returned.

    Physically, for lattice points this is the minimum-image distance on the
    torus defined by the finite supercell, not the naive distance between
    two unwrapped representatives.
    """
    if isinstance(self.space, Lattice):
        delta = self - r.rebase(self.space)
        return self.space.boundaries.distance(delta.rep, self.space.basis)

    if isinstance(r.space, Lattice):
        delta = r - self.rebase(r.space)
        return r.space.boundaries.distance(delta.rep, r.space.basis)

    target_space = self.space
    delta_cart = _cartesian_delta(self, r, target_space)
    return float(np.linalg.norm(delta_cart.reshape(-1)))

__str__

__str__()

Return a symbolic display of the stored coordinates and ambient basis.

Column-vector coordinates are flattened for readability; higher-rank matrix representations keep their nested-list structure. The basis of space is always included so the printed coordinates remain unambiguous.

Source code in src/qten/geometries/spatials.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
def __str__(self):
    """
    Return a symbolic display of the stored coordinates and ambient basis.

    Column-vector coordinates are flattened for readability; higher-rank
    matrix representations keep their nested-list structure. The basis of
    `space` is always included so the printed coordinates remain
    unambiguous.
    """
    # If it's a column vector, flatten to 1D python list
    if self.rep.shape[1] == 1:
        vec = [str(sympify(v)) for v in list(self.rep)]
    else:
        vec = [[str(sympify(x)) for x in row] for row in self.rep.tolist()]
    basis = [[str(sympify(x)) for x in row] for row in self.space.basis.tolist()]
    return f"Offset({vec}{basis})"

__repr__

__repr__()

Return the same display string as __str__().

Source code in src/qten/geometries/spatials.py
1064
1065
1066
def __repr__(self):
    """Return the same display string as [`__str__()`][qten.geometries.spatials.Offset.__str__]."""
    return str(self)