Skip to content

qten.geometries

Package reference for qten.geometries.

geometries

Geometry and spatial-structure primitives used throughout QTen.

This package collects the concrete coordinate-space objects needed to describe real-space and reciprocal-space structure, boundary identification, basis changes, and region construction.

Core spaces and coordinates
  • AffineSpace Generic affine coordinate space.
  • Lattice Real-space lattice with basis, boundaries, and optional unit cell.
  • ReciprocalLattice Reciprocal-space dual lattice.
  • Offset Real-space coordinate/irrep attached to an affine space.
  • Momentum Reciprocal-space momentum coordinate.
Boundary handling
Basis transforms
Region and neighborhood helpers

Exported API

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.

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))

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.

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)\).

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 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)

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.

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.

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.

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 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)

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.

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))

fractional

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

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)

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.

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)

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)

BoundaryCondition

Bases: ABC

Abstract interface for identifying lattice-coordinate points modulo a finite boundary lattice.

A BoundaryCondition defines how integer or fractional lattice coordinates are quotient-ed to obtain a finite simulation region. In this package, boundary objects are attached to Lattice instances and provide the canonicalization and finite-cell logic used throughout the geometry, Fourier, and band-structure layers.

Conceptually, the boundary basis specifies a subgroup of lattice translations that should be treated as equivalent. The quotient \(\mathbb{Z}^d / B\mathbb{Z}^d\), where \(B\) is the boundary basis matrix stored in code as basis, determines:

  • which coordinate representative is considered canonical,
  • which finite set of unit cells should be enumerated,
  • how displacements are reduced when computing distances on a torus, and
  • how finite direct-space boundaries induce the corresponding reciprocal sampling grid.
Repository usage

BoundaryCondition is not only a storage object; it is part of the operational contract of several geometry types:

  • Lattice stores a boundary object in lattice.boundaries and uses representatives to enumerate the finite set of translated unit cells returned by Lattice.cartes.
  • Offset automatically applies wrap in Offset.__post_init__ whenever the ambient space is a lattice, so every stored lattice-site coordinate is normalized into the boundary's canonical fundamental domain.
  • Offset.distance delegates to distance to compute minimum-image distances whenever either operand lives on a bounded lattice.
  • ReciprocalLattice.cartes derives the discrete Brillouin-zone sampling from the direct-lattice boundary basis, so the boundary condition controls both real-space finite-size structure and reciprocal-space momentum enumeration.
  • BasisTransform and InverseBasisTransform transform the boundary basis alongside the lattice basis during supercell construction and unfolding. In the current repository implementation, these transforms explicitly support PeriodicBoundary.
Required semantics

Concrete subclasses are expected to satisfy the following behavioral contract:

  • basis returns a square matrix describing the translation generators that define the identification.
  • wrap(index) returns a canonical representative of the equivalence class containing index.
  • representatives() returns exactly one canonical representative for each equivalence class in the finite quotient induced by basis.
  • distance(delta, lattice_basis) measures the physical length of a displacement after applying the boundary's identification rule, typically by choosing the shortest equivalent image.
Notes

The abstract interface is intentionally generic, but the rest of the repository currently assumes a finite, full-rank identification lattice. In practice, the concrete implementation used across QTen is PeriodicBoundary, which interprets the boundary basis as periodic wrapping data and uses Smith normal form to enumerate quotient representatives.

basis abstractmethod property

basis: ImmutableDenseMatrix

Return the matrix that generates the boundary-identification lattice.

The columns of this square matrix specify the lattice translations that are declared equivalent to zero under the boundary condition. Equivalently, the boundary identifies coordinates modulo the subgroup \(B\mathbb{Z}^d\). In code, \(B\) is the returned basis matrix.

Repository code uses this matrix as the canonical description of the finite geometry:

  • Lattice.shape extracts the Smith-normal-form invariants of basis.
  • ReciprocalLattice.cartes derives the discrete reciprocal grid from the direct-space boundary basis.
  • Basis transforms update this matrix when constructing or inverting supercells.

Returns:

Type Description
ImmutableDenseMatrix

Square matrix describing the translation subgroup used by the boundary condition.

wrap abstractmethod

wrap(index: ImmutableDenseMatrix) -> ImmutableDenseMatrix

Map a lattice-coordinate vector to the canonical representative of its boundary-equivalence class.

Two coordinates are equivalent if they differ by a boundary translation generated by basis. This method chooses one distinguished representative of that class and returns it in the same coordinate system.

In the repository, this operation is performance-critical and semantically important because Offset applies it automatically when an offset is created on a bounded Lattice. As a result, many higher-level geometry objects rely on wrap to keep coordinates in a stable canonical form.

Parameters:

Name Type Description Default
index ImmutableDenseMatrix

Lattice-coordinate column vector to be reduced modulo the boundary identification.

required

Returns:

Type Description
ImmutableDenseMatrix

Canonical representative of the equivalence class containing index.

Source code in src/qten/geometries/boundary.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@abstractmethod
def wrap(self, index: ImmutableDenseMatrix) -> ImmutableDenseMatrix:
    """
    Map a lattice-coordinate vector to the canonical representative of its
    boundary-equivalence class.

    Two coordinates are equivalent if they differ by a boundary
    translation generated by [`basis`][qten.geometries.boundary.BoundaryCondition.basis].
    This method chooses one distinguished representative of that class and
    returns it in the same coordinate system.

    In the repository, this operation is performance-critical and
    semantically important because
    [`Offset`][qten.geometries.spatials.Offset] applies it automatically
    when an offset is created on a bounded
    [`Lattice`][qten.geometries.spatials.Lattice]. As a result, many
    higher-level geometry objects rely on `wrap` to keep coordinates in a
    stable canonical form.

    Parameters
    ----------
    index : ImmutableDenseMatrix
        Lattice-coordinate column vector to be reduced modulo the boundary
        identification.

    Returns
    -------
    ImmutableDenseMatrix
        Canonical representative of the equivalence class containing
        `index`.
    """
    pass

representatives abstractmethod

representatives() -> tuple[ImmutableDenseMatrix, ...]

Enumerate the finite canonical representative set induced by the boundary condition.

The returned tuple must contain exactly one representative from each equivalence class of the quotient lattice. This is the finite set of cell translations used to enumerate a bounded lattice.

Repository code depends on this method in several places:

  • Lattice.cartes builds all finite-lattice sites by combining these representatives with the unit-cell offsets.
  • ReciprocalLattice.cartes uses an analogous construction derived from the transposed boundary basis to enumerate sampled momenta.
  • Region and nearest-neighbor helpers iterate over these representatives when searching a finite torus.

Returns:

Type Description
tuple[ImmutableDenseMatrix, ...]

One canonical lattice-coordinate representative for each boundary equivalence class.

Source code in src/qten/geometries/boundary.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
@abstractmethod
def representatives(self) -> tuple[ImmutableDenseMatrix, ...]:
    """
    Enumerate the finite canonical representative set induced by the
    boundary condition.

    The returned tuple must contain exactly one representative from each
    equivalence class of the quotient lattice. This is the finite set of
    cell translations used to enumerate a bounded lattice.

    Repository code depends on this method in several places:

    - [`Lattice.cartes`][qten.geometries.spatials.Lattice.cartes] builds
      all finite-lattice sites by combining these representatives with the
      unit-cell offsets.
    - [`ReciprocalLattice.cartes`][qten.geometries.spatials.ReciprocalLattice.cartes]
      uses an analogous construction derived from the transposed boundary
      basis to enumerate sampled momenta.
    - Region and nearest-neighbor helpers iterate over these
      representatives when searching a finite torus.

    Returns
    -------
    tuple[ImmutableDenseMatrix, ...]
        One canonical lattice-coordinate representative for each boundary
        equivalence class.
    """
    pass

distance abstractmethod

distance(
    delta: ImmutableDenseMatrix,
    lattice_basis: ImmutableDenseMatrix,
) -> float

Measure the physical distance associated with a lattice displacement after boundary identification.

The input delta is expressed in lattice coordinates, not Cartesian coordinates. Implementations should account for the boundary condition when comparing equivalent images of that displacement, then use lattice_basis to convert the chosen image into physical space before computing its norm.

This method underlies Offset.distance for bounded lattices, so it defines the minimum-image or analogous metric used by higher-level geometry and region-selection routines.

Parameters:

Name Type Description Default
delta ImmutableDenseMatrix

Displacement vector in lattice coordinates.

required
lattice_basis ImmutableDenseMatrix

Direct-space basis matrix mapping lattice coordinates into Cartesian vectors.

required

Returns:

Type Description
float

Physical distance assigned to delta under the boundary rule.

