Skip to content

qten.bands

Module reference for qten.bands.

bands

Band-structure helpers for momentum-resolved QTen tensors.

This module provides utilities for transforming, folding, unfolding, filling, and selecting bands represented as Tensor objects. The common convention is that a band tensor has dimensions (MomentumSpace, HilbertSpace, HilbertSpace): the MomentumSpace axis indexes crystal momenta and the two HilbertSpace axes form the Hamiltonian or operator matrix at each momentum.

Mathematical convention

A band tensor represents a family of matrices indexed by crystal momentum: \(H : k \mapsto H(k)\), with \(H(k)_{ab} = \langle a | H(k) | b \rangle\).

In code this is stored as a rank-3 Tensor with dims (K, B_left, B_right), where K is a MomentumSpace and the two Hilbert-space axes provide the row and column basis labels for each matrix block.

Geometry transformations act on both parts of this object: \(k \mapsto k'\) and \(H(k) \mapsto U(k)\,H(k)\,U(k)^\dagger\).

where the \(k\)-dependent change-of-basis matrix \(U(k)\) is assembled from symbolic Hilbert-space relabeling and finite Fourier transforms.

Repository usage

The functions here sit between geometry, symbolic Hilbert-space labels, and linear algebra. Geometry objects provide real and reciprocal lattice structure, symbolic state spaces label tensor axes, and linear algebra routines diagonalize the momentum-sector matrices when filling or selecting bands.

interpolate_path

interpolate_path(
    recip: ReciprocalLattice,
    waypoints: Sequence[str],
    points: KPointSet,
    n_points: int = 100,
    wrap_fractional: bool = True,
) -> BzPath

Build a sampled Brillouin-zone path in a reciprocal lattice.

Parameters:

Name Type Description Default
recip ReciprocalLattice

Reciprocal lattice in which waypoint coordinates are interpreted.

required
waypoints Sequence[str]

Waypoint names in path order, e.g. ["G", "X", "M", "G"].

required
n_points int

Number of samples used along the full interpolated path.

100
points KPointSet

Named reciprocal-space points carrying their source reciprocal lattice. They are rebased to recip before interpolation.

required
wrap_fractional bool

If True, wrap each rebased waypoint into the canonical fractional cell before interpolation. Set to False to preserve raw rebased coordinates.

True

Returns:

Type Description
BzPath

Sampled Brillouin-zone path with momentum space, waypoint labels, and path-order metadata.

Raises:

Type Description
TypeError

If points is not a KPointSet.

ValueError

If fewer than two waypoints are supplied, if a named waypoint is not present in points, if n_points is too small for the number of waypoints, or if all waypoints are identical.

Examples:

path = interpolate_path(
    recip,
    waypoints=["G", "X", "M"],
    points=KPointSet.from_points(
        recip,
        {"G": (0.0, 0.0), "X": (0.5, 0.0), "M": (0.5, 0.5)},
    ),
)
path = interpolate_path(
    recip=new_recip,
    waypoints=["G", "X", "M"],
    points=original_kpoints,  # KPointSet tied to old reciprocal basis
)
Source code in src/qten/bands.py
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
238
239
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
def interpolate_path(
    recip: ReciprocalLattice,
    waypoints: Sequence[str],
    points: KPointSet,
    n_points: int = 100,
    wrap_fractional: bool = True,
) -> BzPath:
    """
    Build a sampled Brillouin-zone path in a reciprocal lattice.

    Parameters
    ----------
    recip : ReciprocalLattice
        Reciprocal lattice in which waypoint coordinates are interpreted.
    waypoints : Sequence[str]
        Waypoint names in path order, e.g. `["G", "X", "M", "G"]`.
    n_points : int
        Number of samples used along the full interpolated path.
    points : KPointSet
        Named reciprocal-space points carrying their source reciprocal lattice.
        They are rebased to `recip` before interpolation.
    wrap_fractional : bool, default=True
        If True, wrap each rebased waypoint into the canonical fractional cell
        before interpolation. Set to False to preserve raw rebased coordinates.
    Returns
    -------
    BzPath
        Sampled Brillouin-zone path with momentum space, waypoint labels, and
        path-order metadata.

    Raises
    ------
    TypeError
        If `points` is not a [`KPointSet`][qten.geometries.spatials.KPointSet].
    ValueError
        If fewer than two waypoints are supplied, if a named waypoint is not
        present in `points`, if `n_points` is too small for the number of
        waypoints, or if all waypoints are identical.

    Examples
    --------
    ```python
    path = interpolate_path(
        recip,
        waypoints=["G", "X", "M"],
        points=KPointSet.from_points(
            recip,
            {"G": (0.0, 0.0), "X": (0.5, 0.0), "M": (0.5, 0.5)},
        ),
    )
    ```

    ```python
    path = interpolate_path(
        recip=new_recip,
        waypoints=["G", "X", "M"],
        points=original_kpoints,  # KPointSet tied to old reciprocal basis
    )
    ```
    """
    if not isinstance(points, KPointSet):
        raise TypeError("points must be provided as a KPointSet.")
    if len(waypoints) < 2:
        raise ValueError("At least two waypoints are required to define a path.")
    rebased_points = points.rebase(recip)

    resolved_wp: list[Momentum] = []
    dim = recip.dim
    for i, wp in enumerate(waypoints):
        if wp not in rebased_points.points:
            raise ValueError(
                f"Waypoint {i} is the name '{wp}' but it was not found in "
                f"the points dictionary. Available names: "
                f"{sorted(rebased_points.points.keys()) if rebased_points.points else '(empty)'}."
            )
        rebased_wp = rebased_points.points[wp]
        resolved_wp.append(rebased_wp.fractional() if wrap_fractional else rebased_wp)

    if n_points < len(resolved_wp):
        raise ValueError(
            f"n_points ({n_points}) must be >= number of waypoints ({len(resolved_wp)})."
        )

    basis_mat = np.array(recip.basis.evalf(), dtype=float)
    wp_frac = np.array(
        [[float(k.rep[j, 0]) for j in range(dim)] for k in resolved_wp],
        dtype=float,
    )
    wp_cart = wp_frac @ basis_mat.T

    seg_lengths = np.array(
        [
            np.linalg.norm(wp_cart[i + 1] - wp_cart[i])
            for i in range(len(resolved_wp) - 1)
        ]
    )
    total_length = seg_lengths.sum()
    n_segments = len(resolved_wp) - 1

    if total_length < 1e-15:
        raise ValueError("All waypoints are identical; path has zero length.")

    remaining = n_points - n_segments - 1
    interior_per_seg = np.zeros(n_segments, dtype=int)
    if remaining > 0:
        ideal = (seg_lengths / total_length) * remaining
        interior_per_seg = np.floor(ideal).astype(int)
        deficit = remaining - interior_per_seg.sum()
        fracs = ideal - interior_per_seg
        for idx in np.argsort(-fracs)[:deficit]:
            interior_per_seg[idx] += 1

    all_fracs: list[np.ndarray] = []
    waypoint_indices: list[int] = []

    for seg in range(n_segments):
        n_interior = int(interior_per_seg[seg])
        n_seg_points = n_interior + 1
        t_vals = np.linspace(0.0, 1.0, n_seg_points, endpoint=False)
        start = wp_frac[seg]
        end = wp_frac[seg + 1]
        waypoint_indices.append(len(all_fracs))
        for t in t_vals:
            all_fracs.append(start + t * (end - start))

    waypoint_indices.append(len(all_fracs))
    all_fracs.append(wp_frac[-1])

    seen: dict[Momentum, int] = {}
    unique_momenta: list[Momentum] = []
    path_order: list[int] = []

    for frac in all_fracs:
        rep = ImmutableDenseMatrix(
            [sy.Rational(f).limit_denominator(10**9) for f in frac]
        )
        k = Momentum(rep=rep, space=recip)
        if k not in seen:
            seen[k] = len(unique_momenta)
            unique_momenta.append(k)
        path_order.append(seen[k])

    structure: OrderedDict[Momentum, int] = OrderedDict(
        (k, i) for i, k in enumerate(unique_momenta)
    )
    k_space = MomentumSpace(structure=structure)

    all_cart = np.stack(all_fracs) @ basis_mat.T
    diffs = np.diff(all_cart, axis=0)
    dists = np.linalg.norm(diffs, axis=1)
    positions = np.concatenate(([0.0], np.cumsum(dists)))

    return BzPath(
        k_space=k_space,
        labels=tuple(waypoints),
        waypoint_indices=tuple(waypoint_indices),
        path_order=tuple(path_order),
        path_positions=tuple(float(p) for p in positions),
    )

get_band_transform

get_band_transform(
    t: Opr,
    tensor: Tensor,
    side: Literal["left", "right"] = "left",
) -> MomentumBlockTensor
get_band_transform(
    t: Opr,
    kspace: MomentumSpace,
    target_space: HilbertSpace,
    *,
    device: Optional[Device] = None,
) -> MomentumBlockTensor

Construct a reusable one-sided geometric basis-change operator for a momentum-resolved band tensor.

Supported forms

get_band_transform(t, tensor, side=...) Build the transform from a rank-3 band tensor with dims (MomentumSpace, HilbertSpace, HilbertSpace), using side to choose which Hilbert-space leg is sampled.

get_band_transform(t, kspace, target_space, device=...) Build the same transform directly from an explicit MomentumSpace kspace and sampled HilbertSpace target_space, without first packaging them into a rank-3 tensor.

Use cases

This helper is useful when the geometric action should be materialized once and then reused across multiple band tensors, when only one matrix leg of a non-Hermitian or rectangular band object should be transformed, or when the transform itself should be inspected as a MomentumBlockTensor rather than applied immediately.

For example, a caller may build the left and right transforms separately, cache them, and apply them to several tensors sharing the same symbolic momentum and Hilbert spaces.

This function factors one side of the geometric basis change performed by bandtransform into an explicit MomentumBlockTensor \(T_g\). For a momentum-resolved operator \(H\), the one-sided transformed tensor is recovered by \(T_g H\) when side="left" and by \(H T_g^\dagger\) when side="right". Applying both sides requires composing the two separately constructed transforms.

The leading axis of \(T_g\) is a MomentumBlockSpace storing ordered pairs (t @ k, k): each block describes the basis map from the source momentum sector k to the transformed sector t @ k.

Behavior

This function does not transform tensor data directly. Instead it builds a block operator whose momentum-pair axis records how source sectors feed transformed sectors. The Hilbert-space block at each such pair combines:

  1. the symbolic action of t on the sampled basis,
  2. fractional wrapping back to the home unit cell, and
  3. the Fourier phase needed to keep Bloch conventions consistent after the geometric relabeling.

The returned transform is therefore the reusable one-sided ingredient of bandtransform, not merely a permutation of momentum labels.

Basis sampling

The input tensor may have dims (K, B_left, B_right) with potentially different left and right Hilbert spaces. The side argument chooses which matrix leg supplies the canonical Hilbert space used to assemble \(T_g\).

Parameters:

Name Type Description Default
t Opr

Operator acting consistently on both Momentum and the Offset-carrying basis states inside the sampled Hilbert space.

required
tensor Tensor

Rank-3 momentum-space tensor with dims (MomentumSpace, HilbertSpace, HilbertSpace).

required
side Literal['left', 'right']

Which matrix leg to sample when constructing the transform basis. side="left" uses tensor.dims[1]; side="right" uses tensor.dims[2]. The default is "left".

'left'

Returns:

Type Description
MomentumBlockTensor

Block transform tensor with dims (MomentumBlockSpace, B, B), where B is the sampled Hilbert space selected by side.

Raises:

Type Description
ValueError

If tensor is not rank 3, if the transformed Hilbert space is not closed on the sampled basis after fractional wrapping, or if the momentum action of t is not one-to-one on the input MomentumSpace.

TypeError

If the tensor dims do not have the required MomentumSpace/HilbertSpace/HilbertSpace structure.

Notes

The generated API docs for this module show overload signatures, but the prose is rendered from this public implementation docstring. The explicit space overload accepts kspace and target_space directly, then dispatches here through the shared construction path.

Examples:

Build and apply only the left transform:

T_left = get_band_transform(t, tensor, side="left")
routed = T_left @ tensor

Build both one-sided transforms explicitly and compose them:

T_left = get_band_transform(t, tensor, side="left")
T_right = get_band_transform(t, tensor, side="right")
transformed = T_left @ tensor @ T_right.h(-2, -1)

Build the transform directly from symbolic spaces:

T_left = get_band_transform(t, kspace, hilbert_space, device=device)
See Also

bandtransform(t, tensor, opt=...) Public wrapper that applies one-sided or two-sided band transforms. get_band_fold(transform, tensor, side=...) Folding analogue that builds the corresponding block transform for a basis-change-induced Brillouin-zone fold.

Source code in src/qten/bands.py
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
595
596
597
598
599
600
601
602
603
604
605
606
607
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
@multimethod
def get_band_transform(
    t: Opr,
    tensor: Tensor,
    side: Literal["left", "right"] = "left",
) -> MomentumBlockTensor:
    r"""
    Construct a reusable one-sided geometric basis-change operator for a
    momentum-resolved band tensor.

    Supported forms
    ---------------
    [`get_band_transform(t, tensor, side=...)`][qten.bands.get_band_transform]
        Build the transform from a rank-3 band tensor with dims
        `(MomentumSpace, HilbertSpace, HilbertSpace)`, using `side` to choose
        which Hilbert-space leg is sampled.

    [`get_band_transform(t, kspace, target_space, device=...)`][qten.bands.get_band_transform]
        Build the same transform directly from an explicit
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] `kspace`
        and sampled [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace]
        `target_space`, without first packaging them into a rank-3 tensor.

    Use cases
    ---------
    This helper is useful when the geometric action should be materialized once
    and then reused across multiple band tensors, when only one matrix leg of a
    non-Hermitian or rectangular band object should be transformed, or when the
    transform itself should be inspected as a
    [`MomentumBlockTensor`][qten.MomentumBlockTensor] rather than applied
    immediately.

    For example, a caller may build the left and right transforms separately,
    cache them, and apply them to several tensors sharing the same symbolic
    momentum and Hilbert spaces.

    This function factors one side of the geometric basis change performed by
    [`bandtransform`][qten.bands.bandtransform] into an explicit
    [`MomentumBlockTensor`][qten.MomentumBlockTensor] \(T_g\). For a
    momentum-resolved operator \(H\), the one-sided transformed tensor is
    recovered by \(T_g H\) when `side="left"` and by
    \(H T_g^\dagger\) when `side="right"`. Applying both sides requires
    composing the two separately constructed transforms.

    The leading axis of \(T_g\) is a
    [`MomentumBlockSpace`][qten.symbolics.state_space.MomentumBlockSpace]
    storing ordered pairs `(t @ k, k)`: each block describes the basis map from
    the source momentum sector `k` to the transformed sector `t @ k`.

    Behavior
    --------
    This function does not transform tensor data directly. Instead it builds a
    block operator whose momentum-pair axis records how source sectors feed
    transformed sectors. The Hilbert-space block at each such pair combines:

    1. the symbolic action of `t` on the sampled basis,
    2. fractional wrapping back to the home unit cell, and
    3. the Fourier phase needed to keep Bloch conventions consistent after the
       geometric relabeling.

    The returned transform is therefore the reusable one-sided ingredient of
    [`bandtransform`][qten.bands.bandtransform], not merely a permutation of
    momentum labels.

    Basis sampling
    --------------
    The input tensor may have dims `(K, B_left, B_right)` with potentially
    different left and right Hilbert spaces. The `side` argument chooses which
    matrix leg supplies the canonical Hilbert space used to assemble \(T_g\).

    Parameters
    ----------
    t : Opr
        Operator acting consistently on both
        [`Momentum`][qten.geometries.spatials.Momentum] and the
        [`Offset`][qten.geometries.spatials.Offset]-carrying basis states inside
        the sampled Hilbert space.
    tensor : Tensor
        Rank-3 momentum-space tensor with dims
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    side : Literal["left", "right"], optional
        Which matrix leg to sample when constructing the transform basis.
        `side="left"` uses `tensor.dims[1]`; `side="right"` uses
        `tensor.dims[2]`. The default is `"left"`.

    Returns
    -------
    MomentumBlockTensor
        Block transform tensor with dims
        `(MomentumBlockSpace, B, B)`, where `B` is the sampled Hilbert space
        selected by `side`.

    Raises
    ------
    ValueError
        If `tensor` is not rank 3, if the transformed Hilbert space is not
        closed on the sampled basis after fractional wrapping, or if the
        momentum action of `t` is not one-to-one on the input
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace].
    TypeError
        If the tensor dims do not have the required
        `MomentumSpace/HilbertSpace/HilbertSpace` structure.

    Notes
    -----
    The generated API docs for this module show overload signatures, but the
    prose is rendered from this public implementation docstring. The explicit
    space overload accepts `kspace` and `target_space` directly, then
    dispatches here through the shared construction path.

    Examples
    --------
    Build and apply only the left transform:

    ```python
    T_left = get_band_transform(t, tensor, side="left")
    routed = T_left @ tensor
    ```

    Build both one-sided transforms explicitly and compose them:

    ```python
    T_left = get_band_transform(t, tensor, side="left")
    T_right = get_band_transform(t, tensor, side="right")
    transformed = T_left @ tensor @ T_right.h(-2, -1)
    ```

    Build the transform directly from symbolic spaces:

    ```python
    T_left = get_band_transform(t, kspace, hilbert_space, device=device)
    ```

    See Also
    --------
    [`bandtransform(t, tensor, opt=...)`][qten.bands.bandtransform]
        Public wrapper that applies one-sided or two-sided band transforms.
    [`get_band_fold(transform, tensor, side=...)`][qten.bands.get_band_fold]
        Folding analogue that builds the corresponding block transform for a
        basis-change-induced Brillouin-zone fold.
    """
    kspace, target_space = _validate_block_transformable_tensor(
        tensor, "get_band_transform", side
    )
    return _get_band_transform_from_spaces(
        t, kspace, target_space, device=tensor.device
    )

get_band_fold

get_band_fold(
    transform: BasisTransform,
    tensor: Tensor,
    side: Literal["left", "right"] = "left",
) -> MomentumBlockTensor
get_band_fold(
    transform: BasisTransform,
    k_space: MomentumSpace,
    target_space: HilbertSpace,
    *,
    device: Optional[Device] = None,
) -> MomentumBlockTensor

Construct a reusable one-sided Brillouin-zone folding operator for a momentum-resolved band tensor.

Supported forms

get_band_fold(transform, tensor, side=...) Build the folding transform from a rank-3 band tensor with dims (MomentumSpace, HilbertSpace, HilbertSpace), using side to choose which Hilbert-space leg is sampled.

get_band_fold(transform, k_space, target_space, device=...) Build the same folding transform directly from an explicit MomentumSpace k_space and sampled HilbertSpace target_space, without first packaging them into a rank-3 tensor.

Use cases

This helper is useful when Brillouin-zone folding should be factored into a reusable one-sided operator, when left and right Hilbert-space legs should be folded independently, or when the folding map itself should be examined as a block tensor before applying it to data.

Typical workflows include caching folded-cell transforms for repeated use, applying folding to only one matrix leg of a tensor, or explicitly constructing the left and right folded operators before composing them.

This function factors one side of the Brillouin-zone folding operation into an explicit MomentumBlockTensor \(T_g\). For a momentum-resolved operator \(H\), the one-sided folded tensor is recovered by \(T_g H\) when side="left" and by \(H T_g^\dagger\) when side="right". Folding both sides requires composing the two separately constructed transforms.

Each block of \(T_g\) is labelled by a pair \((k_{\mathrm{fold}}, k)\) on its leading MomentumBlockSpace, where \(k\) is a momentum of the original Brillouin zone and \(k_{\mathrm{fold}}\) is the momentum sector it maps to in the folded zone. The Hilbert-space legs encode the Fourier-based change of basis between the original unit cell and the enlarged transformed cell.

Behavior

Folding changes both the momentum grid and the real-space basis. This helper builds the one-sided block operator that performs those two tasks together:

  1. each source momentum sector is routed to its folded-zone momentum,
  2. the sampled Hilbert-space basis is enlarged to the transformed unit cell, and
  3. the corresponding Fourier change of basis is assembled into each block.

The result is not just a relabeling of momentum sectors. It is the reusable one-sided ingredient of bandfold that carries both sector routing and enlarged-cell basis conversion. When multiple basis states share the same fractional site within the sampled Hilbert space, all of them are preserved in the enlarged folded basis.

Basis sampling

The input tensor may have dims (K, B_left, B_right) with potentially different left and right Hilbert spaces. The side argument chooses which leg supplies the canonical basis from which the folding transform is built.

Parameters:

Name Type Description Default
transform BasisTransform

Direct-lattice basis transformation that defines the folded Brillouin zone.

required
tensor Tensor

Rank-3 momentum-space tensor with dims (MomentumSpace, HilbertSpace, HilbertSpace).

required
side Literal['left', 'right']

Which matrix leg to sample when constructing the folding basis. side="left" uses tensor.dims[1]; side="right" uses tensor.dims[2]. The default is "left".

'left'

Returns:

Type Description
MomentumBlockTensor

Block folding tensor with dims (MomentumBlockSpace, B_fold, B), where B is the sampled input Hilbert space selected by side and B_fold is the corresponding enlarged folded-cell Hilbert space.

Raises:

Type Description
ValueError

If tensor is not rank 3, if its momentum axis is empty or inconsistent, or if the sampled Hilbert basis has no states at a required unit-cell offset during the folding construction.

TypeError

If the tensor dims do not have the required MomentumSpace/HilbertSpace/HilbertSpace structure, or if the momentum axis is not backed by a ReciprocalLattice.

Notes

The generated API docs for this module show overload signatures, but the prose is rendered from this public implementation docstring. The explicit space overload accepts k_space and target_space directly, then dispatches here through the shared folding construction path.

Examples:

Build and apply only the right folding transform:

T_right = get_band_fold(transform, tensor, side="right")
routed = tensor @ T_right.h(-2, -1)

Build both one-sided folding transforms explicitly:

T_left = get_band_fold(transform, tensor, side="left")
T_right = get_band_fold(transform, tensor, side="right")
folded = T_left @ tensor @ T_right.h(-2, -1)

Build the folding transform directly from symbolic spaces:

T_left = get_band_fold(transform, k_space, hilbert_space, device=device)
See Also

bandfold(transform, tensor, opt=...) Public wrapper that applies this block folding transform to a band tensor. get_band_transform(t, tensor, side=...) Symmetry-transform analogue that constructs a momentum-block transform without Brillouin-zone folding.

Source code in src/qten/bands.py
817
818
819
820
821
822
823
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
860
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
@multimethod
def get_band_fold(
    transform: BasisTransform,
    tensor: Tensor,
    side: Literal["left", "right"] = "left",
) -> MomentumBlockTensor:
    r"""
    Construct a reusable one-sided Brillouin-zone folding operator for a
    momentum-resolved band tensor.

    Supported forms
    ---------------
    [`get_band_fold(transform, tensor, side=...)`][qten.bands.get_band_fold]
        Build the folding transform from a rank-3 band tensor with dims
        `(MomentumSpace, HilbertSpace, HilbertSpace)`, using `side` to choose
        which Hilbert-space leg is sampled.

    [`get_band_fold(transform, k_space, target_space, device=...)`][qten.bands.get_band_fold]
        Build the same folding transform directly from an explicit
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] `k_space`
        and sampled [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace]
        `target_space`, without first packaging them into a rank-3 tensor.

    Use cases
    ---------
    This helper is useful when Brillouin-zone folding should be factored into a
    reusable one-sided operator, when left and right Hilbert-space legs should
    be folded independently, or when the folding map itself should be examined
    as a block tensor before applying it to data.

    Typical workflows include caching folded-cell transforms for repeated use,
    applying folding to only one matrix leg of a tensor, or explicitly
    constructing the left and right folded operators before composing them.

    This function factors one side of the Brillouin-zone folding operation
    into an explicit [`MomentumBlockTensor`][qten.MomentumBlockTensor] \(T_g\).
    For a momentum-resolved operator \(H\), the one-sided folded tensor is
    recovered by \(T_g H\) when `side="left"` and by
    \(H T_g^\dagger\) when `side="right"`. Folding both sides requires
    composing the two separately constructed transforms.

    Each block of \(T_g\) is labelled by a pair
    \((k_{\mathrm{fold}}, k)\) on its leading
    [`MomentumBlockSpace`][qten.symbolics.state_space.MomentumBlockSpace],
    where \(k\) is a momentum of the original Brillouin zone and
    \(k_{\mathrm{fold}}\) is the momentum sector it maps to in the folded
    zone.
    The Hilbert-space legs encode the Fourier-based change of basis between the
    original unit cell and the enlarged transformed cell.

    Behavior
    --------
    Folding changes both the momentum grid and the real-space basis. This
    helper builds the one-sided block operator that performs those two tasks
    together:

    1. each source momentum sector is routed to its folded-zone momentum,
    2. the sampled Hilbert-space basis is enlarged to the transformed unit
       cell, and
    3. the corresponding Fourier change of basis is assembled into each block.

    The result is not just a relabeling of momentum sectors. It is the
    reusable one-sided ingredient of [`bandfold`][qten.bands.bandfold] that
    carries both sector routing and enlarged-cell basis conversion.
    When multiple basis states share the same fractional site within the
    sampled Hilbert space, all of them are preserved in the enlarged folded
    basis.

    Basis sampling
    --------------
    The input tensor may have dims `(K, B_left, B_right)` with potentially
    different left and right Hilbert spaces. The `side` argument chooses which
    leg supplies the canonical basis from which the folding transform is built.

    Parameters
    ----------
    transform : BasisTransform
        Direct-lattice basis transformation that defines the folded Brillouin
        zone.
    tensor : Tensor
        Rank-3 momentum-space tensor with dims
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    side : Literal["left", "right"], optional
        Which matrix leg to sample when constructing the folding basis.
        `side="left"` uses `tensor.dims[1]`; `side="right"` uses
        `tensor.dims[2]`. The default is `"left"`.

    Returns
    -------
    MomentumBlockTensor
        Block folding tensor with dims `(MomentumBlockSpace, B_fold, B)`, where
        `B` is the sampled input Hilbert space selected by `side` and
        `B_fold` is the corresponding enlarged folded-cell Hilbert space.

    Raises
    ------
    ValueError
        If `tensor` is not rank 3, if its momentum axis is empty or
        inconsistent, or if the sampled Hilbert basis has no states at a
        required unit-cell offset during the folding construction.
    TypeError
        If the tensor dims do not have the required
        `MomentumSpace/HilbertSpace/HilbertSpace` structure, or if the momentum
        axis is not backed by a
        [`ReciprocalLattice`][qten.geometries.spatials.ReciprocalLattice].

    Notes
    -----
    The generated API docs for this module show overload signatures, but the
    prose is rendered from this public implementation docstring. The explicit
    space overload accepts `k_space` and `target_space` directly, then
    dispatches here through the shared folding construction path.

    Examples
    --------
    Build and apply only the right folding transform:

    ```python
    T_right = get_band_fold(transform, tensor, side="right")
    routed = tensor @ T_right.h(-2, -1)
    ```

    Build both one-sided folding transforms explicitly:

    ```python
    T_left = get_band_fold(transform, tensor, side="left")
    T_right = get_band_fold(transform, tensor, side="right")
    folded = T_left @ tensor @ T_right.h(-2, -1)
    ```

    Build the folding transform directly from symbolic spaces:

    ```python
    T_left = get_band_fold(transform, k_space, hilbert_space, device=device)
    ```

    See Also
    --------
    [`bandfold(transform, tensor, opt=...)`][qten.bands.bandfold]
        Public wrapper that applies this block folding transform to a band
        tensor.
    [`get_band_transform(t, tensor, side=...)`][qten.bands.get_band_transform]
        Symmetry-transform analogue that constructs a momentum-block transform
        without Brillouin-zone folding.
    """
    k_space, target_space = _validate_block_transformable_tensor(
        tensor, "get_band_fold", side
    )
    return _get_band_fold_from_spaces(
        transform, k_space, target_space, device=tensor.device
    )

bandtransform

bandtransform(
    t: Opr,
    tensor: Tensor,
    opt: Literal["left", "right", "both"] = "both",
) -> Tensor

Apply a basis transform to a momentum-resolved operator tensor.

The expected tensor shape is (K, B_left, B_right) where K is a MomentumSpace and B_left, B_right are HilbertSpace axes. This function applies the operator-induced basis transform on the selected Hilbert-space legs of the band tensor.

For each transformed side, a k-dependent matrix is built from the action of t on the Hilbert-space basis and Fourier transforms that connect Bloch and real-space sectors.

Mathematical action

Let \(B_{\mathrm{left}}\) and \(B_{\mathrm{right}}\) be the input Hilbert-space bases and let the corresponding transformed bases be \(tB_{\mathrm{left}}\) and \(tB_{\mathrm{right}}\). After wrapping transformed sites back to the home unit cell, the finite Fourier transform contributes a momentum-dependent phase. The resulting basis-change matrices are denoted \(U_t^{(\mathrm{left})}(k)\) and \(U_t^{(\mathrm{right})}(k)\). When routed contributions are collapsed back onto the transformed momentum grid, the transformed band block is one of:

opt="left": \(H'(t k) = U_t^{(\mathrm{left})}(k)\,H(k)\)

opt="right": \(H'(t k) = H(k)\,U_t^{(\mathrm{right})}(k)^\dagger\)

opt="both": \(H'(t k) = U_t^{(\mathrm{left})}(k)\,H(k)\,U_t^{(\mathrm{right})}(k)^\dagger\)

Momentum handling

The action on Momentum is treated as a relabeling or permutation of sectors. For opt="both", the output tensor carries the transformed momentum axis mapped_kspace = {t @ k | k in kspace}. For opt="left" and opt="right", the implementation instead preserves a routed MomentumBlockSpace pair axis so each source block remains attached to its transformed target sector. In either case, the selected Hilbert-space transforms are applied before any optional collapse back to a plain MomentumSpace.

Notes

This function accepts a general Opr, but not every Opr is valid here. In practice, t must act coherently across the real-space and momentum-space labels carried by the tensor:

t @ k must be defined for each Momentum in the first tensor axis. t @ psi must be defined for each U1Basis in the Hilbert-space axes, in particular for the Offset irrep stored inside each basis state. The Hilbert-space action and momentum action must be dual-compatible, so that the Fourier transform remains consistent after applying t. For each selected side, after applying FuncOpr(Offset, Offset.fractional), the transformed Hilbert space must have the same rays as the sampled input basis on that side. Otherwise the transformed basis does not close on that band leg and this function raises ValueError.

Operators that only act on abstract U1Basis values or only on Momentum values are not sufficient. The operator must provide matching actions on site offsets and crystal momentum.

Parameters:

Name Type Description Default
t Opr

Operator to apply. It must satisfy the compatibility conditions described in the notes below.

required
tensor Tensor

Momentum-space tensor with dims (MomentumSpace, HilbertSpace, HilbertSpace).

required
opt Literal['left', 'right', 'both']

Which matrix legs to transform. "left" applies only the left transform, "right" applies only the right transform, and "both" applies independent transforms on both sides. The default is "both".

'both'

Returns:

Type Description
Tensor

If opt="both", returns the transformed tensor with a transformed MomentumSpace axis and transformed Hilbert-space matrix legs. If opt="left" or opt="right", returns the corresponding one-sided routed intermediate as a MomentumBlockTensor whose leading MomentumBlockSpace axis stores ordered pairs (t @ k, k) or (k, t @ k), respectively. In those one-sided modes, the transformed momentum labels are carried on the pair axis rather than collapsed back to a plain MomentumSpace.

Raises:

Type Description
ValueError

If tensor is not rank 3 with a MomentumSpace axis and two HilbertSpace axes. Also raised if a selected transformed Hilbert-space side is not closed under the action of t, or if the momentum action of t is not one-to-one on the input momentum space.

TypeError

If the tensor dims do not have the required MomentumSpace/HilbertSpace/HilbertSpace structure.

Source code in src/qten/bands.py
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def bandtransform(
    t: Opr,
    tensor: Tensor,
    opt: Literal["left", "right", "both"] = "both",
) -> Tensor:
    r"""
    Apply a basis transform to a momentum-resolved operator tensor.

    The expected tensor shape is `(K, B_left, B_right)` where `K` is a
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] and
    `B_left`, `B_right` are
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] axes. This
    function applies the operator-induced basis transform on the selected
    Hilbert-space legs of the band tensor.

    For each transformed side, a k-dependent matrix is built from the action of
    `t` on the Hilbert-space basis and Fourier transforms that connect Bloch and
    real-space sectors.

    Mathematical action
    -------------------
    Let \(B_{\mathrm{left}}\) and \(B_{\mathrm{right}}\) be the input
    Hilbert-space bases and let the corresponding transformed bases be
    \(tB_{\mathrm{left}}\) and \(tB_{\mathrm{right}}\). After wrapping
    transformed sites back to the home unit cell, the finite Fourier transform
    contributes a momentum-dependent phase. The resulting basis-change matrices
    are denoted \(U_t^{(\mathrm{left})}(k)\) and
    \(U_t^{(\mathrm{right})}(k)\). When routed contributions are collapsed back
    onto the transformed momentum grid, the transformed band block is one of:

    `opt="left"`:
    \(H'(t k) = U_t^{(\mathrm{left})}(k)\,H(k)\)

    `opt="right"`:
    \(H'(t k) = H(k)\,U_t^{(\mathrm{right})}(k)^\dagger\)

    `opt="both"`:
    \(H'(t k) = U_t^{(\mathrm{left})}(k)\,H(k)\,U_t^{(\mathrm{right})}(k)^\dagger\)

    Momentum handling
    -----------------
    The action on [`Momentum`][qten.geometries.spatials.Momentum] is treated as
    a relabeling or permutation of sectors. For `opt="both"`, the output
    tensor carries the transformed momentum axis
    `mapped_kspace = {t @ k | k in kspace}`. For `opt="left"` and
    `opt="right"`, the implementation instead preserves a routed
    [`MomentumBlockSpace`][qten.symbolics.state_space.MomentumBlockSpace] pair
    axis so each source block remains attached to its transformed target
    sector. In either case, the selected Hilbert-space transforms are applied
    before any optional collapse back to a plain
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace].

    Notes
    -----
    This function accepts a general [`Opr`][qten.symbolics.hilbert_space.Opr], but not every [`Opr`][qten.symbolics.hilbert_space.Opr] is valid here.
    In practice, `t` must act coherently across the real-space and
    momentum-space labels carried by the tensor:

    `t @ k` must be defined for each
    [`Momentum`][qten.geometries.spatials.Momentum] in the first tensor axis.
    `t @ psi` must be defined for each
    [`U1Basis`][qten.symbolics.hilbert_space.U1Basis] in the Hilbert-space
    axes, in particular for the
    [`Offset`][qten.geometries.spatials.Offset] irrep stored inside each basis
    state.
    The Hilbert-space action and momentum action must be dual-compatible, so
    that the Fourier transform remains consistent after applying `t`.
    For each selected side, after applying
    [`FuncOpr(Offset, Offset.fractional)`][qten.symbolics.hilbert_space.FuncOpr],
    the transformed Hilbert space must have the same rays as the sampled input
    basis on that side. Otherwise the transformed basis does not close on that
    band leg and this function raises `ValueError`.

    Operators that only act on abstract [`U1Basis`][qten.symbolics.hilbert_space.U1Basis] values or only on [`Momentum`][qten.geometries.spatials.Momentum]
    values are not sufficient. The operator must provide matching actions on
    site offsets and crystal momentum.

    Parameters
    ----------
    t : Opr
        Operator to apply. It must satisfy the compatibility conditions
        described in the notes below.
    tensor : Tensor
        Momentum-space tensor with dims
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    opt : Literal["left", "right", "both"], optional
        Which matrix legs to transform. `"left"` applies only the left
        transform, `"right"` applies only the right transform, and `"both"`
        applies independent transforms on both sides. The default is `"both"`.

    Returns
    -------
    Tensor
        If `opt="both"`, returns the transformed tensor with a transformed
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] axis and
        transformed Hilbert-space matrix legs.
        If `opt="left"` or `opt="right"`, returns the corresponding one-sided
        routed intermediate as a
        [`MomentumBlockTensor`][qten.MomentumBlockTensor] whose leading
        [`MomentumBlockSpace`][qten.symbolics.state_space.MomentumBlockSpace]
        axis stores ordered pairs `(t @ k, k)` or `(k, t @ k)`,
        respectively. In those one-sided modes, the transformed momentum labels
        are carried on the pair axis rather than collapsed back to a plain
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace].

    Raises
    ------
    ValueError
        If `tensor` is not rank 3 with a
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] axis and
        two [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] axes.
        Also raised if a selected transformed Hilbert-space side is not closed
        under the action of `t`, or if the momentum action of `t` is not
        one-to-one on the input momentum space.
    TypeError
        If the tensor dims do not have the required
        `MomentumSpace/HilbertSpace/HilbertSpace` structure.
    """
    if opt not in ("left", "right", "both"):
        raise ValueError(f"opt must be 'left', 'right', or 'both', got {opt!r}.")
    if opt == "left":
        return cast(Tensor, get_band_transform(t, tensor, side="left") @ tensor)
    if opt == "right":
        right_transform = get_band_transform(t, tensor, side="right")
        return cast(Tensor, tensor @ right_transform.h(-2, -1))

    left_transform = get_band_transform(t, tensor, side="left")
    right_transform = get_band_transform(t, tensor, side="right")
    return cast(Tensor, left_transform @ tensor @ right_transform.h(-2, -1))

bandfold

bandfold(
    transform: BasisTransform,
    tensor: Tensor,
    opt: Literal["left", "right", "both"] = "both",
) -> Tensor

Fold a momentum-resolved band tensor into the Brillouin zone of a transformed lattice basis.

The input tensor is expected to have dimensions (MomentumSpace, HilbertSpace, HilbertSpace). The basis transformation is applied to the direct lattice underlying the MomentumSpace axis, which produces a new Brillouin zone and a corresponding momentum remapping. One or both HilbertSpace legs are enlarged to match the transformed unit cell, Fourier-space changes of basis are applied, and the momentum sectors are then gathered into the new momentum grid. If multiple basis states share the same site offset in the sampled Hilbert space, folding preserves all of them at the corresponding folded-cell site.

Mathematical action

A forward basis transform coarsens the direct lattice basis, so the reciprocal Brillouin zone shrinks and multiple old momenta fold onto one new momentum sector. If \(F_{\mathrm{left}}(k)\) and \(F_{\mathrm{right}}(k)\) are the Fourier-based change-of-basis maps on the selected tensor legs, then, after routed contributions are collapsed onto the folded momentum grid, the folded block is one of:

opt="left": \(H_{\mathrm{fold}}(k') \mathrel{+}= F_{\mathrm{left}}(k)^\dagger H(k)\)

opt="right": \(H_{\mathrm{fold}}(k') \mathrel{+}= H(k) F_{\mathrm{right}}(k)\)

opt="both": \(H_{\mathrm{fold}}(k') \mathrel{+}= F_{\mathrm{left}}(k)^\dagger H(k) F_{\mathrm{right}}(k)\)

with \(k' = \mathrm{fold}(k)\).

Parameters:

Name Type Description Default
transform BasisTransform

Basis change applied to the direct lattice associated with the momentum axis.

required
tensor Tensor

Rank-3 tensor with dimensions (MomentumSpace, HilbertSpace, HilbertSpace).

required
opt Literal['left', 'right', 'both']

Which matrix legs to fold. "left" folds only the left leg, "right" folds only the right leg, and "both" folds both legs. The default is "both".

'both'

Returns:

Type Description
Tensor

If opt="both", returns the folded tensor on the transformed MomentumSpace grid with both Hilbert-space legs expressed in the folded-cell basis. If opt="left" or opt="right", returns the corresponding one-sided routed intermediate as a MomentumBlockTensor whose leading MomentumBlockSpace axis stores ordered pairs (k_fold, k) or (k, k_fold), respectively. In those one-sided modes, accumulation onto the folded momentum grid is deferred until the complementary side is composed.

Raises:

Type Description
ValueError

If the tensor is not rank-3, if the momentum space is empty, or if the momentum axis does not belong to a single Brillouin zone. Also raised if the sampled Hilbert basis on a selected side has no states at a required unit-cell offset during the folding construction.

TypeError

If the momentum axis is not a MomentumSpace, if its underlying space is not a ReciprocalLattice, or if the selected Hilbert-space leg is not a HilbertSpace.

Source code in src/qten/bands.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
def bandfold(
    transform: BasisTransform,
    tensor: Tensor,
    opt: Literal["left", "right", "both"] = "both",
) -> Tensor:
    r"""
    Fold a momentum-resolved band tensor into the Brillouin zone of a
    transformed lattice basis.

    The input tensor is expected to have dimensions
    `(MomentumSpace, HilbertSpace, HilbertSpace)`. The basis transformation is
    applied to the direct lattice underlying the
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] axis, which
    produces a new Brillouin zone and a corresponding momentum remapping. One
    or both [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] legs
    are enlarged to match the transformed unit cell, Fourier-space changes of
    basis are applied, and the momentum sectors are then gathered into the new
    momentum grid. If multiple basis states share the same site offset in the
    sampled Hilbert space, folding preserves all of them at the corresponding
    folded-cell site.

    Mathematical action
    -------------------
    A forward basis transform coarsens the direct lattice basis, so the
    reciprocal Brillouin zone shrinks and multiple old momenta fold onto one
    new momentum sector. If \(F_{\mathrm{left}}(k)\) and
    \(F_{\mathrm{right}}(k)\) are the Fourier-based change-of-basis maps on the
    selected tensor legs, then, after routed contributions are collapsed onto
    the folded momentum grid, the folded block is one of:

    `opt="left"`:
    \(H_{\mathrm{fold}}(k') \mathrel{+}= F_{\mathrm{left}}(k)^\dagger H(k)\)

    `opt="right"`:
    \(H_{\mathrm{fold}}(k') \mathrel{+}= H(k) F_{\mathrm{right}}(k)\)

    `opt="both"`:
    \(H_{\mathrm{fold}}(k') \mathrel{+}= F_{\mathrm{left}}(k)^\dagger H(k) F_{\mathrm{right}}(k)\)

    with \(k' = \mathrm{fold}(k)\).

    Parameters
    ----------
    transform : BasisTransform
        Basis change applied to the direct lattice associated with the momentum
        axis.
    tensor : Tensor
        Rank-3 tensor with dimensions
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    opt : Literal["left", "right", "both"], optional
        Which matrix legs to fold. `"left"` folds only the left leg,
        `"right"` folds only the right leg, and `"both"` folds both legs. The
        default is `"both"`.

    Returns
    -------
    Tensor
        If `opt="both"`, returns the folded tensor on the transformed
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] grid with
        both Hilbert-space legs expressed in the folded-cell basis.
        If `opt="left"` or `opt="right"`, returns the corresponding one-sided
        routed intermediate as a
        [`MomentumBlockTensor`][qten.MomentumBlockTensor] whose leading
        [`MomentumBlockSpace`][qten.symbolics.state_space.MomentumBlockSpace]
        axis stores ordered pairs `(k_fold, k)` or `(k, k_fold)`,
        respectively. In those one-sided modes, accumulation onto the folded
        momentum grid is deferred until the complementary side is composed.

    Raises
    ------
    ValueError
        If the tensor is not rank-3, if the momentum space is empty, or if the
        momentum axis does not belong to a single Brillouin zone. Also raised
        if the sampled Hilbert basis on a selected side has no states at a
        required unit-cell offset during the folding construction.
    TypeError
        If the momentum axis is not a
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace], if its
        underlying space is not a
        [`ReciprocalLattice`][qten.geometries.spatials.ReciprocalLattice], or
        if the selected Hilbert-space leg is not a
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace].
    """
    if opt not in ("left", "right", "both"):
        raise ValueError(f"opt must be 'left', 'right', or 'both', got {opt!r}.")
    if opt == "left":
        return cast(Tensor, get_band_fold(transform, tensor, side="left") @ tensor)
    if opt == "right":
        right_fold = get_band_fold(transform, tensor, side="right")
        return cast(Tensor, tensor @ right_fold.h(-2, -1))

    left_fold = get_band_fold(transform, tensor, side="left")
    right_fold = get_band_fold(transform, tensor, side="right")
    return cast(Tensor, left_fold @ tensor @ right_fold.h(-2, -1))

bandunfold

bandunfold(
    inverse_transform: InverseBasisTransform, tensor: Tensor
) -> Tensor

Unfold a folded momentum-resolved band tensor using an inverse basis transform.

The input is expected to have dimensions (MomentumSpace, HilbertSpace, HilbertSpace) where the MomentumSpace axis lives on a transformed (folded) Brillouin zone. The inverse transform maps that folded lattice back to the primitive one and recovers dimensions (K_primitive, B_primitive, B_primitive).

Mathematical action

Unfolding routes each primitive momentum \(k\) to its parent folded momentum \(\bar{k}\), gathers \(H_{\mathrm{fold}}(\bar{k})\), and then projects it back to the primitive-cell basis with a Fourier map \(F(k)\): \(H_{\mathrm{unfold}}(k) = F(k)\,H_{\mathrm{fold}}(\bar{k})\,F(k)^\dagger\). In code, the parent-sector lookup is tensor.data[k_indices.data], and the final basis projection is f @ gathered @ f.h(-2, -1).

Parameters:

Name Type Description Default
inverse_transform InverseBasisTransform

Inverse basis transform that maps the folded direct lattice back to the primitive lattice.

required
tensor Tensor

Rank-3 folded band tensor with dimensions (MomentumSpace, HilbertSpace, HilbertSpace).

required

Returns:

Type Description
Tensor

Unfolded tensor on the primitive Brillouin-zone MomentumSpace grid with primitive HilbertSpace matrix axes.

Raises:

Type Description
TypeError

If inverse_transform is not an InverseBasisTransform, if the tensor axes do not have the required symbolic space types, or if the momentum axis is not backed by a ReciprocalLattice.

ValueError

If tensor is not rank 3, if the momentum space is empty, or if the momentum axis mixes incompatible reciprocal lattices.

Source code in src/qten/bands.py
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
def bandunfold(
    inverse_transform: InverseBasisTransform,
    tensor: Tensor,
) -> Tensor:
    r"""
    Unfold a folded momentum-resolved band tensor using an inverse basis transform.

    The input is expected to have dimensions `(MomentumSpace, HilbertSpace,
    HilbertSpace)` where the
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] axis lives on a
    transformed (folded) Brillouin zone. The inverse transform maps that folded
    lattice back to the primitive one and recovers dimensions
    `(K_primitive, B_primitive, B_primitive)`.

    Mathematical action
    -------------------
    Unfolding routes each primitive momentum \(k\) to its parent folded
    momentum \(\bar{k}\), gathers \(H_{\mathrm{fold}}(\bar{k})\), and then
    projects it back to the primitive-cell basis with a Fourier map \(F(k)\):
    \(H_{\mathrm{unfold}}(k)
    = F(k)\,H_{\mathrm{fold}}(\bar{k})\,F(k)^\dagger\). In code, the parent-sector lookup is `tensor.data[k_indices.data]`, and the
    final basis projection is `f @ gathered @ f.h(-2, -1)`.

    Parameters
    ----------
    inverse_transform : InverseBasisTransform
        Inverse basis transform that maps the folded direct lattice back to the
        primitive lattice.
    tensor : Tensor
        Rank-3 folded band tensor with dimensions
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.

    Returns
    -------
    Tensor
        Unfolded tensor on the primitive Brillouin-zone
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] grid with
        primitive [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace]
        matrix axes.

    Raises
    ------
    TypeError
        If `inverse_transform` is not an
        [`InverseBasisTransform`][qten.geometries.basis_transform.InverseBasisTransform],
        if the tensor axes do not have the required symbolic space types, or if
        the momentum axis is not backed by a
        [`ReciprocalLattice`][qten.geometries.spatials.ReciprocalLattice].
    ValueError
        If `tensor` is not rank 3, if the momentum space is empty, or if the
        momentum axis mixes incompatible reciprocal lattices.
    """
    if not isinstance(inverse_transform, InverseBasisTransform):
        raise TypeError(
            "bandunfold requires InverseBasisTransform, "
            f"but got {type(inverse_transform)}"
        )
    if tensor.rank() != 3:
        raise ValueError(
            f"Input tensor must be of rank 3, but has rank {tensor.rank()}"
        )
    if not isinstance(tensor.dims[0], MomentumSpace):
        raise TypeError(
            "The first dimension of the tensor must be a MomentumSpace, "
            f"but is of type {type(tensor.dims[0])}"
        )
    if not isinstance(tensor.dims[1], HilbertSpace):
        raise TypeError(
            "The second dimension of the tensor must be a HilbertSpace, "
            f"but is of type {type(tensor.dims[1])}"
        )
    if not isinstance(tensor.dims[2], HilbertSpace):
        raise TypeError(
            "The third dimension of the tensor must be a HilbertSpace, "
            f"but is of type {type(tensor.dims[2])}"
        )

    k_space = cast(MomentumSpace, tensor.dims[0])
    if not k_space.elements():
        raise ValueError("MomentumSpace is empty")
    lattice_set = set(map(lambda k: k.space, k_space))
    if len(lattice_set) != 1:
        raise ValueError("Invalid BZ")
    folded_reciprocal_lattice = lattice_set.pop()
    if not isinstance(folded_reciprocal_lattice, ReciprocalLattice):
        raise TypeError(
            "Space of momentum should be ReciprocalLattice, but got "
            f"{type(folded_reciprocal_lattice)}"
        )
    folded_reciprocal_lattice = cast(ReciprocalLattice, folded_reciprocal_lattice)
    folded_lattice = folded_reciprocal_lattice.dual

    primitive_lattice = cast(Lattice, inverse_transform(folded_lattice))

    folded_hilbert = cast(HilbertSpace, tensor.dims[2])

    primitive_reciprocal_lattice = primitive_lattice.dual
    primitive_k_space = brillouin_zone(primitive_reciprocal_lattice)

    rebased_states = []
    for psi in folded_hilbert:
        u1_psi = cast(U1Basis, psi)
        rebased_states.append(
            u1_psi.replace(u1_psi.irrep_of(Offset).rebase(primitive_lattice))
        )
    rebased_hilbert = HilbertSpace.new(rebased_states)

    primitive_states: "OrderedDict[U1Basis, int]" = OrderedDict()
    for psi in rebased_states:
        primitive_state = psi.replace(psi.irrep_of(Offset).fractional())
        if primitive_state not in primitive_states:
            primitive_states[primitive_state] = len(primitive_states)
    primitive_hilbert = HilbertSpace(structure=primitive_states)

    # Route each primitive-k sector to its folded-k parent.
    precision = get_precision_config()
    primitive_basis_np = np.array(
        primitive_reciprocal_lattice.basis.evalf(), dtype=precision.np_float
    )
    folded_basis_np = np.array(
        folded_reciprocal_lattice.basis.evalf(), dtype=precision.np_float
    )
    M_rebase = np.linalg.solve(folded_basis_np, primitive_basis_np)
    k_indices = _momentum_match_indices(
        primitive_k_space, k_space, M_rebase, device=tensor.device
    )

    gathered = Tensor(
        data=tensor.data[k_indices.data],
        dims=(primitive_k_space, tensor.dims[1], tensor.dims[2]),
    )
    for dim in (1, 2):
        if gathered.dims[dim] == folded_hilbert:
            gathered = gathered.replace_dim(dim, rebased_hilbert)

    f = fourier_transform(
        primitive_k_space, primitive_hilbert, rebased_hilbert, device=tensor.device
    )
    vratio = np.sqrt(rebased_hilbert.dim / primitive_hilbert.dim)
    f = f / vratio
    unfolded = f @ gathered @ f.h(-2, -1)
    return unfolded

bandcounts

bandcounts(tensor: Tensor) -> Tensor

Count nonzero columns in each momentum-sector matrix.

The input tensor is expected to have dimensions (MomentumSpace, HilbertSpace, StateSpace). For each momentum sector, the trailing two axes are treated as a matrix with rows labelled by the HilbertSpace axis and columns labelled by the trailing StateSpace axis. A column is counted if any entry in that column is nonzero.

Parameters:

Name Type Description Default
tensor Tensor

Rank-3 tensor with dimensions (MomentumSpace, HilbertSpace, StateSpace).

required

Returns:

Type Description
Tensor

Integer-valued tensor with dimensions (MomentumSpace,) whose entries are the nonzero-column counts of the corresponding momentum blocks.

Raises:

Type Description
ValueError

If tensor is not rank 3.

TypeError

If the tensor axes are not MomentumSpace, HilbertSpace, and StateSpace, respectively.

Source code in src/qten/bands.py
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
def bandcounts(tensor: Tensor) -> Tensor:
    r"""
    Count nonzero columns in each momentum-sector matrix.

    The input tensor is expected to have dimensions
    `(MomentumSpace, HilbertSpace, StateSpace)`. For each momentum sector, the
    trailing two axes are treated as a matrix with rows labelled by the
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] axis and
    columns labelled by the trailing
    [`StateSpace`][qten.symbolics.state_space.StateSpace] axis. A column is
    counted if any entry in that column is nonzero.

    Parameters
    ----------
    tensor : Tensor
        Rank-3 tensor with dimensions `(MomentumSpace, HilbertSpace,
        StateSpace)`.

    Returns
    -------
    Tensor
        Integer-valued tensor with dimensions `(MomentumSpace,)` whose entries
        are the nonzero-column counts of the corresponding momentum blocks.

    Raises
    ------
    ValueError
        If `tensor` is not rank 3.
    TypeError
        If the tensor axes are not `MomentumSpace`, `HilbertSpace`, and
        `StateSpace`, respectively.
    """
    if tensor.rank() != 3:
        raise ValueError(
            f"Input tensor must be of rank 3, but has rank {tensor.rank()}"
        )
    if not isinstance(tensor.dims[0], MomentumSpace):
        raise TypeError("The first dimension of the tensor must be a MomentumSpace.")
    if not isinstance(tensor.dims[1], HilbertSpace):
        raise TypeError("The second dimension of the tensor must be a HilbertSpace.")
    if not isinstance(tensor.dims[2], StateSpace):
        raise TypeError("The third dimension of the tensor must be a StateSpace.")

    kspace = cast(MomentumSpace, tensor.dims[0])
    nonzero_columns = torch.any(tensor.data != 0, dim=1)
    counts = nonzero_columns.sum(dim=1, dtype=torch.int64)
    return Tensor(data=counts, dims=(kspace,))

bandfillings

bandfillings(tensor: Tensor, frac: float) -> Tensor

Return eigenvectors for occupied bands up to a filling fraction.

The input tensor is expected to have dimensions (MomentumSpace, HilbertSpace, HilbertSpace), where the MomentumSpace axis indexes momentum sectors and the two HilbertSpace axes form the Hamiltonian matrix at each momentum. The tensor is diagonalized at each momentum, then eigenvectors with energies below the global filling threshold are packed into an output IndexSpace.

Mathematical convention

Each momentum block is diagonalized as \(H(k) V(k) = V(k) E(k)\), and the eigenvectors whose energies fall below the global filling threshold are retained. If frac = f, the target number of occupied states is

\(N_{\mathrm{occ}} = \left\lfloor f\,N_k\,N_b \right\rfloor\), where \(N_k\) is the number of momentum sectors and \(N_b\) is the number of bands per sector. Degenerate states at the threshold are included together.

Degenerate threshold behavior

If one state in a degenerate set is filled, all states in that set are filled. The output index dimension is therefore the maximum number of filled states over all momentum sectors, and sectors with fewer filled states are padded with zeros.

Parameters:

Name Type Description Default
tensor Tensor

Band-resolved tensor with dimensions (MomentumSpace, HilbertSpace, HilbertSpace).

required
frac float

Filling fraction in the inclusive range [0, 1].

required

Returns:

Type Description
Tensor

Eigenvector tensor with dimensions (MomentumSpace, HilbertSpace, IndexSpace). For each momentum sector, columns along IndexSpace contain the eigenvectors selected as filled. The IndexSpace size is the largest filled count among all momentum sectors; sectors with fewer filled bands are padded with zero columns.

Raises:

Type Description
TypeError

If the tensor axes are not MomentumSpace, HilbertSpace, and HilbertSpace, respectively.

ValueError

If tensor is not rank 3. Also raised if frac is outside the inclusive range [0, 1].

Source code in src/qten/bands.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
def bandfillings(tensor: Tensor, frac: float) -> Tensor:
    r"""
    Return eigenvectors for occupied bands up to a filling fraction.

    The input tensor is expected to have dimensions
    `(MomentumSpace, HilbertSpace, HilbertSpace)`, where the
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] axis indexes
    momentum sectors and the two
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] axes form the
    Hamiltonian matrix at each momentum. The tensor is diagonalized at each
    momentum, then eigenvectors with energies below the global filling
    threshold are packed into an output
    [`IndexSpace`][qten.symbolics.state_space.IndexSpace].

    Mathematical convention
    -----------------------
    Each momentum block is diagonalized as \(H(k) V(k) = V(k) E(k)\), and the eigenvectors whose energies fall below the global filling threshold
    are retained. If `frac = f`, the target number of occupied states is

    \(N_{\mathrm{occ}} = \left\lfloor f\,N_k\,N_b \right\rfloor\), where \(N_k\) is the number of momentum sectors and \(N_b\) is the number
    of bands per sector. Degenerate states at the threshold are included
    together.

    Degenerate threshold behavior
    -----------------------------
    If one state in a degenerate set is filled, all states in that set are
    filled. The output index dimension is therefore the maximum number of filled
    states over all momentum sectors, and sectors with fewer filled states are
    padded with zeros.

    Parameters
    ----------
    tensor : Tensor
        Band-resolved tensor with dimensions
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    frac : float
        Filling fraction in the inclusive range `[0, 1]`.

    Returns
    -------
    Tensor
        Eigenvector tensor with dimensions `(MomentumSpace, HilbertSpace,
        IndexSpace)`. For each momentum sector, columns along `IndexSpace`
        contain the eigenvectors selected as filled. The `IndexSpace` size is
        the largest filled count among all momentum sectors; sectors with fewer
        filled bands are padded with zero columns.

    Raises
    ------
    TypeError
        If the tensor axes are not `MomentumSpace`, `HilbertSpace`, and
        `HilbertSpace`, respectively.
    ValueError
        If `tensor` is not rank 3. Also raised if `frac` is outside the
        inclusive range `[0, 1]`.
    """
    if tensor.rank() != 3:
        raise ValueError(
            f"Input tensor must be of rank 3, but has rank {tensor.rank()}"
        )
    if not isinstance(tensor.dims[0], MomentumSpace):
        raise TypeError("The first dimension of the tensor must be a MomentumSpace.")
    if not isinstance(tensor.dims[1], HilbertSpace):
        raise TypeError("The second dimension of the tensor must be a HilbertSpace.")
    if not isinstance(tensor.dims[2], HilbertSpace):
        raise TypeError("The third dimension of the tensor must be a HilbertSpace.")
    if not (0.0 <= frac <= 1.0):
        raise ValueError(f"Filling fraction must be between 0 and 1, got {frac}")

    kspace = cast(MomentumSpace, tensor.dims[0])
    band_space = cast(HilbertSpace, tensor.dims[1])
    eigvals, eigvecs = eigh(tensor)

    nk, nbands = eigvals.data.shape
    total_states = nk * nbands
    target_fill = int(np.floor(frac * total_states + 1e-12))

    if target_fill <= 0:
        return Tensor(
            data=eigvecs.data[..., :0],
            dims=(kspace, band_space, IndexSpace.linear(0)),
        )
    if target_fill >= total_states:
        return Tensor(
            data=eigvecs.data,
            dims=(kspace, band_space, IndexSpace.linear(nbands)),
        )

    flat_vals = eigvals.data.reshape(-1)
    threshold = torch.kthvalue(flat_vals, target_fill).values
    eps = torch.finfo(eigvals.data.dtype).eps
    tol = (abs(threshold).clamp_min(1.0) * eps * max(nbands, 1) * 8).to(
        eigvals.data.dtype
    )
    filled = eigvals.data <= (threshold + tol)

    counts = filled.sum(dim=1)
    max_fill = int(counts.max().item())
    out_dim = IndexSpace.linear(max_fill)

    order = torch.argsort(filled.to(torch.int8), dim=1, descending=True, stable=True)
    packed = torch.gather(
        eigvecs.data,
        2,
        order[:, None, :].expand(-1, eigvecs.data.shape[1], -1),
    )[..., :max_fill]

    valid = (
        torch.arange(max_fill, device=counts.device)[None, :] < counts[:, None]
    ).to(packed.dtype)
    packed = packed * valid[:, None, :]

    return Tensor(data=packed, dims=(kspace, band_space, out_dim))

svd_projection

svd_projection(
    target: Tensor[Any],
    source: Tensor[Any],
    svd_threshold: float = 0.1,
    infer_lattice: bool = False,
) -> Tensor[Any]

Align target states to a source-defined gauge via sectorwise SVD.

This function computes the sectorwise overlap between target and source states, extracts the polar/unitary factor of that overlap via SVD, and rotates the target columns into the source-selected gauge.

Mathematical convention

For each momentum sector \(k\), collect the target columns into a matrix \(T(k)\) and the source columns into a matrix \(S(k)\). If the target Hilbert dimension is \(N\), the target rank is \(r_t\), and the source rank is \(r_s\), then \(T(k) \in \mathbb{C}^{N \times r_t}\) and \(S(k) \in \mathbb{C}^{N \times r_s}\).

The method proceeds sector by sector:

  1. Form the overlap matrix \(M(k) = T(k)^\dagger S(k)\), so \(M(k) \in \mathbb{C}^{r_t \times r_s}\).

  2. Compute the singular value decomposition \(M(k) = U(k)\,\Sigma(k)\,V(k)^\dagger\).

  3. Discard the singular values and keep only the unitary/polar factor \(Q(k) = U(k)\,V(k)^\dagger\).

  4. Rotate the target states by that factor: \(T_{\mathrm{proj}}(k) = T(k)\,Q(k)\).

This output has the same row space as the target states, but its column gauge is chosen to optimally match the source states in the orthogonal Procrustes sense. Equivalently, \(Q(k)\) solves \(\min_Q \|T(k)Q - S(k)\|_F\) over partial isometries \(Q\) of the form \(Q = U V^\dagger\) induced by the SVD of \(T(k)^\dagger S(k)\).

When \(r_t \neq r_s\), the overlap \(M(k)\) is rectangular, so the method still makes sense: it returns the best SVD-induced alignment from the target column space toward the source column space without requiring equal rank.

If either target or source uses zero-padded columns to represent an inconsistent number of states across the Brillouin zone, those padded columns are ignored on a per-momentum basis when forming the SVD. The projection therefore acts only on the intersection of nonzero target columns and nonzero source columns at each momentum sector.

In the default branch, or whenever the source metadata is insufficient to infer a lattice-backed column space, the result is a plain rank-3 Tensor with the input MomentumSpace axis preserved.

If infer_lattice=True and the source column space is a HilbertSpace carrying Offset labels, the function tries to build a lattice description directly from those labels.

A simple example is:

  • suppose the source-side basis contains states such as \(|r_1\rangle \otimes |\alpha\rangle\), \(|r_2\rangle \otimes |\beta\rangle\), \(|r_1\rangle \otimes |\gamma\rangle\);
  • then the new unit cell is built from the distinct site positions \(r_1, r_2\) in the order they first appear;
  • the extra labels \(|\alpha\rangle\), \(|\beta\rangle\), \(|\gamma\rangle\) are kept, but they are now understood as living on that newly built unit cell.

More concretely, the construction:

  • rebases the source offsets onto the direct lattice of the input momentum grid;
  • converts those offsets to fractional coordinates;
  • uses the distinct fractional positions as the sites of a new unit cell;
  • keeps the same overall lattice basis and boundary conditions, so only the unit-cell contents are being rebuilt.

In that branch, the return value becomes a MomentumBlockTensor. Its leading MomentumBlockSpace stores pairs (k_old, k_new), where k_old is the original momentum sector from the input tensor and k_new is the momentum sector in the newly created reciprocal lattice with the same fractional momentum coordinate.

The last two tensor legs also become more specific:

  • the middle leg stays in the original target/band Hilbert space;
  • the last leg becomes the Bloch space built from the newly created lattice, so its basis states now refer to the newly constructed unit-cell sites rather than the original source labels.

If this lattice inference cannot be carried out, the function simply falls back to the plain rank-3 projected tensor.

Parameters:

Name Type Description Default
target Tensor

Target states with dims (MomentumSpace, HilbertSpace, IndexSpace).

required
source Tensor

Source states with dims (MomentumSpace, HilbertSpace, D), where D may be an IndexSpace or a HilbertSpace.

required
svd_threshold float

Warn if the minimum singular value of the overlap drops below this threshold, which signals linearly dependent source states or poor projection onto the target subspace after zero-padded columns have been ignored.

0.1
infer_lattice bool

If True, try to build a new unit cell from the source-side offset labels by taking their distinct fractional positions. When this succeeds, the output is no longer a plain (k, band, column) tensor: it becomes a MomentumBlockTensor whose momentum axis records how each original momentum sector matches a momentum sector in the reciprocal lattice of that new unit cell, and whose final Hilbert-space leg is rebuilt on that lattice. If inference fails, the function falls back to the plain-tensor result.

False

Returns:

Type Description
Tensor

Projected states. The fallback result has dims (MomentumSpace, HilbertSpace, D). The lattice-aware result is a MomentumBlockTensor with dims (MomentumBlockSpace(k_old, k_new), HilbertSpace, InferredHilbertSpace), where k_old is the original momentum label, k_new is the momentum label in the reciprocal lattice built from the new unit cell, and InferredHilbertSpace is the source-side Bloch space rewritten on that lattice.

Raises:

Type Description
ValueError

If either input tensor is not rank 3.

TypeError

If either input tensor does not have MomentumSpace/HilbertSpace/... leading dimensions.

Source code in src/qten/bands.py
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
def svd_projection(
    target: Tensor[Any],
    source: Tensor[Any],
    svd_threshold: float = 1e-1,
    infer_lattice: bool = False,
) -> Tensor[Any]:
    r"""
    Align target states to a source-defined gauge via sectorwise SVD.

    This function computes the sectorwise overlap between target and source
    states, extracts the polar/unitary factor of that overlap via SVD, and
    rotates the target columns into the source-selected gauge.

    Mathematical convention
    -----------------------
    For each momentum sector \(k\), collect the target columns into a matrix
    \(T(k)\) and the source columns into a matrix \(S(k)\). If the target
    Hilbert dimension is \(N\), the target rank is \(r_t\), and the source
    rank is \(r_s\), then
    \(T(k) \in \mathbb{C}^{N \times r_t}\) and
    \(S(k) \in \mathbb{C}^{N \times r_s}\).

    The method proceeds sector by sector:

    1. Form the overlap matrix
       \(M(k) = T(k)^\dagger S(k)\), so
       \(M(k) \in \mathbb{C}^{r_t \times r_s}\).

    2. Compute the singular value decomposition
       \(M(k) = U(k)\,\Sigma(k)\,V(k)^\dagger\).

    3. Discard the singular values and keep only the unitary/polar factor
       \(Q(k) = U(k)\,V(k)^\dagger\).

    4. Rotate the target states by that factor:
       \(T_{\mathrm{proj}}(k) = T(k)\,Q(k)\).

    This output has the same row space as the target states, but its column
    gauge is chosen to optimally match the source states in the orthogonal
    Procrustes sense. Equivalently, \(Q(k)\) solves
    \(\min_Q \|T(k)Q - S(k)\|_F\) over partial isometries \(Q\) of the form
    \(Q = U V^\dagger\) induced by the SVD of \(T(k)^\dagger S(k)\).

    When \(r_t \neq r_s\), the overlap \(M(k)\) is rectangular, so the method
    still makes sense: it returns the best SVD-induced alignment from the
    target column space toward the source column space without requiring equal
    rank.

    If either `target` or `source` uses zero-padded columns to represent
    an inconsistent number of states across the Brillouin zone, those padded
    columns are ignored on a per-momentum basis when forming the SVD. The
    projection therefore acts only on the intersection of nonzero target
    columns and nonzero source columns at each momentum sector.

    In the default branch, or whenever the source metadata is insufficient to
    infer a lattice-backed column space, the result is a plain rank-3
    [`Tensor`][qten.linalg.tensors.Tensor] with the input
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] axis preserved.

    If `infer_lattice=True` and the source column space is a
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] carrying
    [`Offset`][qten.geometries.spatials.Offset] labels, the function tries to
    build a lattice description directly from those labels.

    A simple example is:

    - suppose the source-side basis contains states such as
      \(|r_1\rangle \otimes |\alpha\rangle\),
      \(|r_2\rangle \otimes |\beta\rangle\),
      \(|r_1\rangle \otimes |\gamma\rangle\);
    - then the new unit cell is built from the distinct site positions
      \(r_1, r_2\) in the order they first appear;
    - the extra labels \(|\alpha\rangle\), \(|\beta\rangle\),
      \(|\gamma\rangle\) are kept, but they are now understood as living on
      that newly built unit cell.

    More concretely, the construction:

    - rebases the source offsets onto the direct lattice of the input momentum
      grid;
    - converts those offsets to fractional coordinates;
    - uses the distinct fractional positions as the sites of a new unit cell;
    - keeps the same overall lattice basis and boundary conditions, so only the
      unit-cell contents are being rebuilt.

    In that branch, the return value becomes a
    [`MomentumBlockTensor`][qten.MomentumBlockTensor]. Its leading
    [`MomentumBlockSpace`][qten.symbolics.state_space.MomentumBlockSpace]
    stores pairs `(k_old, k_new)`, where `k_old` is the original momentum
    sector from the input tensor and `k_new` is the momentum sector in the
    newly created reciprocal lattice with the same fractional momentum
    coordinate.

    The last two tensor legs also become more specific:

    - the middle leg stays in the original target/band Hilbert space;
    - the last leg becomes the Bloch space built from the newly created
      lattice, so its basis states now refer to the newly constructed unit-cell
      sites rather than the original source labels.

    If this lattice inference cannot be carried out, the function simply falls
    back to the plain rank-3 projected tensor.

    Parameters
    ----------
    target : Tensor
        Target states with dims
        `(MomentumSpace, HilbertSpace, IndexSpace)`.
    source : Tensor
        Source states with dims `(MomentumSpace, HilbertSpace, D)`, where `D`
        may
        be an [`IndexSpace`][qten.symbolics.state_space.IndexSpace] or a
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace].
    svd_threshold : float, optional
        Warn if the minimum singular value of the overlap drops below this
        threshold, which signals linearly dependent source states or poor projection
        onto the target subspace after zero-padded columns have been ignored.
    infer_lattice : bool, optional
        If `True`, try to build a new unit cell from the source-side offset
        labels by taking their distinct fractional positions. When this
        succeeds, the output is no longer a plain `(k, band, column)` tensor:
        it becomes a
        [`MomentumBlockTensor`][qten.MomentumBlockTensor] whose momentum axis
        records how each original momentum sector matches a momentum sector in
        the reciprocal lattice of that new unit cell, and whose final
        Hilbert-space leg is rebuilt on that lattice. If inference fails, the
        function falls back to the plain-tensor result.

    Returns
    -------
    Tensor
        Projected states. The fallback result has dims
        `(MomentumSpace, HilbertSpace, D)`. The lattice-aware result is a
        [`MomentumBlockTensor`][qten.MomentumBlockTensor] with dims
        `(MomentumBlockSpace(k_old, k_new), HilbertSpace, InferredHilbertSpace)`,
        where `k_old` is the original momentum label, `k_new` is the momentum
        label in the reciprocal lattice built from the new unit cell, and
        `InferredHilbertSpace` is the source-side Bloch space rewritten on that
        lattice.

    Raises
    ------
    ValueError
        If either input tensor is not rank 3.
    TypeError
        If either input tensor does not have
        `MomentumSpace/HilbertSpace/...` leading dimensions.
    """
    if target.rank() != 3 or source.rank() != 3:
        raise ValueError("Both target and source must be rank-3 Tensors.")
    if not isinstance(target.dims[0], MomentumSpace):
        raise TypeError("The first dimension of target must be a MomentumSpace.")
    if not isinstance(source.dims[0], MomentumSpace):
        raise TypeError("The first dimension of source must be a MomentumSpace.")
    if not isinstance(target.dims[1], HilbertSpace):
        raise TypeError("The second dimension of target must be a HilbertSpace.")
    if not isinstance(source.dims[1], HilbertSpace):
        raise TypeError("The second dimension of source must be a HilbertSpace.")

    eps = torch.finfo(target.data.real.dtype).eps

    def _valid_column_mask(data: torch.Tensor) -> torch.Tensor:
        norms = (data.abs() ** 2).sum(dim=1)
        if not norms.numel():
            return torch.zeros_like(norms, dtype=torch.bool)
        scale = norms.amax(dim=1, keepdim=True).clamp_min(1.0)
        # Zero-padded columns are expected to have vanishing norm compared to
        # genuine state columns. Use a noticeably looser threshold than machine
        # epsilon so tiny numerical leakage does not resurrect padded bands.
        tol = scale * (eps**0.5) * max(data.shape[1], 1) * 8
        return norms > tol

    valid_target_mask = _valid_column_mask(target.data)
    valid_source_mask = _valid_column_mask(source.data)

    def _pack_active_columns(
        data: torch.Tensor, mask: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        order = torch.argsort(mask.to(torch.int8), dim=1, descending=True, stable=True)
        packed = data.gather(2, order[:, None, :].expand(-1, data.shape[1], -1))
        packed_mask = mask.gather(1, order)
        packed = packed * packed_mask[:, None, :].to(dtype=data.dtype)
        return packed, packed_mask.sum(dim=1), order

    packed_target, target_counts, _ = _pack_active_columns(
        target.data, valid_target_mask
    )
    packed_source, source_counts, source_order = _pack_active_columns(
        source.data, valid_source_mask
    )

    projected_packed = target.data.new_zeros(
        target.data.shape[0],
        target.data.shape[1],
        source.data.shape[2],
    )
    min_svd_val = float("inf")
    count_pairs = torch.stack((target_counts, source_counts), dim=1)

    for target_count, source_count in torch.unique(count_pairs, dim=0):
        n_target = int(target_count.item())
        n_source = int(source_count.item())
        if n_target == 0 or n_source == 0:
            continue

        pair_mask = (target_counts == target_count) & (source_counts == source_count)
        local_target = packed_target[pair_mask, :, :n_target]
        local_source = packed_source[pair_mask, :, :n_source]
        overlap = local_target.conj().transpose(1, 2) @ local_source
        u_data, s_data, vh_data = torch.linalg.svd(overlap, full_matrices=False)
        if s_data.numel():
            min_svd_val = min(min_svd_val, float(s_data.min().item()))

        # Match the Julia wannierprojection contract: ignore padded zero
        # columns, warn on small singular values, and always build the active
        # block from the full thin polar factor of the overlap. This preserves
        # the active source column count while giving an effective support of
        # min(rank(target), rank(source)) sectorwise.
        projected_packed[pair_mask, :, :n_source] = local_target @ (u_data @ vh_data)

    projected_data = target.data.new_zeros(
        target.data.shape[0],
        target.data.shape[1],
        source.data.shape[2],
    )
    projected_data.scatter_(
        2,
        source_order[:, None, :].expand(-1, projected_data.shape[1], -1),
        projected_packed,
    )

    if min_svd_val < svd_threshold:
        warnings.warn(
            f"Precarious SVD projection with minimum singular value of {min_svd_val:.4g}",
            UserWarning,
            stacklevel=2,
        )

    projected = Tensor(
        data=projected_data,
        dims=(target.dims[0], target.dims[1], source.dims[2]),
    )

    if not infer_lattice or not isinstance(source.dims[2], HilbertSpace):
        return projected

    bridge = _infer_wannier_bridge(projected, cast(HilbertSpace, source.dims[2]))
    if bridge is None:
        return projected

    return cast(Tensor[Any], projected @ bridge)

bandselect

bandselect(
    tensor: Tensor,
    **kwargs: Dict[
        str,
        Union[
            slice,
            Tuple[int, ...],
            Tuple[float, float],
            Callable[[float], bool],
        ],
    ],
) -> Dict[str, Tensor]

Select specific bands from a band-resolved Tensor based on criteria provided in kwargs.

The input Tensor is diagonalized at each MomentumSpace sector. Each keyword argument defines one named selection criterion, and the returned dictionary maps each name to a tensor containing the matching eigenvectors. Outputs have dimensions (MomentumSpace, HilbertSpace, IndexSpace), where HilbertSpace labels the band basis and IndexSpace labels the selected states for each criterion.

Mathematical convention

For each momentum sector, \(H(k) v_n(k) = \epsilon_n(k) v_n(k)\), and each criterion selects a subset of band labels \(n\). The returned tensor packs the matching eigenvectors \(v_n(k)\) into an IndexSpace, padding sectors with fewer matches by zero columns.

Supported criteria
  • slice: select bands by sorted energy index, such as slice(0, 2) for the two lowest-energy bands.
  • Tuple[int, ...]: select explicit sorted band indices, such as (0, 2) for the lowest and third-lowest bands.
  • Tuple[float, float]: select an inclusive energy range.
  • Callable[[float], bool]: select energies for which the callable returns True.

If a criterion matches no bands in all momentum sectors, the corresponding output tensor has an IndexSpace of dimension zero.

Parameters:

Name Type Description Default
tensor Tensor

Band-resolved tensor with dimensions (MomentumSpace, HilbertSpace, HilbertSpace).

required
kwargs Dict[str, Union[slice, Tuple[int, ...], Tuple[float, float], Callable[[float], bool]]]

Named band-selection criteria.

{}

Returns:

Type Description
Dict[str, Tensor]

Mapping from criterion name to selected eigenvector tensor with dimensions (MomentumSpace, HilbertSpace, IndexSpace).

Raises:

Type Description
TypeError

If the tensor axes are not (MomentumSpace, HilbertSpace, HilbertSpace), or if a criterion has an unsupported type.

ValueError

If tensor is not rank 3.

IndexError

If an explicit integer band index is outside the available band range.

Source code in src/qten/bands.py
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
def bandselect(
    tensor: Tensor,
    **kwargs: Dict[
        str, Union[slice, Tuple[int, ...], Tuple[float, float], Callable[[float], bool]]
    ],
) -> Dict[str, Tensor]:
    r"""
    Select specific bands from a band-resolved [`Tensor`][qten.linalg.tensors.Tensor] based on criteria provided in `kwargs`.

    The input [`Tensor`][qten.linalg.tensors.Tensor] is diagonalized at each
    [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace] sector. Each
    keyword argument defines one named selection criterion, and the returned
    dictionary maps each name to a tensor containing the matching eigenvectors.
    Outputs have dimensions `(MomentumSpace, HilbertSpace, IndexSpace)`, where
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] labels the band
    basis and [`IndexSpace`][qten.symbolics.state_space.IndexSpace] labels the
    selected states for each criterion.

    Mathematical convention
    -----------------------
    For each momentum sector, \(H(k) v_n(k) = \epsilon_n(k) v_n(k)\), and each criterion selects a subset of band labels \(n\). The returned
    tensor packs the matching eigenvectors \(v_n(k)\) into an
    [`IndexSpace`][qten.symbolics.state_space.IndexSpace], padding sectors with
    fewer matches by zero columns.

    Supported criteria
    ------------------
    - `slice`: select bands by sorted energy index, such as `slice(0, 2)` for
      the two lowest-energy bands.
    - `Tuple[int, ...]`: select explicit sorted band indices, such as `(0, 2)`
      for the lowest and third-lowest bands.
    - `Tuple[float, float]`: select an inclusive energy range.
    - `Callable[[float], bool]`: select energies for which the callable returns
      `True`.

    If a criterion matches no bands in all momentum sectors, the corresponding
    output tensor has an `IndexSpace` of dimension zero.

    Parameters
    ----------
    tensor : Tensor
        Band-resolved tensor with dimensions
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    kwargs : Dict[str, Union[slice, Tuple[int, ...], Tuple[float, float], Callable[[float], bool]]]
        Named band-selection criteria.

    Returns
    -------
    Dict[str, Tensor]
        Mapping from criterion name to selected eigenvector tensor with
        dimensions `(MomentumSpace, HilbertSpace, IndexSpace)`.

    Raises
    ------
    TypeError
        If the tensor axes are not `(MomentumSpace, HilbertSpace,
        HilbertSpace)`, or if a criterion has an unsupported type.
    ValueError
        If `tensor` is not rank 3.
    IndexError
        If an explicit integer band index is outside the available band range.
    """
    if tensor.rank() != 3:
        raise ValueError(
            f"Input tensor must be of rank 3, but has rank {tensor.rank()}"
        )
    if not isinstance(tensor.dims[0], MomentumSpace):
        raise TypeError("The first dimension of the tensor must be a MomentumSpace.")
    if not isinstance(tensor.dims[1], HilbertSpace):
        raise TypeError("The second dimension of the tensor must be a HilbertSpace.")
    if not isinstance(tensor.dims[2], HilbertSpace):
        raise TypeError("The third dimension of the tensor must be a HilbertSpace.")

    kspace = cast(MomentumSpace, tensor.dims[0])
    band_space = cast(HilbertSpace, tensor.dims[1])
    eigvals, eigvecs = eigh(tensor)
    values = eigvals.data
    vectors = eigvecs.data

    nk, nbands = values.shape
    band_indices = torch.arange(nbands, device=values.device)

    def pack(mask: torch.Tensor) -> Tensor:
        counts = mask.sum(dim=1)
        max_count = int(counts.max().item()) if counts.numel() else 0
        out_dim = IndexSpace.linear(max_count)
        if max_count == 0:
            return Tensor(data=vectors[..., :0], dims=(kspace, band_space, out_dim))

        order = torch.argsort(mask.to(torch.int8), dim=1, descending=True, stable=True)
        packed = torch.gather(
            vectors,
            2,
            order[:, None, :].expand(-1, vectors.shape[1], -1),
        )[..., :max_count]
        valid = (
            torch.arange(max_count, device=counts.device)[None, :] < counts[:, None]
        ).to(packed.dtype)
        packed = packed * valid[:, None, :]
        return Tensor(data=packed, dims=(kspace, band_space, out_dim))

    selected: Dict[str, Tensor] = {}
    for name, criterion in kwargs.items():
        mask: torch.Tensor
        if isinstance(criterion, slice):
            picked = band_indices[criterion]
            mask = torch.zeros((nk, nbands), dtype=torch.bool, device=values.device)
            if picked.numel():
                mask[:, picked] = True
        elif isinstance(criterion, tuple):
            if all(isinstance(x, int) and not isinstance(x, bool) for x in criterion):
                mask = torch.zeros((nk, nbands), dtype=torch.bool, device=values.device)
                if criterion:
                    raw_idx = torch.tensor(
                        criterion, dtype=torch.long, device=values.device
                    )
                    if ((raw_idx < -nbands) | (raw_idx >= nbands)).any():
                        raise IndexError(
                            f"Band index out of range in criterion {name!r}"
                        )
                    mask[:, raw_idx % nbands] = True
            elif len(criterion) == 2 and all(
                isinstance(x, (int, float, np.integer, np.floating))
                and not isinstance(x, bool)
                for x in criterion
            ):
                lo, hi = criterion
                mask = (values >= lo) & (values <= hi)
            else:
                raise TypeError(
                    f"Unsupported tuple criterion for {name!r}: {criterion!r}"
                )
        elif callable(criterion):
            mask = torch.tensor(
                [
                    [bool(criterion(v)) for v in row]
                    for row in values.detach().cpu().tolist()
                ],
                dtype=torch.bool,
                device=values.device,
            )
        else:
            raise TypeError(f"Unsupported criterion for {name!r}: {criterion!r}")

        selected[name] = pack(mask)

    return selected

nearest_bands

nearest_bands(
    h_k: Tensor,
    point: Union[str, Sequence[float]] = "Gamma",
    close_to: float = 0.0,
    tol: float = 1e-06,
    points: Optional[Dict[str, Sequence[float]]] = None,
) -> Tensor

Project a momentum-resolved Hamiltonian onto bands selected at one k-point.

The input h_k is diagonalized at a single anchor momentum \(k_0\). Eigenvectors whose anchor eigenvalues lie within tol of close_to are collected into a rectangular matrix \(V\). If the input Hilbert dimension is \(N\) and \(S\) bands are selected, then V has shape (N, S) and the returned tensor stores \(V^\dagger H(k) V\) for every momentum \(k\).

Projection convention

At the selected anchor sector, the code computes eigenvalues, eigenvectors = torch.linalg.eigh(H_anchor). The columns of eigenvectors with \(|\epsilon_n(k_0) - \mathrm{close\_to}| \le \mathrm{tol}\) form \(V\). The projected block at each momentum is \(H_{\mathrm{proj}}(k) = V^\dagger H(k) V\).

In implementation terms, this projection is the einsum torch.einsum("ia,kab,bj->kij", V_dag, h_k.data, V).

Anchor selection
  • A string point is looked up in points.
  • "Gamma" defaults to the fractional origin when absent from points.
  • A coordinate sequence is interpreted directly as fractional coordinates.
  • Fractional-coordinate differences are wrapped by subtracting the nearest integer, so equivalent periodic coordinates select the same anchor.

If no eigenvalue falls inside the tolerance window, the result has two zero-dimensional IndexSpace axes and data shape (len(kspace), 0, 0).

Notes

The selected subspace is fixed by the anchor momentum only. The same anchor eigenvector matrix \(V\) is applied to every \(H(k)\); this is a projection onto an anchor-defined subspace, not a separately diagonalized band selection at each momentum.

Parameters:

Name Type Description Default
h_k Tensor

Hamiltonian tensor with dims (MomentumSpace, HilbertSpace, HilbertSpace).

required
point str or Sequence[float]

Anchor k-point. String labels are resolved through points, except "Gamma" which defaults to the fractional origin.

"Gamma"
close_to float

Target eigenvalue for the subspace selection.

0.0
tol float

Half-width of the eigenvalue window around close_to.

1e-6
points dict[str, Sequence[float]]

Mapping from labels to fractional coordinates.

None

Returns:

Type Description
Tensor

Projected Hamiltonian with dims (MomentumSpace, IndexSpace, IndexSpace). The last two axes span the selected subspace.

Raises:

Type Description
ValueError

If h_k is not rank 3, if the momentum space is empty, or if the anchor coordinate dimension does not match the momentum-space dimension.

TypeError

If the input dimensions are not (MomentumSpace, HilbertSpace, HilbertSpace).

KeyError

If point is a string other than "Gamma" and is not present in points.

Source code in src/qten/bands.py
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
def nearest_bands(
    h_k: Tensor,
    point: Union[str, Sequence[float]] = "Gamma",
    close_to: float = 0.0,
    tol: float = 1e-6,
    points: Optional[Dict[str, Sequence[float]]] = None,
) -> Tensor:
    r"""
    Project a momentum-resolved Hamiltonian onto bands selected at one k-point.

    The input `h_k` is diagonalized at a single anchor momentum \(k_0\).
    Eigenvectors whose anchor eigenvalues lie within `tol` of `close_to` are
    collected into a rectangular matrix \(V\). If the input Hilbert dimension is
    \(N\) and \(S\) bands are selected, then `V` has shape `(N, S)` and the
    returned tensor stores \(V^\dagger H(k) V\) for every momentum \(k\).

    Projection convention
    ---------------------
    At the selected anchor sector, the code computes
    `eigenvalues, eigenvectors = torch.linalg.eigh(H_anchor)`. The columns of
    `eigenvectors` with \(|\epsilon_n(k_0) - \mathrm{close\_to}| \le \mathrm{tol}\)
    form \(V\). The projected block at each momentum is
    \(H_{\mathrm{proj}}(k) = V^\dagger H(k) V\).

    In implementation terms, this projection is the einsum
    `torch.einsum("ia,kab,bj->kij", V_dag, h_k.data, V)`.

    Anchor selection
    ----------------
    - A string `point` is looked up in `points`.
    - `"Gamma"` defaults to the fractional origin when absent from `points`.
    - A coordinate sequence is interpreted directly as fractional coordinates.
    - Fractional-coordinate differences are wrapped by subtracting the nearest
      integer, so equivalent periodic coordinates select the same anchor.

    If no eigenvalue falls inside the tolerance window, the result has two
    zero-dimensional [`IndexSpace`][qten.symbolics.state_space.IndexSpace] axes
    and data shape `(len(kspace), 0, 0)`.

    Notes
    -----
    The selected subspace is fixed by the anchor momentum only. The same
    anchor eigenvector matrix \(V\) is applied to every \(H(k)\); this is a
    projection onto an anchor-defined subspace, not a separately diagonalized
    band selection at each momentum.

    Parameters
    ----------
    h_k : Tensor
        Hamiltonian tensor with dims
        ([`MomentumSpace`][qten.symbolics.state_space.MomentumSpace],
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace],
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace]).
    point : str or Sequence[float], default="Gamma"
        Anchor k-point. String labels are resolved through `points`, except
        `"Gamma"` which defaults to the fractional origin.
    close_to : float, default=0.0
        Target eigenvalue for the subspace selection.
    tol : float, default=1e-6
        Half-width of the eigenvalue window around `close_to`.
    points : dict[str, Sequence[float]], optional
        Mapping from labels to fractional coordinates.

    Returns
    -------
    Tensor
        Projected Hamiltonian with dims
        ([`MomentumSpace`][qten.symbolics.state_space.MomentumSpace],
        [`IndexSpace`][qten.symbolics.state_space.IndexSpace],
        [`IndexSpace`][qten.symbolics.state_space.IndexSpace]). The last two
        axes span the selected subspace.

    Raises
    ------
    ValueError
        If `h_k` is not rank 3, if the momentum space is empty, or if the
        anchor coordinate dimension does not match the momentum-space
        dimension.
    TypeError
        If the input dimensions are not
        `(MomentumSpace, HilbertSpace, HilbertSpace)`.
    KeyError
        If `point` is a string other than `"Gamma"` and is not present in
        `points`.
    """
    if h_k.rank() != 3:
        raise ValueError(f"Input tensor must be of rank 3, but has rank {h_k.rank()}")
    if not isinstance(h_k.dims[0], MomentumSpace):
        raise TypeError("The first dimension of the tensor must be a MomentumSpace.")
    if not isinstance(h_k.dims[1], HilbertSpace):
        raise TypeError("The second dimension of the tensor must be a HilbertSpace.")
    if not isinstance(h_k.dims[2], HilbertSpace):
        raise TypeError("The third dimension of the tensor must be a HilbertSpace.")

    kspace = cast(MomentumSpace, h_k.dims[0])
    k_items = list(kspace.structure.items())
    if not k_items:
        raise ValueError("MomentumSpace is empty")

    dim = k_items[0][0].space.dim
    if isinstance(point, str):
        if points is not None and point in points:
            target_frac = tuple(float(x) for x in points[point])
        elif point == "Gamma":
            target_frac = tuple(0.0 for _ in range(dim))
        else:
            raise KeyError(
                f"Point {point!r} not found in `points`; "
                "provide a `points` mapping or pass explicit fractional coordinates."
            )
    else:
        target_frac = tuple(float(x) for x in point)
    if len(target_frac) != dim:
        raise ValueError(
            f"Anchor point has {len(target_frac)} coordinates but momentum "
            f"space has dimension {dim}."
        )

    precision = get_precision_config()
    k_frac = np.array(
        [[float(k.rep[j, 0]) for j in range(dim)] for k, _ in k_items],
        dtype=precision.np_float,
    )
    k_indices = np.array([idx for _, idx in k_items], dtype=np.int64)
    target_arr = np.asarray(target_frac, dtype=precision.np_float)
    diff = k_frac - target_arr
    diff = diff - np.round(diff)
    dist = np.linalg.norm(diff, axis=1)
    best_row = int(np.argmin(dist))
    anchor_idx = int(k_indices[best_row])

    H_anchor = h_k.data[anchor_idx]
    eigenvalues, eigenvectors = torch.linalg.eigh(H_anchor)

    mask = (eigenvalues - close_to).abs() <= tol
    selected = torch.nonzero(mask, as_tuple=False).flatten()
    n_selected = int(selected.numel())

    V = eigenvectors.index_select(-1, selected)  # (N, H)
    V_dag = V.conj().transpose(-2, -1)  # (H, N)

    projected = torch.einsum("ia,kab,bj->kij", V_dag, h_k.data, V)

    out_space = IndexSpace.linear(n_selected)
    return Tensor(data=projected, dims=(kspace, out_space, out_space))

proj_wannierization

proj_wannierization(
    eigenvectors: Tensor[Any],
    seeds: Tensor[Any],
    svd_threshold: float = 0.1,
    wannierize_lattice: bool = True,
) -> Tensor[Any]

Perform projective Wannierization from localized real-space trial orbitals.

This helper implements the standard two-stage projective-Wannier workflow:

  1. Fourier transform localized seed states into momentum space.
  2. At each momentum sector, rotate the target band subspace into the gauge that best matches those transformed seeds via the polar/SVD factor of the overlap matrix.

The function is therefore a thin orchestration layer around fourier_transform() and svd_projection().

Mathematical convention

Let \(k \in \mathcal{K}\) denote a sampled momentum, let \(\{|b\rangle\}_{b=1}^{N_b}\) be the Bloch basis stored on the second axis of eigenvectors, and let \(\{|r\rangle\}_{r=1}^{N_r}\) be the localized basis stored on the first axis of seeds.

Suppose the seed tensor stores coefficients \(A_{r n}\), where \(n = 1, \dots, N_s\) labels the trial orbitals. In matrix form, \(A \in \mathbb{C}^{N_r \times N_s}\).

The discrete Fourier-transform tensor returned by fourier_transform(k_space, bloch_space, local_seed_space) is a rank-3 object with entries

\[ F(k)_{b r} = \delta_{\text{internal}(b),\,\text{internal}(r)} \exp(-\mathrm{i}\, k \cdot r), \]

where the Kronecker-style matching factor indicates that only localized and Bloch basis states with matching non-offset irreps are connected. In the repository's fractional-coordinate convention, this phase is equivalently \(\exp(-2\pi\mathrm{i}\,\kappa \cdot n)\).

For each momentum sector, the real-space seeds are lifted to Bloch form as

\[ S(k) = F(k)\,A, \]

with \(S(k) \in \mathbb{C}^{N_b \times N_s}\).

The input eigenvectors stores the target subspace as matrices

\[ U(k) \in \mathbb{C}^{N_b \times N_t}, \]

whose columns span the band manifold to be Wannierized.

The gauge-fixing step then forms the overlap

\[ M(k) = U(k)^\dagger S(k) \in \mathbb{C}^{N_t \times N_s}, \]

computes its singular value decomposition

\[ M(k) = X(k)\,\Sigma(k)\,Y(k)^\dagger, \]

discards the singular values, and keeps only the polar/unitary factor

\[ Q(k) = X(k)\,Y(k)^\dagger. \]

The projected Wannier-gauge states are then

\[ \widetilde{U}(k) = U(k)\,Q(k). \]

This is exactly the orthogonal-Procrustes solution used by svd_projection(): it preserves the target column space while choosing the column gauge that best aligns the target states with the Fourier-transformed trial orbitals.

Step-by-step behavior

Given eigenvectors and seeds, the code performs:

  1. Read the shared momentum grid k_space = eigenvectors.dims[0].
  2. Read the Bloch Hilbert space bloch_space = eigenvectors.dims[1].
  3. Read the localized seed row basis local_seed_space = seeds.dims[0].
  4. Build the discrete Fourier transform tensor F = fourier_transform(k_space, bloch_space, local_seed_space).
  5. Convert localized trial orbitals into momentum-resolved trial orbitals by the tensor contraction crystal_seeds = F @ seeds.
  6. Call svd_projection(eigenvectors, crystal_seeds, svd_threshold, infer_lattice=wannierize_lattice).
  7. Return the projected states.
Interpretation of the tensor legs
  • eigenvectors must have dims (MomentumSpace, HilbertSpace, D_target), where the first two axes represent momentum and Bloch basis, and the last axis enumerates the target band columns.
  • seeds must have dims (HilbertSpace_local, D_seed), where the first axis is a localized real-space basis containing Offset labels, and the second axis enumerates trial orbitals.
  • After Fourier transformation, crystal_seeds has dims (MomentumSpace, HilbertSpace, D_seed).

Here D_target and D_seed may be different state-space types. The most common case is that both are IndexSpace, but the seed-column space may also be a HilbertSpace.

Lattice-aware output

The wannierize_lattice flag is forwarded to svd_projection(), but lattice rebuilding is only possible when the column space of the transformed seeds still carries a HilbertSpace with meaningful Offset labels.

Concretely:

  • if seeds.dims[1] is an IndexSpace, projection still works exactly as described above, but no lattice-backed output basis can be inferred, so the result remains a plain rank-3 tensor;
  • if seeds.dims[1] is a HilbertSpace, then after Fourier transformation the source columns retain those symbolic labels, and svd_projection(..., infer_lattice=True) may return a MomentumBlockTensor whose final Hilbert leg has been rebuilt on the inferred Wannier lattice.
Numerical behavior

The SVD warning threshold is interpreted exactly as in svd_projection(): if the minimum singular value of the overlap becomes smaller than svd_threshold, a warning is emitted because the trial orbitals may poorly span the target subspace or may be nearly linearly dependent after projection. Zero-padded columns, if present in the target or source, are ignored sector by sector by the underlying projection routine.

Parameters:

Name Type Description Default
eigenvectors Tensor

Target band states with dims (MomentumSpace, HilbertSpace, D_target).

required
seeds Tensor

Localized trial orbitals with dims (HilbertSpace_local, D_seed). The first axis is the localized real-space basis to be Fourier transformed; the second axis enumerates the trial orbitals themselves. D_seed does not have to be an IndexSpace: it may also be a HilbertSpace. This distinction controls whether wannierize_lattice can do anything:

  • if D_seed is an IndexSpace, the function still performs the full projective Wannierization, but the output remains a plain rank-3 tensor because there is no symbolic seed-column geometry to rebuild into a Wannier lattice;
  • if D_seed is a HilbertSpace, the transformed seed columns retain their symbolic offset labels, so wannierize_lattice=True may trigger lattice inference in the final projection step.
required
svd_threshold float

Warning threshold passed to svd_projection().

0.1
wannierize_lattice bool

Forwarded as infer_lattice to svd_projection(). This only has an effect when the transformed seed columns carry a HilbertSpace label.

True

Returns:

Type Description
Tensor

Projected Wannier-gauge states. Usually this is a rank-3 tensor with dims (MomentumSpace, HilbertSpace, D_seed). If lattice inference is enabled and succeeds, the result may instead be a MomentumBlockTensor.

Raises:

Type Description
ValueError

If eigenvectors is not rank 3 or seeds is not rank 2.

TypeError

If eigenvectors.dims[0] is not a MomentumSpace, or if eigenvectors.dims[1] / seeds.dims[0] are not HilbertSpace.

Source code in src/qten/bands.py
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
def proj_wannierization(
    eigenvectors: Tensor[Any],
    seeds: Tensor[Any],
    svd_threshold: float = 1e-1,
    wannierize_lattice: bool = True,
) -> Tensor[Any]:
    r"""
    Perform projective Wannierization from localized real-space trial orbitals.

    This helper implements the standard two-stage projective-Wannier workflow:

    1. Fourier transform localized seed states into momentum space.
    2. At each momentum sector, rotate the target band subspace into the gauge
       that best matches those transformed seeds via the polar/SVD factor of
       the overlap matrix.

    The function is therefore a thin orchestration layer around
    [`fourier_transform()`][qten.geometries.fourier.fourier_transform] and
    [`svd_projection()`][qten.bands.svd_projection].

    Mathematical convention
    -----------------------
    Let
    \(k \in \mathcal{K}\) denote a sampled momentum,
    let \(\{|b\rangle\}_{b=1}^{N_b}\) be the Bloch basis stored on the second
    axis of `eigenvectors`, and let
    \(\{|r\rangle\}_{r=1}^{N_r}\) be the localized basis stored on the first
    axis of `seeds`.

    Suppose the seed tensor stores coefficients
    \(A_{r n}\), where \(n = 1, \dots, N_s\) labels the trial orbitals. In
    matrix form,
    \(A \in \mathbb{C}^{N_r \times N_s}\).

    The discrete Fourier-transform tensor returned by
    [`fourier_transform(k_space, bloch_space, local_seed_space)`][qten.geometries.fourier.fourier_transform]
    is a rank-3 object with entries

    \[
    F(k)_{b r} =
    \delta_{\text{internal}(b),\,\text{internal}(r)}
    \exp(-\mathrm{i}\, k \cdot r),
    \]

    where the Kronecker-style matching factor indicates that only localized and
    Bloch basis states with matching non-offset irreps are connected. In the
    repository's fractional-coordinate convention, this phase is equivalently
    \(\exp(-2\pi\mathrm{i}\,\kappa \cdot n)\).

    For each momentum sector, the real-space seeds are lifted to Bloch form as

    \[
    S(k) = F(k)\,A,
    \]

    with
    \(S(k) \in \mathbb{C}^{N_b \times N_s}\).

    The input `eigenvectors` stores the target subspace as matrices

    \[
    U(k) \in \mathbb{C}^{N_b \times N_t},
    \]

    whose columns span the band manifold to be Wannierized.

    The gauge-fixing step then forms the overlap

    \[
    M(k) = U(k)^\dagger S(k)
    \in \mathbb{C}^{N_t \times N_s},
    \]

    computes its singular value decomposition

    \[
    M(k) = X(k)\,\Sigma(k)\,Y(k)^\dagger,
    \]

    discards the singular values, and keeps only the polar/unitary factor

    \[
    Q(k) = X(k)\,Y(k)^\dagger.
    \]

    The projected Wannier-gauge states are then

    \[
    \widetilde{U}(k) = U(k)\,Q(k).
    \]

    This is exactly the orthogonal-Procrustes solution used by
    [`svd_projection()`][qten.bands.svd_projection]: it preserves the target
    column space while choosing the column gauge that best aligns the target
    states with the Fourier-transformed trial orbitals.

    Step-by-step behavior
    ---------------------
    Given `eigenvectors` and `seeds`, the code performs:

    1. Read the shared momentum grid `k_space = eigenvectors.dims[0]`.
    2. Read the Bloch Hilbert space
       `bloch_space = eigenvectors.dims[1]`.
    3. Read the localized seed row basis
       `local_seed_space = seeds.dims[0]`.
    4. Build the discrete Fourier transform tensor
       `F = fourier_transform(k_space, bloch_space, local_seed_space)`.
    5. Convert localized trial orbitals into momentum-resolved trial orbitals
       by the tensor contraction `crystal_seeds = F @ seeds`.
    6. Call
       `svd_projection(eigenvectors, crystal_seeds, svd_threshold, infer_lattice=wannierize_lattice)`.
    7. Return the projected states.

    Interpretation of the tensor legs
    ---------------------------------
    - `eigenvectors` must have dims
      `(MomentumSpace, HilbertSpace, D_target)`, where the first two axes
      represent momentum and Bloch basis, and the last axis enumerates the
      target band columns.
    - `seeds` must have dims
      `(HilbertSpace_local, D_seed)`, where the first axis is a localized
      real-space basis containing [`Offset`][qten.geometries.spatials.Offset]
      labels, and the second axis enumerates trial orbitals.
    - After Fourier transformation, `crystal_seeds` has dims
      `(MomentumSpace, HilbertSpace, D_seed)`.

    Here `D_target` and `D_seed` may be different state-space types. The most
    common case is that both are
    [`IndexSpace`][qten.symbolics.state_space.IndexSpace], but the seed-column
    space may also be a
    [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace].

    Lattice-aware output
    --------------------
    The `wannierize_lattice` flag is forwarded to
    [`svd_projection()`][qten.bands.svd_projection], but lattice rebuilding is
    only possible when the **column space of the transformed seeds** still
    carries a [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace]
    with meaningful [`Offset`][qten.geometries.spatials.Offset] labels.

    Concretely:

    - if `seeds.dims[1]` is an
      [`IndexSpace`][qten.symbolics.state_space.IndexSpace], projection still
      works exactly as described above, but no lattice-backed output basis can
      be inferred, so the result remains a plain rank-3 tensor;
    - if `seeds.dims[1]` is a
      [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace], then after
      Fourier transformation the source columns retain those symbolic labels,
      and `svd_projection(..., infer_lattice=True)` may return a
      [`MomentumBlockTensor`][qten.MomentumBlockTensor] whose final Hilbert leg
      has been rebuilt on the inferred Wannier lattice.

    Numerical behavior
    ------------------
    The SVD warning threshold is interpreted exactly as in
    [`svd_projection()`][qten.bands.svd_projection]: if the minimum singular
    value of the overlap becomes smaller than `svd_threshold`, a warning is
    emitted because the trial orbitals may poorly span the target subspace or
    may be nearly linearly dependent after projection. Zero-padded columns, if
    present in the target or source, are ignored sector by sector by the
    underlying projection routine.

    Parameters
    ----------
    eigenvectors : Tensor
        Target band states with dims
        `(MomentumSpace, HilbertSpace, D_target)`.
    seeds : Tensor
        Localized trial orbitals with dims `(HilbertSpace_local, D_seed)`.
        The first axis is the localized real-space basis to be Fourier
        transformed; the second axis enumerates the trial orbitals themselves.
        `D_seed` does not have to be an
        [`IndexSpace`][qten.symbolics.state_space.IndexSpace]: it may also be a
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace].
        This distinction controls whether `wannierize_lattice` can do
        anything:

        - if `D_seed` is an
          [`IndexSpace`][qten.symbolics.state_space.IndexSpace], the function
          still performs the full projective Wannierization, but the output
          remains a plain rank-3 tensor because there is no symbolic
          seed-column geometry to rebuild into a Wannier lattice;
        - if `D_seed` is a
          [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace], the
          transformed seed columns retain their symbolic offset labels, so
          `wannierize_lattice=True` may trigger lattice inference in the final
          projection step.
    svd_threshold : float, optional
        Warning threshold passed to
        [`svd_projection()`][qten.bands.svd_projection].
    wannierize_lattice : bool, optional
        Forwarded as `infer_lattice` to
        [`svd_projection()`][qten.bands.svd_projection]. This only has an
        effect when the transformed seed columns carry a
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace] label.

    Returns
    -------
    Tensor
        Projected Wannier-gauge states. Usually this is a rank-3 tensor with
        dims `(MomentumSpace, HilbertSpace, D_seed)`. If lattice inference is
        enabled and succeeds, the result may instead be a
        [`MomentumBlockTensor`][qten.MomentumBlockTensor].

    Raises
    ------
    ValueError
        If `eigenvectors` is not rank 3 or `seeds` is not rank 2.
    TypeError
        If `eigenvectors.dims[0]` is not a
        [`MomentumSpace`][qten.symbolics.state_space.MomentumSpace], or if
        `eigenvectors.dims[1]` / `seeds.dims[0]` are not
        [`HilbertSpace`][qten.symbolics.hilbert_space.HilbertSpace].
    """
    if eigenvectors.rank() != 3:
        raise ValueError("eigenvectors must be a rank-3 Tensor.")
    if seeds.rank() != 2:
        raise ValueError("seeds must be a rank-2 Tensor.")
    if not isinstance(eigenvectors.dims[0], MomentumSpace):
        raise TypeError(
            "The first dimension of the eigenvectors must be a MomentumSpace."
        )

    kspace = eigenvectors.dims[0]
    bloch_space = eigenvectors.dims[1]
    local_seed_space = seeds.dims[0]
    if not isinstance(bloch_space, HilbertSpace) or not isinstance(
        local_seed_space, HilbertSpace
    ):
        raise TypeError(
            "The second dimension of eigenvectors and first dimension "
            "of seeds must be HilbertSpace."
        )

    # Perform Fourier transform on local seeds to move them to momentum space
    # `f` has dims `(MomentumSpace, BlochHilbertSpace, LocalSeedHilbertSpace)`.
    f = fourier_transform(
        kspace, bloch_space, local_seed_space, device=eigenvectors.device
    )

    # Map the seeds to crystal momentum seeds
    # f @ local_seeds -> (MomentumSpace, HilbertSpace_out, IndexSpace)
    crystal_seeds = f @ seeds

    return svd_projection(
        eigenvectors,
        crystal_seeds,
        svd_threshold,
        infer_lattice=wannierize_lattice,
    )