Source code in src/qten/geometries/boundary.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
@abstractmethod
def distance(
    self, delta: ImmutableDenseMatrix, lattice_basis: ImmutableDenseMatrix
) -> float:
    """
    Measure the physical distance associated with a lattice displacement
    after boundary identification.

    The input `delta` is expressed in lattice coordinates, not Cartesian
    coordinates. Implementations should account for the boundary condition
    when comparing equivalent images of that displacement, then use
    `lattice_basis` to convert the chosen image into physical space before
    computing its norm.

    This method underlies
    [`Offset.distance`][qten.geometries.spatials.Offset.distance] for
    bounded lattices, so it defines the minimum-image or analogous metric
    used by higher-level geometry and region-selection routines.

    Parameters
    ----------
    delta : ImmutableDenseMatrix
        Displacement vector in lattice coordinates.
    lattice_basis : ImmutableDenseMatrix
        Direct-space basis matrix mapping lattice coordinates into
        Cartesian vectors.

    Returns
    -------
    float
        Physical distance assigned to `delta` under the boundary rule.
    """
    pass

PeriodicBoundary dataclass

PeriodicBoundary(_basis: ImmutableDenseMatrix)

Bases: BoundaryCondition

Periodic boundary: wraps indices using modulo arithmetic via Smith Normal Form.

Attributes:

Name Type Description
_basis ImmutableDenseMatrix

Square integer matrix whose columns generate the periodic identification lattice.

_U ImmutableDenseMatrix

Left unimodular factor from the Smith normal form of _basis.

_U_inv ImmutableDenseMatrix

Inverse of _U, cached for coordinate conversions during wrapping.

_periods tuple[int, ...]

Positive Smith invariants defining the finite quotient periods.

basis property

basis: ImmutableDenseMatrix

Return the periodic identification matrix stored by this boundary.

For a diagonal matrix, the diagonal entries are the periods along the primitive lattice directions. For a non-diagonal matrix, the columns span the translation lattice whose quotient defines the periodic torus. This matrix is the quantity propagated through lattice basis transforms and inspected by lattice-shape and reciprocal-grid code.

Returns:

Type Description
ImmutableDenseMatrix

Square matrix whose columns generate the periodic identification lattice.

__post_init__

__post_init__()

Validate the boundary basis and cache Smith-normal-form data.

PeriodicBoundary accepts a square integer matrix whose columns generate the periodic identification lattice. During initialization, the matrix is decomposed via Smith normal form so later calls to wrap and representatives can work with either diagonal or non-diagonal periodic cells using a canonical finite quotient description.

Raises:

Type Description
ValueError

If the supplied boundary basis is not square, or if its Smith invariants indicate a non-full-rank or sign-invalid periodic cell.

Source code in src/qten/geometries/boundary.py
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
def __post_init__(self):
    """
    Validate the boundary basis and cache Smith-normal-form data.

    `PeriodicBoundary` accepts a square integer matrix whose columns
    generate the periodic identification lattice. During initialization,
    the matrix is decomposed via Smith normal form so later calls to
    [`wrap`][qten.geometries.boundary.PeriodicBoundary.wrap] and
    [`representatives`][qten.geometries.boundary.PeriodicBoundary.representatives]
    can work with either diagonal or non-diagonal periodic cells using a
    canonical finite quotient description.

    Raises
    ------
    ValueError
        If the supplied boundary basis is not square, or if its Smith
        invariants indicate a non-full-rank or sign-invalid periodic cell.
    """
    if self._basis.rows != self._basis.cols:
        raise ValueError(f"boundary basis must be square, got {self._basis.shape}.")

    S, U, _ = smith_normal_decomp(self._basis, domain=sy.ZZ)
    S = ImmutableDenseMatrix(S)
    U = ImmutableDenseMatrix(U)
    periods = self._snf_periods(S)

    object.__setattr__(self, "_U", U)
    object.__setattr__(self, "_U_inv", ImmutableDenseMatrix(U.inv()))
    object.__setattr__(self, "_periods", periods)

wrap

wrap(index: ImmutableDenseMatrix) -> ImmutableDenseMatrix

Reduce a lattice coordinate to this periodic boundary's canonical fundamental-domain representative.

For diagonal boundary bases, this is ordinary component-wise modulo reduction. For general full-rank integer bases, the index is first expressed in boundary-lattice coordinates, each coefficient is reduced modulo one, and the result is mapped back into the original lattice coordinates. The returned vector therefore represents the same point on the torus as index, but in the canonical region used internally by the repository.

This is the normalization used by Offset.__post_init__, so any offset created on a Lattice with PeriodicBoundary is stored in this wrapped form.

Parameters:

Name Type Description Default
index ImmutableDenseMatrix

Lattice-coordinate column vector to wrap. The shape must be (dim, 1) where dim matches the boundary basis dimension.

required

Returns:

Type Description
ImmutableDenseMatrix

Canonical wrapped column vector representing the same boundary-equivalence class as index.

Raises:

Type Description
ValueError

If index does not have the expected column-vector shape.

Source code in src/qten/geometries/boundary.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def wrap(self, index: ImmutableDenseMatrix) -> ImmutableDenseMatrix:
    """
    Reduce a lattice coordinate to this periodic boundary's canonical
    fundamental-domain representative.

    For diagonal boundary bases, this is ordinary component-wise modulo
    reduction. For general full-rank integer bases, the index is first
    expressed in boundary-lattice coordinates, each coefficient is reduced
    modulo one, and the result is mapped back into the original lattice
    coordinates. The returned vector therefore represents the same point on
    the torus as `index`, but in the canonical region used internally by
    the repository.

    This is the normalization used by
    [`Offset.__post_init__`][qten.geometries.spatials.Offset.__post_init__],
    so any offset created on a
    [`Lattice`][qten.geometries.spatials.Lattice] with
    `PeriodicBoundary` is stored in this wrapped form.

    Parameters
    ----------
    index : ImmutableDenseMatrix
        Lattice-coordinate column vector to wrap. The shape must be
        `(dim, 1)` where `dim` matches the boundary basis dimension.

    Returns
    -------
    ImmutableDenseMatrix
        Canonical wrapped column vector representing the same
        boundary-equivalence class as `index`.

    Raises
    ------
    ValueError
        If `index` does not have the expected column-vector shape.
    """
    expected_shape = (self.basis.rows, 1)
    if index.shape != expected_shape:
        raise ValueError(
            f"index shape {index.shape} does not match expected {expected_shape}."
        )

    if self.basis.is_diagonal():
        wrapped_entries = [
            sy.Mod(index[i, 0], int(self.basis[i, i]))
            for i in range(self.basis.rows)
        ]
        return ImmutableDenseMatrix(self.basis.rows, 1, wrapped_entries)

    coordinates = ImmutableDenseMatrix(self.basis.inv() @ index)
    wrapped_entries = [
        coordinates[i, 0] - sy.floor(coordinates[i, 0])
        for i in range(self.basis.rows)
    ]
    wrapped_coords = ImmutableDenseMatrix(self.basis.rows, 1, wrapped_entries)

    # Avoid applying sy.Rational blindly as the wrapped result could contain
    # irrational expressions (e.g. sqrt). We rationalise Floats within expressions.
    def _rationalize(expr):
        if hasattr(expr, "is_Float") and expr.is_Float:
            return sy.nsimplify(expr)
        elif hasattr(expr, "args") and expr.args:
            return expr.func(*[_rationalize(arg) for arg in expr.args])
        return expr

    return ImmutableDenseMatrix(self.basis @ wrapped_coords).applyfunc(_rationalize)

representatives

representatives() -> tuple[ImmutableDenseMatrix, ...]

Enumerate the canonical finite set of lattice representatives for this periodic torus.

For diagonal periodicities, the representatives are the obvious integer box \(0 \le n_i < \mathrm{basis}_{ii}\). In code, the upper bound is basis[i, i]. For non-diagonal cells, the method enumerates the quotient described by the Smith normal form and then maps those elements back into canonical wrapped lattice coordinates.

The size of the returned tuple is the index of the boundary lattice in the ambient lattice, which is the number of translated unit cells in the finite periodic system. This tuple drives finite-lattice site enumeration in Lattice.cartes.

Returns:

Type Description
tuple[ImmutableDenseMatrix, ...]

Tuple of wrapped lattice-coordinate representatives spanning the finite quotient \(\mathbb{Z}^d / B\mathbb{Z}^d\), where \(B\) is the basis matrix.

Source code in src/qten/geometries/boundary.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def representatives(self) -> tuple[ImmutableDenseMatrix, ...]:
    r"""
    Enumerate the canonical finite set of lattice representatives for this
    periodic torus.

    For diagonal periodicities, the representatives are the obvious
    integer box \(0 \le n_i < \mathrm{basis}_{ii}\). In code, the upper
    bound is `basis[i, i]`.
    For non-diagonal cells, the method enumerates the quotient described by
    the Smith normal form and then maps those elements back into canonical
    wrapped lattice coordinates.

    The size of the returned tuple is the index of the boundary lattice in
    the ambient lattice, which is the number of translated unit cells in
    the finite periodic system. This tuple drives finite-lattice site
    enumeration in
    [`Lattice.cartes`][qten.geometries.spatials.Lattice.cartes].

    Returns
    -------
    tuple[ImmutableDenseMatrix, ...]
        Tuple of wrapped lattice-coordinate representatives spanning the
        finite quotient \(\mathbb{Z}^d / B\mathbb{Z}^d\), where \(B\) is
        the `basis` matrix.
    """
    if self.basis.is_diagonal():
        elements = product(
            *(range(int(self.basis[i, i])) for i in range(self.basis.rows))
        )
        return tuple(
            ImmutableDenseMatrix(self.basis.rows, 1, el) for el in elements
        )

    elements = product(*(range(period) for period in self._periods))
    # Ensure representatives are within the fundamental domain by wrapping them
    return tuple(
        self.wrap(
            ImmutableDenseMatrix(
                self._U_inv @ ImmutableDenseMatrix(self.basis.rows, 1, el)
            )
        )
        for el in elements
    )

distance

distance(
    delta: ImmutableDenseMatrix,
    lattice_basis: ImmutableDenseMatrix,
) -> float

Compute the minimum-image distance associated with a periodic lattice displacement.

The displacement delta is given in lattice coordinates. This method converts it to Cartesian space using lattice_basis, considers nearby periodic images obtained by adding boundary translations, and returns the Euclidean norm of the shortest candidate. That is the metric used throughout the repository for distances on lattices with periodic boundaries.

The current implementation evaluates the nearest images generated by shifts with coefficients in {-1, 0, 1} along the boundary generators, which is sufficient for the fundamental displacements produced by the surrounding geometry code.

Parameters:

Name Type Description Default
delta ImmutableDenseMatrix

Lattice-coordinate displacement column vector with shape (dim, 1).

required
lattice_basis ImmutableDenseMatrix

Real-space lattice basis used to convert lattice coordinates into Cartesian displacements.

required

Returns:

Type Description
float

Euclidean norm of the shortest boundary-equivalent Cartesian displacement.

Raises:

Type Description
ValueError

If delta does not have the expected column-vector shape.

Source code in src/qten/geometries/boundary.py
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def distance(
    self, delta: ImmutableDenseMatrix, lattice_basis: ImmutableDenseMatrix
) -> float:
    """
    Compute the minimum-image distance associated with a periodic lattice
    displacement.

    The displacement `delta` is given in lattice coordinates. This method
    converts it to Cartesian space using `lattice_basis`, considers nearby
    periodic images obtained by adding boundary translations, and returns
    the Euclidean norm of the shortest candidate. That is the metric used
    throughout the repository for distances on lattices with periodic
    boundaries.

    The current implementation evaluates the nearest images generated by
    shifts with coefficients in `{-1, 0, 1}` along the boundary
    generators, which is sufficient for the fundamental displacements
    produced by the surrounding geometry code.

    Parameters
    ----------
    delta : ImmutableDenseMatrix
        Lattice-coordinate displacement column vector with shape
        `(dim, 1)`.
    lattice_basis : ImmutableDenseMatrix
        Real-space lattice basis used to convert lattice coordinates into
        Cartesian displacements.

    Returns
    -------
    float
        Euclidean norm of the shortest boundary-equivalent Cartesian
        displacement.

    Raises
    ------
    ValueError
        If `delta` does not have the expected column-vector shape.
    """
    expected_shape = (self.basis.rows, 1)
    if delta.shape != expected_shape:
        raise ValueError(
            f"delta shape {delta.shape} does not match expected {expected_shape}."
        )
    coeffs = np.array(
        tuple(product((-1, 0, 1), repeat=self.basis.rows)),
        dtype=get_precision_config().np_float,
    )
    physical_boundaries = _matrix_to_ndarray(lattice_basis) @ _matrix_to_ndarray(
        self.basis
    )
    delta_cart = _matrix_to_ndarray(lattice_basis) @ _matrix_to_ndarray(delta)
    candidate_displacements = (
        delta_cart.reshape(1, -1) + coeffs @ physical_boundaries.T
    )
    return float(np.linalg.norm(candidate_displacements, axis=1).min())

__str__

__str__()
Source code in src/qten/geometries/boundary.py
534
535
536
def __str__(self):
    data = [[str(sy.sympify(x)) for x in row] for row in self._basis.tolist()]
    return f"PeriodicBoundary(basis={data})"

__repr__

__repr__()
Source code in src/qten/geometries/boundary.py
538
539
def __repr__(self):
    return str(self)

BasisTransform dataclass

BasisTransform(M: ImmutableDenseMatrix)

Bases: AbstractBasisTransform

Forward-view basis transform acting with matrix M.

This is the "build a supercell / change to a coarser Lattice basis" convention used throughout the geometry and band-folding code. For a direct-lattice basis matrix A, the transformed basis is

\(A' = A M\).

The same physical point is then re-expressed in the new basis rather than moved in space. In other words, BasisTransform changes coordinates by changing the basis objects attached to the geometry.

Supported Actions

BasisTransform is registered on the following object types:

The registrations are coordinated so that Lattice and ReciprocalLattice objects remain dual to each other.

Mathematical Action

Let A denote a Lattice-basis matrix and \(B = 2\pi A^{-\mathsf{T}}\) the corresponding ReciprocalLattice-basis matrix.

On AffineSpace : \(A' = A M\).

On Lattice : the lattice basis becomes \(A M\), while periodic boundary generators are re-expressed as \(M^{-1}G\) so that the same physical torus is described in the transformed basis. For integer \(M\) with positive determinant, this typically produces a supercell with \(\lvert\det M\rvert\) sites in the transformed unit cell.

On ReciprocalLattice : because reciprocal bases transform contragrediently, \(B' = B M^{-\mathsf{T}}\).

On Offset : an offset with Lattice-fractional coordinates \(r\) is rebased into the transformed space, giving \(r' = M^{-1} r\).

On Momentum : a momentum with ReciprocalLattice- fractional coordinates \(\kappa\) are rebased into the transformed reciprocal space, giving \(\kappa' = M^{\mathsf{T}}\kappa\).

In implementation terms, these rules correspond to matrix products such as A @ M, B @ M.inv().T, M.inv() @ r, and M.T @ kappa.

Repository Usage

In this repository, BasisTransform is used in two main ways:

  • Geometry-level supercell construction via BasisTransform(lat), which enlarges the Lattice unit cell and propagates the corresponding boundary and ReciprocalLattice changes.
  • Band folding via bandfold, where the transform maps a primitive Brillouin zone onto the Brillouin zone of the transformed lattice and enlarges the Hilbert-space legs to match the folded unit cell.
Notes

This class does not store \(M^{-1}\). It stores M and applies the forward convention consistently across dispatches. The opposite convention is represented by InverseBasisTransform.

register classmethod

register(obj_type: type)

Register a function defining the action of the Functional on a specific object type.

This method returns a decorator. The decorated function should accept the functional instance as its first argument and an object of obj_type as its second argument. Any keyword arguments passed to invoke() are forwarded to the decorated function.

Dispatch is resolved at call time via MRO, so only the exact (obj_type, cls) key is stored here. Resolution later searches both:

  • the MRO of the runtime object type,
  • the MRO of the runtime functional type.

This means registrations on a functional superclass are inherited by subclass functionals unless a more specific registration overrides them.

Parameters:

Name Type Description Default
obj_type type

The type of object the function applies to.

required

Returns:

Type Description
Callable

A decorator that registers the function for the specified object type.

Examples:

@MyFunctional.register(MyObject)
def _(functional: MyFunctional, obj: MyObject) -> MyObject:
    ...
Source code in src/qten/abstracts.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
@classmethod
def register(cls, obj_type: type):
    """
    Register a function defining the action of the [`Functional`][qten.abstracts.Functional] on a specific object type.

    This method returns a decorator. The decorated function should accept
    the functional instance as its first argument and an object of
    `obj_type` as its second argument. Any keyword arguments passed to
    [`invoke()`][qten.abstracts.Functional.invoke] are forwarded to the
    decorated function.

    Dispatch is resolved at call time via MRO, so only the exact
    `(obj_type, cls)` key is stored here. Resolution later searches both:

    - the MRO of the runtime object type,
    - the MRO of the runtime functional type.

    This means registrations on a functional superclass are inherited by
    subclass functionals unless a more specific registration overrides them.

    Parameters
    ----------
    obj_type : type
        The type of object the function applies to.

    Returns
    -------
    Callable
        A decorator that registers the function for the specified object type.

    Examples
    --------
    ```python
    @MyFunctional.register(MyObject)
    def _(functional: MyFunctional, obj: MyObject) -> MyObject:
        ...
    ```
    """

    def decorator(func: Callable):
        cls._registered_methods[(obj_type, cls)] = func
        cls._invalidate_resolved_methods(obj_type)
        return func

    return decorator

get_applicable_types staticmethod

get_applicable_types() -> tuple[type, ...]

Get all object types that can be applied by this Functional.

Parameters:

Name Type Description Default
cls Type[Functional]

Functional class whose direct registrations should be inspected.

required

Returns:

Type Description
Tuple[Type, ...]

A tuple of all registered object types that this Functional can handle.

Source code in src/qten/abstracts.py
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
@staticmethod
def get_applicable_types(cls) -> Tuple[Type, ...]:
    """
    Get all object types that can be applied by this [`Functional`][qten.abstracts.Functional].

    Parameters
    ----------
    cls : Type[Functional]
        Functional class whose direct registrations should be inspected.

    Returns
    -------
    Tuple[Type, ...]
        A tuple of all registered object types that this [`Functional`][qten.abstracts.Functional] can handle.
    """
    types = set()
    for obj_type, functional_type in cls._registered_methods.keys():
        if functional_type is cls:
            types.add(obj_type)
    return tuple(types)

allows

allows(obj: Any) -> bool

Check if this Functional can be applied on the given object.

Parameters:

Name Type Description Default
obj Any

The object to check for applicability.

required

Returns:

Type Description
bool

True if this Functional can be applied on the object, False otherwise.

Notes

Applicability is checked using the same inherited dispatch rules as invoke(): both the object's MRO and the functional-class MRO are searched.

Source code in src/qten/abstracts.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def allows(self, obj: Any) -> bool:
    """
    Check if this [`Functional`][qten.abstracts.Functional] can be applied on the given object.

    Parameters
    ----------
    obj : Any
        The object to check for applicability.

    Returns
    -------
    bool
        True if this [`Functional`][qten.abstracts.Functional] can be applied on the object, False otherwise.

    Notes
    -----
    Applicability is checked using the same inherited dispatch rules as
    [`invoke()`][qten.abstracts.Functional.invoke]: both the object's MRO
    and the functional-class MRO are searched.
    """
    return self._resolve_method(type(obj), type(self)) is not None

invoke

invoke(obj: Any, **kwargs) -> Any

Apply this functional to obj using registered multimethod dispatch.

Parameters:

Name Type Description Default
obj Any

Runtime object to dispatch on.

required
**kwargs Any

Additional keyword arguments forwarded to the resolved implementation.

{}

Returns:

Type Description
Any

Result produced by the resolved registered method.

Raises:

Type Description
NotImplementedError

If no registration exists for the runtime pair (type(obj), type(self)) after MRO fallback.

Source code in src/qten/abstracts.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def invoke(self, obj: Any, **kwargs) -> Any:
    """
    Apply this functional to `obj` using registered multimethod dispatch.

    Parameters
    ----------
    obj : Any
        Runtime object to dispatch on.
    **kwargs : Any
        Additional keyword arguments forwarded to the resolved
        implementation.

    Returns
    -------
    Any
        Result produced by the resolved registered method.

    Raises
    ------
    NotImplementedError
        If no registration exists for the runtime pair
        `(type(obj), type(self))` after MRO fallback.
    """
    functional_class = type(self)
    obj_class = type(obj)
    method = self._resolve_method(obj_class, functional_class)

    if method is None:
        raise NotImplementedError(
            f"No function registered for {obj_class.__name__} "
            f"with {functional_class.__name__}"
        )

    return method(self, obj, **kwargs)

__call__

__call__(obj: Any, **kwargs) -> Any

Apply this functional to obj.

This is a thin wrapper around invoke().

Parameters:

Name Type Description Default
obj Any

Runtime object to dispatch on.

required
**kwargs Any

Additional keyword arguments forwarded to the resolved implementation.

{}

Returns:

Type Description
Any

Result produced by the resolved registered method.

Raises:

Type Description
NotImplementedError

If no registration exists for the runtime pair after MRO fallback.

See Also

invoke(obj, **kwargs) Full dispatch method used by this call wrapper.

Source code in src/qten/abstracts.py
648
649
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
def __call__(self, obj: Any, **kwargs) -> Any:
    """
    Apply this functional to `obj`.

    This is a thin wrapper around [`invoke()`][qten.abstracts.Functional.invoke].

    Parameters
    ----------
    obj : Any
        Runtime object to dispatch on.
    **kwargs : Any
        Additional keyword arguments forwarded to the resolved
        implementation.

    Returns
    -------
    Any
        Result produced by the resolved registered method.

    Raises
    ------
    NotImplementedError
        If no registration exists for the runtime pair after MRO fallback.

    See Also
    --------
    [`invoke(obj, **kwargs)`][qten.abstracts.Functional.invoke]
        Full dispatch method used by this call wrapper.
    """
    return self.invoke(obj, **kwargs)

inv

inv() -> InverseBasisTransform

Return the inverse-view transform associated with the same matrix M.

This switches from the forward convention \(A \mapsto A M\) to the inverse convention \(A \mapsto A M^{-1}\) without changing the stored parameter M. The returned object therefore represents the basis-change view that reverses the action of this BasisTransform on supported geometry objects.

Returns:

Type Description
InverseBasisTransform

InverseBasisTransform carrying the same matrix M.

Notes

This method does not replace M by \(M^{-1}\) in the dataclass field. Instead, it returns the companion transform class whose dispatch rules interpret the same matrix using the opposite basis-change convention.

For example, if this transform maps a Lattice basis as \(A \mapsto A M\), then the returned transform maps it as \(A \mapsto A M^{-1}\). Likewise, applying self.inv().inv() returns a new BasisTransform with the original matrix M.

Source code in src/qten/geometries/basis_transform.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def inv(self) -> "InverseBasisTransform":
    r"""
    Return the inverse-view transform associated with the same matrix `M`.

    This switches from the forward convention
    \(A \mapsto A M\) to the inverse convention
    \(A \mapsto A M^{-1}\) without changing the stored parameter `M`.
    The returned object therefore represents the basis-change view that
    reverses the action of this [`BasisTransform`][qten.geometries.basis_transform.BasisTransform]
    on supported geometry objects.

    Returns
    -------
    InverseBasisTransform
        [`InverseBasisTransform`][qten.geometries.basis_transform.InverseBasisTransform]
        carrying the same matrix `M`.

    Notes
    -----
    This method does not replace `M` by \(M^{-1}\) in the dataclass field.
    Instead, it returns the companion transform class whose dispatch rules
    interpret the same matrix using the opposite basis-change convention.

    For example, if this transform maps a
    [`Lattice`][qten.geometries.spatials.Lattice] basis as
    \(A \mapsto A M\), then the returned transform maps it as
    \(A \mapsto A M^{-1}\). Likewise,
    applying `self.inv().inv()` returns a new
    [`BasisTransform`][qten.geometries.basis_transform.BasisTransform]
    with the original matrix `M`.
    """
    return InverseBasisTransform(self.M)

InverseBasisTransform dataclass

InverseBasisTransform(M: ImmutableDenseMatrix)

Bases: AbstractBasisTransform

Inverse-view basis transform paired with BasisTransform.

InverseBasisTransform(M) uses the same stored matrix as BasisTransform, but it interprets that matrix as the inverse change of basis. For a Lattice-basis matrix A, the transformed basis is

\(A' = A M^{-1}\).

This is the "undo the supercell / recover the primitive description" convention used when unfolding folded lattices, offsets, and band structures back into their primitive representation.

Supported Actions

InverseBasisTransform directly registers specialized implementations for:

Through the shared AbstractBasisTransform registrations, it also acts on:

Mathematical Action

Let A denote a Lattice-basis matrix and \(B = 2\pi A^{-\mathsf{T}}\) the corresponding ReciprocalLattice-basis matrix.

On AffineSpace : \(A' = A M^{-1}\).

On Lattice : the lattice basis becomes \(A M^{-1}\), while periodic boundary generators are mapped as \(G \mapsto M G\). For lattices produced by BasisTransform, this reconstructs the primitive-cell description and merges folded unit-cell labels back onto primitive labels when possible.

On ReciprocalLattice : duality gives \(B' = B M^{\mathsf{T}}\).

On Offset : Lattice-fractional coordinates are rebased by \(r' = M r\).

On Momentum : ReciprocalLattice- fractional coordinates are rebased by \(\kappa' = M^{-\mathsf{T}}\kappa\).

In implementation terms, these rules correspond to matrix products such as A @ M.inv(), B @ M.T, M @ r, and M.inv().T @ kappa.

Repository Usage

In this repository, InverseBasisTransform is primarily used for:

  • Recovering primitive lattices from supercells created by BasisTransform.
  • Band unfolding via bandunfold, which requires an InverseBasisTransform explicitly so the direction of the operation is unambiguous at runtime.
Notes

InverseBasisTransform(M).inv() returns BasisTransform(M). The two classes therefore share the same matrix parameter while differing only in which side of the basis-change convention they represent.

register classmethod

register(obj_type: type)

Register a function defining the action of the Functional on a specific object type.

This method returns a decorator. The decorated function should accept the functional instance as its first argument and an object of obj_type as its second argument. Any keyword arguments passed to invoke() are forwarded to the decorated function.

Dispatch is resolved at call time via MRO, so only the exact (obj_type, cls) key is stored here. Resolution later searches both:

  • the MRO of the runtime object type,
  • the MRO of the runtime functional type.

This means registrations on a functional superclass are inherited by subclass functionals unless a more specific registration overrides them.

Parameters:

Name Type Description Default
obj_type type

The type of object the function applies to.

required

Returns:

Type Description
Callable

A decorator that registers the function for the specified object type.

Examples:

@MyFunctional.register(MyObject)
def _(functional: MyFunctional, obj: MyObject) -> MyObject:
    ...
Source code in src/qten/abstracts.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
@classmethod
def register(cls, obj_type: type):
    """
    Register a function defining the action of the [`Functional`][qten.abstracts.Functional] on a specific object type.

    This method returns a decorator. The decorated function should accept
    the functional instance as its first argument and an object of
    `obj_type` as its second argument. Any keyword arguments passed to
    [`invoke()`][qten.abstracts.Functional.invoke] are forwarded to the
    decorated function.

    Dispatch is resolved at call time via MRO, so only the exact
    `(obj_type, cls)` key is stored here. Resolution later searches both:

    - the MRO of the runtime object type,
    - the MRO of the runtime functional type.

    This means registrations on a functional superclass are inherited by
    subclass functionals unless a more specific registration overrides them.

    Parameters
    ----------
    obj_type : type
        The type of object the function applies to.

    Returns
    -------
    Callable
        A decorator that registers the function for the specified object type.

    Examples
    --------
    ```python
    @MyFunctional.register(MyObject)
    def _(functional: MyFunctional, obj: MyObject) -> MyObject:
        ...
    ```
    """

    def decorator(func: Callable):
        cls._registered_methods[(obj_type, cls)] = func
        cls._invalidate_resolved_methods(obj_type)
        return func

    return decorator

get_applicable_types staticmethod

get_applicable_types() -> tuple[type, ...]

Get all object types that can be applied by this Functional.

Parameters:

Name Type Description Default
cls Type[Functional]

Functional class whose direct registrations should be inspected.

required

Returns:

Type Description
Tuple[Type, ...]

A tuple of all registered object types that this Functional can handle.

Source code in src/qten/abstracts.py
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
@staticmethod
def get_applicable_types(cls) -> Tuple[Type, ...]:
    """
    Get all object types that can be applied by this [`Functional`][qten.abstracts.Functional].

    Parameters
    ----------
    cls : Type[Functional]
        Functional class whose direct registrations should be inspected.

    Returns
    -------
    Tuple[Type, ...]
        A tuple of all registered object types that this [`Functional`][qten.abstracts.Functional] can handle.
    """
    types = set()
    for obj_type, functional_type in cls._registered_methods.keys():
        if functional_type is cls:
            types.add(obj_type)
    return tuple(types)

allows

allows(obj: Any) -> bool

Check if this Functional can be applied on the given object.

Parameters:

Name Type Description Default
obj Any

The object to check for applicability.

required

Returns:

Type Description
bool

True if this Functional can be applied on the object, False otherwise.

Notes

Applicability is checked using the same inherited dispatch rules as invoke(): both the object's MRO and the functional-class MRO are searched.

Source code in src/qten/abstracts.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def allows(self, obj: Any) -> bool:
    """
    Check if this [`Functional`][qten.abstracts.Functional] can be applied on the given object.

    Parameters
    ----------
    obj : Any
        The object to check for applicability.

    Returns
    -------
    bool
        True if this [`Functional`][qten.abstracts.Functional] can be applied on the object, False otherwise.

    Notes
    -----
    Applicability is checked using the same inherited dispatch rules as
    [`invoke()`][qten.abstracts.Functional.invoke]: both the object's MRO
    and the functional-class MRO are searched.
    """
    return self._resolve_method(type(obj), type(self)) is not None

invoke

invoke(obj: Any, **kwargs) -> Any

Apply this functional to obj using registered multimethod dispatch.

Parameters:

Name Type Description Default
obj Any

Runtime object to dispatch on.

required
**kwargs Any

Additional keyword arguments forwarded to the resolved implementation.

{}

Returns:

Type Description
Any

Result produced by the resolved registered method.

Raises:

Type Description
NotImplementedError

If no registration exists for the runtime pair (type(obj), type(self)) after MRO fallback.

Source code in src/qten/abstracts.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def invoke(self, obj: Any, **kwargs) -> Any:
    """
    Apply this functional to `obj` using registered multimethod dispatch.

    Parameters
    ----------
    obj : Any
        Runtime object to dispatch on.
    **kwargs : Any
        Additional keyword arguments forwarded to the resolved
        implementation.

    Returns
    -------
    Any
        Result produced by the resolved registered method.

    Raises
    ------
    NotImplementedError
        If no registration exists for the runtime pair
        `(type(obj), type(self))` after MRO fallback.
    """
    functional_class = type(self)
    obj_class = type(obj)
    method = self._resolve_method(obj_class, functional_class)

    if method is None:
        raise NotImplementedError(
            f"No function registered for {obj_class.__name__} "
            f"with {functional_class.__name__}"
        )

    return method(self, obj, **kwargs)

__call__

__call__(obj: Any, **kwargs) -> Any

Apply this functional to obj.

This is a thin wrapper around invoke().

Parameters:

Name Type Description Default
obj Any

Runtime object to dispatch on.

required
**kwargs Any

Additional keyword arguments forwarded to the resolved implementation.

{}

Returns:

Type Description
Any

Result produced by the resolved registered method.

Raises:

Type Description
NotImplementedError

If no registration exists for the runtime pair after MRO fallback.

See Also

invoke(obj, **kwargs) Full dispatch method used by this call wrapper.

Source code in src/qten/abstracts.py
648
649
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
def __call__(self, obj: Any, **kwargs) -> Any:
    """
    Apply this functional to `obj`.

    This is a thin wrapper around [`invoke()`][qten.abstracts.Functional.invoke].

    Parameters
    ----------
    obj : Any
        Runtime object to dispatch on.
    **kwargs : Any
        Additional keyword arguments forwarded to the resolved
        implementation.

    Returns
    -------
    Any
        Result produced by the resolved registered method.

    Raises
    ------
    NotImplementedError
        If no registration exists for the runtime pair after MRO fallback.

    See Also
    --------
    [`invoke(obj, **kwargs)`][qten.abstracts.Functional.invoke]
        Full dispatch method used by this call wrapper.
    """
    return self.invoke(obj, **kwargs)

inv

inv() -> BasisTransform

Return the forward-view transform associated with the same matrix M.

This switches from the inverse convention \(A \mapsto A M^{-1}\) back to the forward convention \(A \mapsto A M\) without changing the stored parameter M. The returned object is the companion BasisTransform used for supercell construction and band folding.

Returns:

Type Description
BasisTransform

BasisTransform carrying the same matrix M.

Notes

This method does not explicitly invert the stored matrix field. Instead, it returns the paired transform class whose registrations interpret M in the forward basis-change convention.

For example, if this transform maps a Lattice basis as \(A \mapsto A M^{-1}\), then the returned transform maps it as \(A \mapsto A M\). Likewise, applying self.inv().inv() returns a new InverseBasisTransform with the original matrix M.

Source code in src/qten/geometries/basis_transform.py
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
def inv(self) -> BasisTransform:
    r"""
    Return the forward-view transform associated with the same matrix `M`.

    This switches from the inverse convention
    \(A \mapsto A M^{-1}\) back to the forward convention
    \(A \mapsto A M\) without changing the stored parameter `M`.
    The returned object is the companion
    [`BasisTransform`][qten.geometries.basis_transform.BasisTransform]
    used for supercell construction and band folding.

    Returns
    -------
    BasisTransform
        [`BasisTransform`][qten.geometries.basis_transform.BasisTransform]
        carrying the same matrix `M`.

    Notes
    -----
    This method does not explicitly invert the stored matrix field.
    Instead, it returns the paired transform class whose registrations
    interpret `M` in the forward basis-change convention.

    For example, if this transform maps a
    [`Lattice`][qten.geometries.spatials.Lattice] basis as
    \(A \mapsto A M^{-1}\), then the returned transform maps it as
    \(A \mapsto A M\). Likewise,
    applying `self.inv().inv()` returns a new
    [`InverseBasisTransform`][qten.geometries.basis_transform.InverseBasisTransform]
    with the original matrix `M`.
    """
    return BasisTransform(self.M)

center_of_region

center_of_region(
    region: tuple[OffsetType, ...],
) -> OffsetType

Return the arithmetic center of a non-empty region of offsets or momenta.

Parameters:

Name Type Description Default
region tuple[Offset, ...] | tuple[Momentum, ...]

Non-empty tuple of spatial points. All entries must share the same concrete type and affine space.

required

Returns:

Type Description
Offset | Momentum

Arithmetic mean of the region coordinates, returned as the same type as the input entries.

Raises:

Type Description
ValueError

If region is empty.

TypeError

If region entries do not all share the same concrete type and space.

Source code in src/qten/geometries/ops.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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
450
451
452
453
454
455
def center_of_region(region: tuple[OffsetType, ...]) -> OffsetType:
    """
    Return the arithmetic center of a non-empty region of offsets or momenta.

    Parameters
    ----------
    region : tuple[Offset, ...] | tuple[Momentum, ...]
        Non-empty tuple of spatial points. All entries must share the same
        concrete type and affine space.

    Returns
    -------
    Offset | Momentum
        Arithmetic mean of the region coordinates, returned as the same type as
        the input entries.

    Raises
    ------
    ValueError
        If `region` is empty.
    TypeError
        If region entries do not all share the same concrete type and space.
    """
    if len(region) == 0:
        raise ValueError("region must be non-empty.")

    first = region[0]
    point_type = type(first)

    for point in region[1:]:
        if type(point) is not point_type:
            raise TypeError("region entries must all have the same concrete type.")
        if point.space != first.space:
            raise TypeError("region entries must all belong to the same space.")

    if isinstance(first.space, Lattice):
        boundary_basis = np.array(first.space.boundaries.basis.evalf(), dtype=float)
        wrapped = np.stack(
            [
                np.array(
                    (first.space.boundaries.basis.inv() @ point.rep).evalf(),
                    dtype=float,
                ).reshape(-1)
                for point in region
            ]
        )
        reference = wrapped[0]
        unwrapped = wrapped.copy()
        for i in range(1, len(region)):
            delta = wrapped[i] - reference
            unwrapped[i] = wrapped[i] - np.round(delta)

        mean_boundary = unwrapped.mean(axis=0) % 1.0
        mean_rep_np = boundary_basis @ mean_boundary
        mean_rep = ImmutableDenseMatrix([sy.nsimplify(x) for x in mean_rep_np])
        return point_type(rep=mean_rep, space=first.space)

    if isinstance(first.space, ReciprocalLattice):
        wrapped = np.stack(
            [np.array(point.rep.evalf(), dtype=float).reshape(-1) for point in region]
        )
        reference = wrapped[0]
        unwrapped = wrapped.copy()
        for i in range(1, len(region)):
            delta = wrapped[i] - reference
            unwrapped[i] = wrapped[i] - np.round(delta)

        mean_rep_np = unwrapped.mean(axis=0) % 1.0
        mean_rep = ImmutableDenseMatrix([sy.nsimplify(x) for x in mean_rep_np])
        return point_type(rep=mean_rep, space=first.space)

    total = first.rep
    for point in region[1:]:
        total += point.rep

    return point_type(rep=ImmutableDenseMatrix(total / len(region)), space=first.space)

get_strip_region_2d

get_strip_region_2d(
    direction: Offset[Lattice],
    *,
    length_step: int,
    width_step: int,
    trim_step: int = 0,
    side: Literal["lhs", "rhs"] = "rhs",
    origin: Offset[AffineSpace]
    | Offset[Lattice]
    | None = None,
) -> tuple[Offset[Lattice], ...]

Return a 2D rectangular strip region in primitive-strip lattice coordinates.

This helper is defined only for 2D lattices.

Let r0 be the supplied origin (or the lattice origin when omitted). Let \((d_x, d_y)\) be the supplied direction coordinates. Let \(p = (p_x, p_y)\) be the associated primitive integer direction, and let \(n = (-p_y, p_x)\) be the primitive integer normal. side="lhs" grows toward positive \(n\) and side="rhs" grows toward negative \(n\).

A lattice site belongs to the strip when some periodic image of that site satisfies both of the following:

  • Longitudinal bound: \(\mathrm{trim\_step}(d_x^2 + d_y^2) \le d_x(r_x-r_{0x}) + d_y(r_y-r_{0y}) \le (\mathrm{length\_step}-1)(d_x^2+d_y^2)\).
  • Transverse bound: \(0 \le s[-p_y(r_x-r_{0x}) + p_x(r_y-r_{0y})] \le \mathrm{width\_step}-1\).

where \(s = 1\) for "lhs" and \(s = -1\) for "rhs".

For integer directions, \((d_x, d_y) = (p_x, p_y)\). For rational directions, longitudinal shell spacing is computed from the supplied direction (dx, dy), while transverse shelling is computed from the primitive integer direction p.

width_step counts the transverse shell thickness including the main axis row. trim_step is a tail trimmer only: it advances the strip start along the longitudinal axis without affecting the transverse width.

Parameters:

Name Type Description Default
direction Offset[Lattice]

Non-zero lattice translation on a 2D lattice whose primitive direction defines the strip axis.

required
length_step int

Number of strip shells from the origin along the primitive direction.

required
width_step int

Number of transverse shell rows including the main axis row.

required
trim_step int

Number of longitudinal shells trimmed from the tail near the origin.

0
side Literal['lhs', 'rhs']

Side on which transverse width shells are accumulated relative to the strip direction. "lhs" uses the positive lattice normal and "rhs" uses the negative lattice normal.

'rhs'
origin Offset[AffineSpace] | Offset[Lattice] | None

Anchor point for the strip coordinates. If omitted, the zero offset in the lattice space is used. When provided, it is rebased into the lattice before evaluating strip membership.

None

Returns:

Type Description
tuple[Offset[Lattice], ...]

Deduplicated lattice sites in the strip, ordered by the lattice-site ordering.

Raises:

Type Description
ValueError

If the direction is invalid, the lattice is not 2D, or any step count is out of range.

Source code in src/qten/geometries/ops.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
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
374
375
376
377
def get_strip_region_2d(
    direction: Offset[Lattice],
    *,
    length_step: int,
    width_step: int,
    trim_step: int = 0,
    side: Literal["lhs", "rhs"] = "rhs",
    origin: Offset[AffineSpace] | Offset[Lattice] | None = None,
) -> tuple[Offset[Lattice], ...]:
    r"""
    Return a 2D rectangular strip region in primitive-strip lattice coordinates.

    This helper is defined only for 2D lattices.

    Let `r0` be the supplied [`origin`][qten.geometries.spatials.AffineSpace.origin] (or the lattice origin when omitted).
    Let \((d_x, d_y)\) be the supplied direction coordinates. Let
    \(p = (p_x, p_y)\) be the associated primitive integer direction, and let
    \(n = (-p_y, p_x)\) be the primitive integer normal. `side="lhs"` grows
    toward positive \(n\) and `side="rhs"` grows toward negative \(n\).

    A lattice site belongs to the strip when some periodic image of that site
    satisfies both of the following:

    - Longitudinal bound:
      \(\mathrm{trim\_step}(d_x^2 + d_y^2)
      \le d_x(r_x-r_{0x}) + d_y(r_y-r_{0y})
      \le (\mathrm{length\_step}-1)(d_x^2+d_y^2)\).
    - Transverse bound:
      \(0 \le s[-p_y(r_x-r_{0x}) + p_x(r_y-r_{0y})]
      \le \mathrm{width\_step}-1\).

    where \(s = 1\) for `"lhs"` and \(s = -1\) for `"rhs"`.

    For integer directions, \((d_x, d_y) = (p_x, p_y)\). For rational directions,
    longitudinal shell spacing is computed from the supplied direction
    `(dx, dy)`, while transverse shelling is computed from the primitive
    integer direction `p`.

    `width_step` counts the transverse shell thickness including the main axis
    row. `trim_step` is a tail trimmer only: it advances the strip start along
    the longitudinal axis without affecting the transverse width.

    Parameters
    ----------
    direction : Offset[Lattice]
        Non-zero lattice translation on a 2D lattice whose primitive direction
        defines the strip axis.
    length_step : int
        Number of strip shells from the origin along the primitive direction.
    width_step : int
        Number of transverse shell rows including the main axis row.
    trim_step : int
        Number of longitudinal shells trimmed from the tail near the origin.
    side : Literal["lhs", "rhs"]
        Side on which transverse width shells are accumulated relative to the
        strip direction. `"lhs"` uses the positive lattice normal and `"rhs"`
        uses the negative lattice normal.
    origin : Offset[AffineSpace] | Offset[Lattice] | None
        Anchor point for the strip coordinates. If omitted, the zero offset in
        the lattice space is used. When provided, it is rebased into the
        lattice before evaluating strip membership.

    Returns
    -------
    tuple[Offset[Lattice], ...]
        Deduplicated lattice sites in the strip, ordered by the lattice-site
        ordering.

    Raises
    ------
    ValueError
        If the direction is invalid, the lattice is not 2D, or any step count
        is out of range.
    """
    if length_step < 0:
        raise ValueError(f"length_step must be non-negative, got {length_step}.")
    if width_step < 0:
        raise ValueError(f"width_step must be non-negative, got {width_step}.")
    if trim_step < 0:
        raise ValueError(f"trim_step must be non-negative, got {trim_step}.")
    if trim_step > length_step:
        raise ValueError(
            f"trim_step must not exceed length_step, got {trim_step} and {length_step}."
        )
    if side not in ("lhs", "rhs"):
        raise ValueError(f"side must be 'lhs' or 'rhs', got {side!r}.")
    if length_step == 0 or width_step == 0:
        return ()

    lattice, dx, dy, px, py = _strip_direction_data(direction)
    if origin is None:
        origin = lattice.origin()
    if origin.dim != lattice.dim:
        raise ValueError(
            f"origin must have dimension {lattice.dim} to match the lattice, got {origin.dim}."
        )
    origin_rep = np.array(origin.rebase(lattice).rep, dtype=float).reshape(-1)
    all_sites = lattice.cartes()
    if len(all_sites) == 0:
        return ()

    normal_x = -py
    normal_y = px
    normal_sign = 1 if side == "lhs" else -1
    longitudinal_min = trim_step * (dx * dx + dy * dy)
    longitudinal_max = (length_step - 1) * (dx * dx + dy * dy)
    transverse_min = 0
    transverse_max = width_step - 1

    boundary_basis = np.array(lattice.boundaries.basis.tolist(), dtype=int)
    image_shifts = [
        boundary_basis @ np.array(shift, dtype=int)
        for shift in product((-1, 0, 1), repeat=lattice.dim)
    ]

    region: list[Offset[Lattice]] = []
    for site in all_sites:
        base_rep = np.array(site.rep, dtype=float).reshape(-1)
        include = False
        for shift in image_shifts:
            image_rep = base_rep + shift
            relative_rep = image_rep - origin_rep
            along = dx * relative_rep[0] + dy * relative_rep[1]
            across = normal_sign * (
                normal_x * relative_rep[0] + normal_y * relative_rep[1]
            )
            if (
                along >= longitudinal_min - 1e-9
                and along <= longitudinal_max + 1e-9
                and across >= transverse_min - 1e-9
                and across <= transverse_max + 1e-9
            ):
                include = True
                break
        if include:
            region.append(site)

    return tuple(sorted(region))

interstitial_centers

interstitial_centers(
    region: tuple[OffsetType, ...],
) -> tuple[OffsetType, ...]

Return centers of locally maximal empty spheres supported by region.

Candidate gap points are built as circumcenters of local simplices formed from nearby sites. A candidate is retained when its defining sites are equidistant from the center and no input point lies strictly closer. This recovers square-lattice plaquette centers and also produces non-trivial void centers for lattices such as diamond.

Parameters:

Name Type Description Default
region tuple[Offset, ...] | tuple[Momentum, ...]

Spatial points defining the candidate corner set. All entries must share the same concrete type and affine space.

required

Returns:

Type Description
tuple[Offset, ...] | tuple[Momentum, ...]

Interstitial centers, returned as the same concrete type as the inputs and ordered lexicographically by point coordinates.

Raises:

Type Description
TypeError

If region entries do not all share the same concrete type and space.

Source code in src/qten/geometries/ops.py
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
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
def interstitial_centers(region: tuple[OffsetType, ...]) -> tuple[OffsetType, ...]:
    """
    Return centers of locally maximal empty spheres supported by `region`.

    Candidate gap points are built as circumcenters of local simplices formed
    from nearby sites. A candidate is retained when its defining sites are
    equidistant from the center and no input point lies strictly closer. This
    recovers square-lattice plaquette centers and also produces non-trivial
    void centers for lattices such as diamond.

    Parameters
    ----------
    region : tuple[Offset, ...] | tuple[Momentum, ...]
        Spatial points defining the candidate corner set. All entries must
        share the same concrete type and affine space.

    Returns
    -------
    tuple[Offset, ...] | tuple[Momentum, ...]
        Interstitial centers, returned as the same concrete type as the inputs
        and ordered lexicographically by point coordinates.

    Raises
    ------
    TypeError
        If region entries do not all share the same concrete type and space.
    """
    if len(region) == 0:
        return ()

    first = region[0]
    point_type = type(first)

    for point in region[1:]:
        if type(point) is not point_type:
            raise TypeError("region entries must all have the same concrete type.")
        if point.space != first.space:
            raise TypeError("region entries must all belong to the same space.")

    if len(region) < first.dim + 1:
        return ()

    coords = np.stack([point.to_vec(np.ndarray) for point in region])
    pairwise_distances = np.linalg.norm(coords[:, np.newaxis, :] - coords, axis=2)
    np.fill_diagonal(pairwise_distances, np.inf)

    neighborhood_size = min(len(region), max(8, 4 * first.dim + 2))
    min_support = max(first.dim + 1, 4)
    tolerance = 1e-7
    centers_by_rep: dict[tuple, OffsetType] = {}

    for seed_idx in range(len(region)):
        nearest = np.argsort(pairwise_distances[seed_idx])[: neighborhood_size - 1]
        for neighbor_indices in combinations(nearest, first.dim):
            simplex_indices = (seed_idx, *neighbor_indices)
            center_cart = _circumcenter(coords[list(simplex_indices)])
            if center_cart is None:
                continue

            radius = np.linalg.norm(coords[seed_idx] - center_cart)
            distances = np.linalg.norm(coords - center_cart, axis=1)
            if np.any(distances < radius - tolerance):
                continue

            if (
                np.count_nonzero(
                    np.isclose(distances, radius, atol=tolerance, rtol=tolerance)
                )
                < min_support
            ):
                continue

            center_rep = first.space.basis.inv() @ ImmutableDenseMatrix(center_cart)
            center_rep = ImmutableDenseMatrix(
                [sy.nsimplify(coord) for coord in center_rep]
            )
            center = point_type(rep=center_rep, space=first.space)
            centers_by_rep[tuple(center.rep)] = center

    return tuple(sorted(centers_by_rep.values()))

nearest_sites

nearest_sites(
    lattice: Lattice,
    center: Offset[AffineSpace] | Offset[Lattice],
    n_nearest: int,
) -> tuple[Offset[Lattice], ...]

Return lattice sites through the n_nearest-th distinct distance shell.

Sites are ordered by increasing distance from center, with lattice-site ordering used to break ties deterministically. n_nearest=1 returns the nearest-distance shell, n_nearest=2 returns the first two distinct distance shells, and so on. The center itself is included only when it coincides with a lattice site.

Parameters:

Name Type Description Default
lattice Lattice

Finite lattice whose sites define the candidate region.

required
center Offset[AffineSpace] | Offset[Lattice]

Center used to rank lattice sites by distance. The center may be an arbitrary offset in the lattice affine space and does not need to lie on a lattice site.

required
n_nearest int

Number of distinct distance shells to include. 0 returns an empty region. If n_nearest exceeds the number of distinct distance shells in the finite lattice, all sites are returned.

required

Returns:

Type Description
tuple[Offset[Lattice], ...]

Tuple of lattice sites whose distances from center lie in the first n_nearest distinct distance shells, ordered by increasing distance and then by the lattice-site ordering.

Raises:

Type Description
ValueError

If n_nearest is negative or if center.dim does not match lattice.dim.

Source code in src/qten/geometries/ops.py
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def nearest_sites(
    lattice: Lattice, center: Offset[AffineSpace] | Offset[Lattice], n_nearest: int
) -> tuple[Offset[Lattice], ...]:
    """
    Return lattice sites through the `n_nearest`-th distinct distance shell.

    Sites are ordered by increasing distance from `center`, with lattice-site
    ordering used to break ties deterministically. `n_nearest=1` returns the
    nearest-distance shell, `n_nearest=2` returns the first two distinct
    distance shells, and so on. The center itself is included only when it
    coincides with a lattice site.

    Parameters
    ----------
    lattice : Lattice
        Finite lattice whose sites define the candidate region.
    center : Offset[AffineSpace] | Offset[Lattice]
        Center used to rank lattice sites by distance. The center may be an
        arbitrary offset in the lattice affine space and does not need to lie
        on a lattice site.
    n_nearest : int
        Number of distinct distance shells to include. `0` returns an empty
        region. If `n_nearest` exceeds the number of distinct distance shells
        in the finite lattice, all sites are returned.

    Returns
    -------
    tuple[Offset[Lattice], ...]
        Tuple of lattice sites whose distances from `center` lie in the first
        n_nearest distinct distance shells, ordered by increasing distance
        and then by the lattice-site ordering.

    Raises
    ------
    ValueError
        If `n_nearest` is negative or if `center.dim` does not match
        lattice.dim.
    """
    if n_nearest < 0:
        raise ValueError(f"n_nearest must be non-negative, got {n_nearest}.")
    if center.dim != lattice.dim:
        raise ValueError(
            f"center must have dimension {lattice.dim} to match the lattice, got {center.dim}."
        )
    if n_nearest == 0:
        return ()

    unit_cell_sites = tuple(lattice.unit_cell.values())
    total_sites = math.prod(lattice.shape) * len(unit_cell_sites)
    center_rep = center.rebase(lattice).rep
    origin_cell = tuple(
        int(math.floor(float(center_rep[i, 0]))) for i in range(lattice.dim)
    )

    discovered: dict[Offset[Lattice], float] = {}
    included_count = -1
    stable_after_cutoff = False
    max_local_radius = max(shape // 2 for shape in lattice.shape)

    for radius in range(max_local_radius + 1):
        ranges = [range(cell - radius, cell + radius + 1) for cell in origin_cell]
        for cell_offset in product(*ranges):
            if radius and all(
                abs(cell_offset[i] - origin_cell[i]) < radius
                for i in range(lattice.dim)
            ):
                continue
            cell_rep = ImmutableDenseMatrix(cell_offset)
            for site in unit_cell_sites:
                candidate = Offset(
                    rep=ImmutableDenseMatrix(cell_rep + site.rep), space=lattice
                )
                if candidate in discovered:
                    continue
                discovered[candidate] = center.distance(candidate)

        if len(discovered) == total_sites:
            break

        if len(discovered) < n_nearest:
            continue

        local_sites = sorted(
            ((distance, site) for site, distance in discovered.items()),
            key=lambda item: (item[0], item[1]),
        )
        cutoff_distance = _cutoff_from_sites(local_sites, n_nearest)
        if cutoff_distance is None:
            continue

        new_included_count = sum(
            1
            for distance, _ in local_sites
            if distance < cutoff_distance
            or math.isclose(distance, cutoff_distance, rel_tol=1e-9, abs_tol=1e-9)
        )
        if new_included_count == included_count:
            stable_after_cutoff = True
            break
        included_count = new_included_count

    if stable_after_cutoff or len(discovered) == total_sites:
        sites_with_distances = sorted(
            ((distance, site) for site, distance in discovered.items()),
            key=lambda item: (item[0], item[1]),
        )
    else:
        sites_with_distances = sorted(
            (
                (center.distance(candidate), candidate)
                for cell in lattice.boundaries.representatives()
                for site in unit_cell_sites
                for candidate in (
                    Offset(rep=ImmutableDenseMatrix(cell + site.rep), space=lattice),
                )
            ),
            key=lambda item: (item[0], item[1]),
        )

    cutoff_distance = _cutoff_from_sites(sites_with_distances, n_nearest)

    if cutoff_distance is None:
        return tuple(site for _, site in sites_with_distances)

    return tuple(
        site
        for distance, site in sites_with_distances
        if distance < cutoff_distance
        or math.isclose(distance, cutoff_distance, rel_tol=1e-9, abs_tol=1e-9)
    )

region_centering

region_centering(
    region: tuple[OffsetType, ...], center: OffsetType
) -> tuple[OffsetType, ...]

Translate a region so that its arithmetic center lands at center.

Parameters:

Name Type Description Default
region tuple[Offset, ...] | tuple[Momentum, ...]

Region to translate. All entries must share the same concrete type and affine space.

required
center Offset | Momentum

Target center for the translated region. It must have the same concrete type and affine space as the region entries.

required

Returns:

Type Description
tuple[Offset, ...] | tuple[Momentum, ...]

Region translated by center - center_of_region(region). Empty input returns an empty tuple.

Raises:

Type Description
TypeError

If region entries do not all share the same concrete type and space, or if center does not match them.

Source code in src/qten/geometries/ops.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
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
def region_centering(
    region: tuple[OffsetType, ...], center: OffsetType
) -> tuple[OffsetType, ...]:
    """
    Translate a region so that its arithmetic center lands at `center`.

    Parameters
    ----------
    region : tuple[Offset, ...] | tuple[Momentum, ...]
        Region to translate. All entries must share the same concrete type and
        affine space.
    center : Offset | Momentum
        Target center for the translated region. It must have the same
        concrete type and affine space as the region entries.

    Returns
    -------
    tuple[Offset, ...] | tuple[Momentum, ...]
        Region translated by `center - center_of_region(region)`. Empty input
        returns an empty tuple.

    Raises
    ------
    TypeError
        If region entries do not all share the same concrete type and space,
        or if `center` does not match them.
    """
    if len(region) == 0:
        return ()

    first = region[0]
    point_type = type(first)

    for point in region[1:]:
        if type(point) is not point_type:
            raise TypeError("region entries must all have the same concrete type.")
        if point.space != first.space:
            raise TypeError("region entries must all belong to the same space.")

    if type(center) is not point_type:
        raise TypeError(
            "center must have the same concrete type as the region entries."
        )
    if center.space != first.space:
        raise TypeError("center must belong to the same space as the region entries.")

    translation = cast(OffsetType, center - center_of_region(region))
    return tuple(cast(OffsetType, point + translation) for point in region)

region_tile

region_tile(
    region: tuple[OffsetType, ...],
    bases: tuple[OffsetType, ...],
    counts: tuple[int, ...],
) -> tuple[OffsetType, ...]

Tile a region by integer combinations of the supplied translation bases.

The returned region contains translations of every point in region by offsets

\(\sum_i n_i b_i\), with \(0 \le n_i < \mathrm{counts}[i]\),

where b_i are the entries of bases.

Parameters:

Name Type Description Default
region tuple[Offset, ...] | tuple[Momentum, ...]

Region to translate. All entries must share the same concrete type and affine space.

required
bases tuple[Offset, ...] | tuple[Momentum, ...]

Translation basis vectors. All entries must share the same concrete type and affine space as the region entries.

required
counts tuple[int, ...]

Number of repetitions along each translation basis. Each entry must be non-negative.

required

Returns:

Type Description
tuple[Offset, ...] | tuple[Momentum, ...]

Deduplicated tiled region, ordered by the point ordering.

Raises:

Type Description
TypeError

If region or basis entries do not all share the same concrete type and space.

ValueError

If counts has the wrong length or contains negative entries.

Source code in src/qten/geometries/ops.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
def region_tile(
    region: tuple[OffsetType, ...],
    bases: tuple[OffsetType, ...],
    counts: tuple[int, ...],
) -> tuple[OffsetType, ...]:
    r"""
    Tile a region by integer combinations of the supplied translation bases.

    The returned region contains translations of every point in `region` by
    offsets

    \(\sum_i n_i b_i\), with \(0 \le n_i < \mathrm{counts}[i]\),

    where `b_i` are the entries of `bases`.

    Parameters
    ----------
    region : tuple[Offset, ...] | tuple[Momentum, ...]
        Region to translate. All entries must share the same concrete type and
        affine space.
    bases : tuple[Offset, ...] | tuple[Momentum, ...]
        Translation basis vectors. All entries must share the same concrete
        type and affine space as the region entries.
    counts : tuple[int, ...]
        Number of repetitions along each translation basis. Each entry must be
        non-negative.

    Returns
    -------
    tuple[Offset, ...] | tuple[Momentum, ...]
        Deduplicated tiled region, ordered by the point ordering.

    Raises
    ------
    TypeError
        If region or basis entries do not all share the same concrete type and
        space.
    ValueError
        If `counts` has the wrong length or contains negative entries.
    """
    if len(region) == 0:
        return ()

    if len(bases) != len(counts):
        raise ValueError(
            f"bases and counts must have the same length, got {len(bases)} and {len(counts)}."
        )
    if any(count < 0 for count in counts):
        raise ValueError(f"counts must be non-negative, got {counts}.")
    if any(count == 0 for count in counts):
        return ()

    first = region[0]
    point_type = type(first)

    for point in region[1:]:
        if type(point) is not point_type:
            raise TypeError("region entries must all have the same concrete type.")
        if point.space != first.space:
            raise TypeError("region entries must all belong to the same space.")

    for basis in bases:
        if type(basis) is not point_type:
            raise TypeError(
                "basis entries must all have the same concrete type as the region entries."
            )
        if basis.space != first.space:
            raise TypeError(
                "basis entries must all belong to the same space as the region entries."
            )

    tiled: dict[OffsetType, None] = {}
    for coefficients in product(*(range(count) for count in counts)):
        translation_rep = sum(
            (
                coefficient * basis.rep
                for coefficient, basis in zip(coefficients, bases)
            ),
            ImmutableDenseMatrix.zeros(first.dim, 1),
        )
        translation = point_type(
            rep=ImmutableDenseMatrix(translation_rep), space=first.space
        )
        for point in region:
            tiled[cast(OffsetType, point + translation)] = None

    return tuple(sorted(tiled))