Skip to content

jaxquantum

jaxquantum

DenseImpl

Bases: QarrayImpl

Dense implementation using JAX dense arrays.

Attributes:

Name Type Description
_data Array

The underlying jnp.ndarray.

Source code in jaxquantum/core/qarray.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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
@struct.dataclass
class DenseImpl(QarrayImpl):
    """Dense implementation using JAX dense arrays.

    Attributes:
        _data: The underlying ``jnp.ndarray``.
    """

    _data: Array

    PROMOTION_ORDER = 2  # noqa: RUF012 — not a struct field; no annotation intentional

    @classmethod
    def from_data(cls, data) -> "DenseImpl":
        """Wrap *data* in a new ``DenseImpl``.

        Args:
            data: Array-like input data.

        Returns:
            A ``DenseImpl`` wrapping ``robust_asarray(data)``.
        """
        return cls(_data=robust_asarray(data))

    def get_data(self) -> Array:
        """Return the underlying dense array."""
        return self._data

    def matmul(self, other: QarrayImpl) -> QarrayImpl:
        """Matrix multiply ``self @ other``, coercing types as needed.

        Args:
            other: Right-hand operand.

        Returns:
            A ``DenseImpl`` containing the matrix product.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.matmul(b)
        return DenseImpl(self._data @ b._data)

    def add(self, other: QarrayImpl) -> QarrayImpl:
        """Element-wise addition ``self + other``, coercing types as needed.

        Args:
            other: Right-hand operand.

        Returns:
            A ``DenseImpl`` containing the sum.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.add(b)
        return DenseImpl(self._data + b._data)

    def sub(self, other: QarrayImpl) -> QarrayImpl:
        """Element-wise subtraction ``self - other``, coercing types as needed.

        Args:
            other: Right-hand operand.

        Returns:
            A ``DenseImpl`` containing the difference.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.sub(b)
        return DenseImpl(self._data - b._data)

    def mul(self, scalar) -> QarrayImpl:
        """Scalar multiplication.

        Args:
            scalar: Scalar value.

        Returns:
            A ``DenseImpl`` with each element multiplied by *scalar*.
        """
        return DenseImpl(scalar * self._data)

    def dag(self) -> QarrayImpl:
        """Conjugate transpose.

        Returns:
            A ``DenseImpl`` containing the conjugate transpose.
        """
        return DenseImpl(jnp.moveaxis(jnp.conj(self._data), -1, -2))

    def to_dense(self) -> "DenseImpl":
        """Return self (already dense).

        Returns:
            This ``DenseImpl`` instance unchanged.
        """
        return self

    def to_sparse_bcoo(self) -> "SparseBCOOImpl":
        """Convert to a ``SparseBCOOImpl`` via ``BCOO.fromdense``.

        Returns:
            A ``SparseBCOOImpl`` wrapping a BCOO conversion of this array.
        """
        from jaxquantum.core.sparse_bcoo import SparseBCOOImpl
        return SparseBCOOImpl(sparse.BCOO.fromdense(self._data))

    def shape(self) -> tuple:
        """Shape of the underlying dense array.

        Returns:
            Tuple of dimension sizes.
        """
        return self._data.shape

    def dtype(self):
        """Data type of the underlying dense array.

        Returns:
            The dtype of ``_data``.
        """
        return self._data.dtype

    def frobenius_norm(self) -> float:
        """Compute the Frobenius norm.

        Returns:
            The Frobenius norm as a scalar.
        """
        return jnp.sqrt(jnp.sum(jnp.abs(self._data) ** 2))

    def real(self) -> QarrayImpl:
        """Element-wise real part.

        Returns:
            A ``DenseImpl`` containing the real parts.
        """
        return DenseImpl(jnp.real(self._data))

    def imag(self) -> QarrayImpl:
        """Element-wise imaginary part.

        Returns:
            A ``DenseImpl`` containing the imaginary parts.
        """
        return DenseImpl(jnp.imag(self._data))

    def conj(self) -> QarrayImpl:
        """Element-wise complex conjugate.

        Returns:
            A ``DenseImpl`` containing the complex-conjugated values.
        """
        return DenseImpl(jnp.conj(self._data))

    def __deepcopy__(self, memo=None):
        return DenseImpl(
            _data=deepcopy(self._data, memo)
        )

    def tidy_up(self, atol):
        """Zero out real/imaginary parts whose magnitude is below *atol*.

        Args:
            atol: Absolute tolerance threshold.

        Returns:
            A new ``DenseImpl`` with small values zeroed.
        """
        data = self._data
        data_re = jnp.real(data)
        data_im = jnp.imag(data)
        data_re_mask = jnp.abs(data_re) > atol
        data_im_mask = jnp.abs(data_im) > atol
        data_new = data_re * data_re_mask + 1j * data_im * data_im_mask

        return DenseImpl(
            _data=data_new
        )

    def kron(self, other: "QarrayImpl") -> "QarrayImpl":
        """Kronecker product using ``jnp.kron``.

        Args:
            other: Right-hand operand.

        Returns:
            A ``DenseImpl`` containing the Kronecker product.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.kron(b)
        return DenseImpl(jnp.kron(self._data, b._data))

    @classmethod
    def _eye_data(cls, n: int, dtype=None):
        """Create an ``n x n`` identity matrix as a dense JAX array.

        Args:
            n: Matrix size.
            dtype: Optional data type.

        Returns:
            A ``jnp.ndarray`` identity matrix of shape ``(n, n)``.
        """
        return jnp.eye(n, dtype=dtype)

    @classmethod
    def can_handle_data(cls, arr) -> bool:
        """Return True for any non-BCOO, non-SparseDIA array.

        ``SparseDiaData`` objects carry a ``_is_sparse_dia`` marker so we can
        exclude them without a direct type import (which would be circular).

        Args:
            arr: Raw array.

        Returns:
            True when *arr* is a plain dense array (not BCOO, not SparseDiaData).
        """
        return not isinstance(arr, sparse.BCOO) and not getattr(arr, "_is_sparse_dia", False)

    @classmethod
    def dag_data(cls, arr) -> Array:
        """Conjugate transpose for dense arrays.

        Swaps the last two axes via :func:`jnp.moveaxis` and conjugates all
        elements.  For 1-D inputs only conjugation is applied.

        Args:
            arr: Dense array.

        Returns:
            Conjugate transpose with the last two axes swapped.
        """
        if len(arr.shape) == 1:
            return jnp.conj(arr)
        return jnp.moveaxis(jnp.conj(arr), -1, -2)

add(other)

Element-wise addition self + other, coercing types as needed.

Parameters:

Name Type Description Default
other QarrayImpl

Right-hand operand.

required

Returns:

Type Description
QarrayImpl

A DenseImpl containing the sum.

Source code in jaxquantum/core/qarray.py
441
442
443
444
445
446
447
448
449
450
451
452
453
def add(self, other: QarrayImpl) -> QarrayImpl:
    """Element-wise addition ``self + other``, coercing types as needed.

    Args:
        other: Right-hand operand.

    Returns:
        A ``DenseImpl`` containing the sum.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.add(b)
    return DenseImpl(self._data + b._data)

can_handle_data(arr) classmethod

Return True for any non-BCOO, non-SparseDIA array.

SparseDiaData objects carry a _is_sparse_dia marker so we can exclude them without a direct type import (which would be circular).

Parameters:

Name Type Description Default
arr

Raw array.

required

Returns:

Type Description
bool

True when arr is a plain dense array (not BCOO, not SparseDiaData).

Source code in jaxquantum/core/qarray.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
@classmethod
def can_handle_data(cls, arr) -> bool:
    """Return True for any non-BCOO, non-SparseDIA array.

    ``SparseDiaData`` objects carry a ``_is_sparse_dia`` marker so we can
    exclude them without a direct type import (which would be circular).

    Args:
        arr: Raw array.

    Returns:
        True when *arr* is a plain dense array (not BCOO, not SparseDiaData).
    """
    return not isinstance(arr, sparse.BCOO) and not getattr(arr, "_is_sparse_dia", False)

conj()

Element-wise complex conjugate.

Returns:

Type Description
QarrayImpl

A DenseImpl containing the complex-conjugated values.

Source code in jaxquantum/core/qarray.py
545
546
547
548
549
550
551
def conj(self) -> QarrayImpl:
    """Element-wise complex conjugate.

    Returns:
        A ``DenseImpl`` containing the complex-conjugated values.
    """
    return DenseImpl(jnp.conj(self._data))

dag()

Conjugate transpose.

Returns:

Type Description
QarrayImpl

A DenseImpl containing the conjugate transpose.

Source code in jaxquantum/core/qarray.py
480
481
482
483
484
485
486
def dag(self) -> QarrayImpl:
    """Conjugate transpose.

    Returns:
        A ``DenseImpl`` containing the conjugate transpose.
    """
    return DenseImpl(jnp.moveaxis(jnp.conj(self._data), -1, -2))

dag_data(arr) classmethod

Conjugate transpose for dense arrays.

Swaps the last two axes via :func:jnp.moveaxis and conjugates all elements. For 1-D inputs only conjugation is applied.

Parameters:

Name Type Description Default
arr

Dense array.

required

Returns:

Type Description
Array

Conjugate transpose with the last two axes swapped.

Source code in jaxquantum/core/qarray.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
@classmethod
def dag_data(cls, arr) -> Array:
    """Conjugate transpose for dense arrays.

    Swaps the last two axes via :func:`jnp.moveaxis` and conjugates all
    elements.  For 1-D inputs only conjugation is applied.

    Args:
        arr: Dense array.

    Returns:
        Conjugate transpose with the last two axes swapped.
    """
    if len(arr.shape) == 1:
        return jnp.conj(arr)
    return jnp.moveaxis(jnp.conj(arr), -1, -2)

dtype()

Data type of the underlying dense array.

Returns:

Type Description

The dtype of _data.

Source code in jaxquantum/core/qarray.py
513
514
515
516
517
518
519
def dtype(self):
    """Data type of the underlying dense array.

    Returns:
        The dtype of ``_data``.
    """
    return self._data.dtype

frobenius_norm()

Compute the Frobenius norm.

Returns:

Type Description
float

The Frobenius norm as a scalar.

Source code in jaxquantum/core/qarray.py
521
522
523
524
525
526
527
def frobenius_norm(self) -> float:
    """Compute the Frobenius norm.

    Returns:
        The Frobenius norm as a scalar.
    """
    return jnp.sqrt(jnp.sum(jnp.abs(self._data) ** 2))

from_data(data) classmethod

Wrap data in a new DenseImpl.

Parameters:

Name Type Description Default
data

Array-like input data.

required

Returns:

Type Description
'DenseImpl'

A DenseImpl wrapping robust_asarray(data).

Source code in jaxquantum/core/qarray.py
411
412
413
414
415
416
417
418
419
420
421
@classmethod
def from_data(cls, data) -> "DenseImpl":
    """Wrap *data* in a new ``DenseImpl``.

    Args:
        data: Array-like input data.

    Returns:
        A ``DenseImpl`` wrapping ``robust_asarray(data)``.
    """
    return cls(_data=robust_asarray(data))

get_data()

Return the underlying dense array.

Source code in jaxquantum/core/qarray.py
423
424
425
def get_data(self) -> Array:
    """Return the underlying dense array."""
    return self._data

imag()

Element-wise imaginary part.

Returns:

Type Description
QarrayImpl

A DenseImpl containing the imaginary parts.

Source code in jaxquantum/core/qarray.py
537
538
539
540
541
542
543
def imag(self) -> QarrayImpl:
    """Element-wise imaginary part.

    Returns:
        A ``DenseImpl`` containing the imaginary parts.
    """
    return DenseImpl(jnp.imag(self._data))

kron(other)

Kronecker product using jnp.kron.

Parameters:

Name Type Description Default
other 'QarrayImpl'

Right-hand operand.

required

Returns:

Type Description
'QarrayImpl'

A DenseImpl containing the Kronecker product.

Source code in jaxquantum/core/qarray.py
578
579
580
581
582
583
584
585
586
587
588
589
590
def kron(self, other: "QarrayImpl") -> "QarrayImpl":
    """Kronecker product using ``jnp.kron``.

    Args:
        other: Right-hand operand.

    Returns:
        A ``DenseImpl`` containing the Kronecker product.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.kron(b)
    return DenseImpl(jnp.kron(self._data, b._data))

matmul(other)

Matrix multiply self @ other, coercing types as needed.

Parameters:

Name Type Description Default
other QarrayImpl

Right-hand operand.

required

Returns:

Type Description
QarrayImpl

A DenseImpl containing the matrix product.

Source code in jaxquantum/core/qarray.py
427
428
429
430
431
432
433
434
435
436
437
438
439
def matmul(self, other: QarrayImpl) -> QarrayImpl:
    """Matrix multiply ``self @ other``, coercing types as needed.

    Args:
        other: Right-hand operand.

    Returns:
        A ``DenseImpl`` containing the matrix product.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.matmul(b)
    return DenseImpl(self._data @ b._data)

mul(scalar)

Scalar multiplication.

Parameters:

Name Type Description Default
scalar

Scalar value.

required

Returns:

Type Description
QarrayImpl

A DenseImpl with each element multiplied by scalar.

Source code in jaxquantum/core/qarray.py
469
470
471
472
473
474
475
476
477
478
def mul(self, scalar) -> QarrayImpl:
    """Scalar multiplication.

    Args:
        scalar: Scalar value.

    Returns:
        A ``DenseImpl`` with each element multiplied by *scalar*.
    """
    return DenseImpl(scalar * self._data)

real()

Element-wise real part.

Returns:

Type Description
QarrayImpl

A DenseImpl containing the real parts.

Source code in jaxquantum/core/qarray.py
529
530
531
532
533
534
535
def real(self) -> QarrayImpl:
    """Element-wise real part.

    Returns:
        A ``DenseImpl`` containing the real parts.
    """
    return DenseImpl(jnp.real(self._data))

shape()

Shape of the underlying dense array.

Returns:

Type Description
tuple

Tuple of dimension sizes.

Source code in jaxquantum/core/qarray.py
505
506
507
508
509
510
511
def shape(self) -> tuple:
    """Shape of the underlying dense array.

    Returns:
        Tuple of dimension sizes.
    """
    return self._data.shape

sub(other)

Element-wise subtraction self - other, coercing types as needed.

Parameters:

Name Type Description Default
other QarrayImpl

Right-hand operand.

required

Returns:

Type Description
QarrayImpl

A DenseImpl containing the difference.

Source code in jaxquantum/core/qarray.py
455
456
457
458
459
460
461
462
463
464
465
466
467
def sub(self, other: QarrayImpl) -> QarrayImpl:
    """Element-wise subtraction ``self - other``, coercing types as needed.

    Args:
        other: Right-hand operand.

    Returns:
        A ``DenseImpl`` containing the difference.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.sub(b)
    return DenseImpl(self._data - b._data)

tidy_up(atol)

Zero out real/imaginary parts whose magnitude is below atol.

Parameters:

Name Type Description Default
atol

Absolute tolerance threshold.

required

Returns:

Type Description

A new DenseImpl with small values zeroed.

Source code in jaxquantum/core/qarray.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def tidy_up(self, atol):
    """Zero out real/imaginary parts whose magnitude is below *atol*.

    Args:
        atol: Absolute tolerance threshold.

    Returns:
        A new ``DenseImpl`` with small values zeroed.
    """
    data = self._data
    data_re = jnp.real(data)
    data_im = jnp.imag(data)
    data_re_mask = jnp.abs(data_re) > atol
    data_im_mask = jnp.abs(data_im) > atol
    data_new = data_re * data_re_mask + 1j * data_im * data_im_mask

    return DenseImpl(
        _data=data_new
    )

to_dense()

Return self (already dense).

Returns:

Type Description
'DenseImpl'

This DenseImpl instance unchanged.

Source code in jaxquantum/core/qarray.py
488
489
490
491
492
493
494
def to_dense(self) -> "DenseImpl":
    """Return self (already dense).

    Returns:
        This ``DenseImpl`` instance unchanged.
    """
    return self

to_sparse_bcoo()

Convert to a SparseBCOOImpl via BCOO.fromdense.

Returns:

Type Description
'SparseBCOOImpl'

A SparseBCOOImpl wrapping a BCOO conversion of this array.

Source code in jaxquantum/core/qarray.py
496
497
498
499
500
501
502
503
def to_sparse_bcoo(self) -> "SparseBCOOImpl":
    """Convert to a ``SparseBCOOImpl`` via ``BCOO.fromdense``.

    Returns:
        A ``SparseBCOOImpl`` wrapping a BCOO conversion of this array.
    """
    from jaxquantum.core.sparse_bcoo import SparseBCOOImpl
    return SparseBCOOImpl(sparse.BCOO.fromdense(self._data))

Qarray

Bases: Generic[ImplT]

Quantum array with a pluggable storage backend.

Qarray wraps a QarrayImpl together with quantum-mechanical dimension metadata (_qdims) and optional batch dimensions (_bdims). The default backend is dense (DenseImpl); pass implementation="sparse_bcoo" (or QarrayImplType.SPARSE_BCOO) to store data as a JAX BCOO sparse array.

Attributes:

Name Type Description
_impl ImplT

The storage backend holding the raw data.

_qdims Qdims

Quantum dimension metadata (bra/ket structure, Hilbert space sizes).

_bdims tuple[int]

Tuple of batch dimension sizes (empty tuple = non-batched).

Example

import jaxquantum as jqt a = jqt.destroy(10, implementation="sparse_bcoo") a.is_sparse_bcoo True

Source code in jaxquantum/core/qarray.py
 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
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 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
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 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
1111
1112
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
1207
1208
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
1351
1352
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
1400
1401
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
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
@struct.dataclass
class Qarray(Generic[ImplT]):
    """Quantum array with a pluggable storage backend.

    ``Qarray`` wraps a ``QarrayImpl`` together with quantum-mechanical
    dimension metadata (``_qdims``) and optional batch dimensions
    (``_bdims``).  The default backend is dense (``DenseImpl``); pass
    ``implementation="sparse_bcoo"`` (or ``QarrayImplType.SPARSE_BCOO``) to
    store data as a JAX BCOO sparse array.

    Attributes:
        _impl: The storage backend holding the raw data.
        _qdims: Quantum dimension metadata (bra/ket structure, Hilbert space
            sizes).
        _bdims: Tuple of batch dimension sizes (empty tuple = non-batched).

    Example:
        >>> import jaxquantum as jqt
        >>> a = jqt.destroy(10, implementation="sparse_bcoo")
        >>> a.is_sparse_bcoo
        True
    """

    _impl: ImplT
    _qdims: Qdims = struct.field(pytree_node=False)
    _bdims: tuple[int] = struct.field(pytree_node=False)

    # Initialization ----
    @classmethod
    @overload
    def create(cls, data, dims=None, bdims=None, implementation: Literal[QarrayImplType.DENSE] = QarrayImplType.DENSE) -> "Qarray[DenseImpl]":
        ...

    @classmethod
    @overload
    def create(cls, data, dims=None, bdims=None, implementation: Literal[QarrayImplType.SPARSE_BCOO] = ...) -> "Qarray[SparseBCOOImpl]":
        ...

    @classmethod
    @overload
    def create(cls, data, dims=None, bdims=None, implementation=...) -> "Qarray[DenseImpl]":
        ...

    @classmethod
    def create(cls, data, dims=None, bdims=None, implementation=QarrayImplType.DENSE):
        """Create a ``Qarray`` from raw data.

        Handles shape normalisation, dimension inference, and tidying of small
        values.

        Args:
            data: Input data array (dense array-like or ``sparse.BCOO``).
            dims: Quantum dimensions as ``((row_dims...), (col_dims...))``.
                Inferred from *data* shape when ``None``.
            bdims: Tuple of batch dimension sizes.  Inferred from the leading
                dimensions of *data* when ``None``.
            implementation: Storage backend — ``QarrayImplType.DENSE``
                (default) or ``QarrayImplType.SPARSE_BCOO``, or the equivalent
                string ``"dense"`` / ``"sparse_bcoo"``.

        Returns:
            A new ``Qarray`` backed by the requested implementation.
        """
        # Step 1: Prepare data ----
        data = robust_asarray(data)

        if len(data.shape) == 1 and data.shape[0] > 0:
            data = data.reshape(data.shape[0], 1)

        if len(data.shape) >= 2:
            if data.shape[-2] != data.shape[-1] and not (
                data.shape[-2] == 1 or data.shape[-1] == 1
            ):
                data = data.reshape(*data.shape[:-1], data.shape[-1], 1)

        if bdims is not None:
            if len(data.shape) - len(bdims) == 1:
                data = data.reshape(*data.shape[:-1], data.shape[-1], 1)
        # ----

        # Step 2: Prepare dimensions ----
        if bdims is None:
            bdims = tuple(data.shape[:-2])

        if dims is None:
            dims = ((data.shape[-2],), (data.shape[-1],))

        if not isinstance(dims[0], (list, tuple)):
            # This handles the case where only the hilbert space dimensions are sent in.
            if data.shape[-1] == 1:
                dims = (tuple(dims), tuple([1 for _ in dims]))
            elif data.shape[-2] == 1:
                dims = (tuple([1 for _ in dims]), tuple(dims))
            else:
                dims = (tuple(dims), tuple(dims))
        else:
            dims = (tuple(dims[0]), tuple(dims[1]))

        check_dims(dims, bdims, data.shape)

        qdims = Qdims(dims)

        # NOTE: Constantly tidying up on Qarray creation might be a bit overkill.
        # It increases the compilation time, but only very slightly
        # increased the runtime of the jit compiled function.
        # We could instead use this tidy up where we think we need it.

        impl_class = QarrayImplType(implementation).get_impl_class()
        impl = impl_class.from_data(data)
        impl = impl.tidy_up(SETTINGS["auto_tidyup_atol"])

        return cls(impl, qdims, bdims)

    @classmethod
    @overload
    def from_sparse_bcoo(cls, data, dims=None, bdims=None) -> "Qarray[SparseBCOOImpl]":
        ...

    @classmethod
    def from_sparse_bcoo(cls, data, dims=None, bdims=None):
        """Create a ``Qarray`` directly from a sparse BCOO array without densifying.

        Args:
            data: A ``sparse.BCOO`` or array-like to store as sparse BCOO.
            dims: Quantum dimensions.  Inferred when ``None``.
            bdims: Batch dimensions.  Inferred when ``None``.

        Returns:
            A ``Qarray[SparseBCOOImpl]``.
        """
        return cls.create(data, dims=dims, bdims=bdims, implementation=QarrayImplType.SPARSE_BCOO)

    @classmethod
    def from_sparse_dia(cls, data, dims=None, bdims=None) -> "Qarray":
        """Create a SparseDIA-backed ``Qarray``.

        Accepts either a dense array-like (diagonals are auto-detected) or a
        :class:`~jaxquantum.core.sparse_dia.SparseDiaData` container.

        Args:
            data: Dense array of shape (*batch, n, n) or a ``SparseDiaData``.
            dims: Quantum dimensions ``((row_dims,), (col_dims,))``.
            bdims: Batch dimension sizes.

        Returns:
            A ``Qarray`` backed by ``SparseDiaImpl``.
        """
        return cls.create(data, dims=dims, bdims=bdims, implementation=QarrayImplType.SPARSE_DIA)

    @classmethod
    @overload
    def from_list(cls, qarr_list: List["Qarray[DenseImpl]"]) -> "Qarray[DenseImpl]":
        ...

    @classmethod
    @overload
    def from_list(cls, qarr_list: List["Qarray[SparseBCOOImpl]"]) -> "Qarray[SparseBCOOImpl]":
        ...

    @classmethod
    def from_list(cls, qarr_list: List[Qarray]) -> Qarray:
        """Create a batched ``Qarray`` from a list of same-shaped ``Qarray`` objects.

        The output implementation is determined by the element with the highest
        ``PROMOTION_ORDER``: if all inputs are sparse the result is sparse; if
        any input is dense (or types are mixed) all inputs are promoted to dense
        and the result is dense.

        Args:
            qarr_list: List of ``Qarray`` objects with identical ``dims`` and
                ``bdims``.  May be empty.

        Returns:
            A ``Qarray`` with an extra leading batch dimension of size
            ``len(qarr_list)``.

        Raises:
            ValueError: If the elements have mismatched ``dims`` or ``bdims``.
        """
        if len(qarr_list) == 0:
            dims = ((), ())
            bdims = (0,)
            return cls.create(jnp.array([]), dims=dims, bdims=bdims)

        dims = qarr_list[0].dims
        bdims = qarr_list[0].bdims

        if not all(qarr.dims == dims and qarr.bdims == bdims for qarr in qarr_list):
            raise ValueError("All Qarrays in the list must have the same dimensions.")

        new_bdims = (len(qarr_list),) + bdims

        # Pick the target type: highest PROMOTION_ORDER wins (dense beats sparse).
        target_impl_type = max(
            (q.impl_type for q in qarr_list),
            key=lambda t: t.get_impl_class().PROMOTION_ORDER,
        )

        if target_impl_type == QarrayImplType.SPARSE_DIA:
            # All inputs are SparseDIA — batch without densifying.
            # Compute union of offsets across all operators, then remap each
            # operator's _diags rows into the union shape and stack.
            from jaxquantum.core.sparse_dia import SparseDiaData  # lazy to avoid circular
            union_offsets = tuple(sorted(
                set().union(*[set(q._impl._offsets) for q in qarr_list])
            ))
            union_idx = {k: i for i, k in enumerate(union_offsets)}
            n = qarr_list[0]._impl._diags.shape[-1]
            dtype = jnp.result_type(*[q._impl._diags.dtype for q in qarr_list])
            remapped = []
            for q in qarr_list:
                row = jnp.zeros((len(union_offsets), n), dtype=dtype)
                for i_src, k in enumerate(q._impl._offsets):
                    row = row.at[union_idx[k], :].set(q._impl._diags[i_src, :])
                remapped.append(row)
            stacked = jnp.stack(remapped, axis=0)  # (n_ops, n_union_diags, N)
            raw = SparseDiaData(offsets=union_offsets, diags=stacked)
            return cls.create(raw, dims=dims, bdims=new_bdims, implementation=QarrayImplType.SPARSE_DIA)

        if target_impl_type == QarrayImplType.SPARSE_BCOO:
            # All inputs are sparse BCOO — stack via dense intermediates then re-sparsify.
            data = jnp.array([q.data.todense() for q in qarr_list])
            return cls.create(data, dims=dims, bdims=new_bdims, implementation=QarrayImplType.SPARSE_BCOO)

        # Target is dense: promote any sparse inputs before stacking.
        data = jnp.array([q.to_dense().data for q in qarr_list])
        return cls.create(data, dims=dims, bdims=new_bdims, implementation=QarrayImplType.DENSE)

    @classmethod
    @overload
    def from_array(cls, qarr_arr: "Qarray[DenseImpl]") -> "Qarray[DenseImpl]":
        ...

    @classmethod
    @overload
    def from_array(cls, qarr_arr: "Qarray[SparseBCOOImpl]") -> "Qarray[SparseBCOOImpl]":
        ...

    @classmethod
    def from_array(cls, qarr_arr) -> Qarray:
        """Create a ``Qarray`` from a (possibly nested) list of ``Qarray`` objects.

        Args:
            qarr_arr: A ``Qarray`` (returned as-is) or a nested list of
                ``Qarray`` objects.

        Returns:
            A ``Qarray`` with batch dimensions matching the nesting structure
            of *qarr_arr*.
        """
        if isinstance(qarr_arr, Qarray):
            return qarr_arr

        bdims = ()
        lvl = qarr_arr
        while not isinstance(lvl, Qarray):
            bdims = bdims + (len(lvl),)
            if len(lvl) > 0:
                lvl = lvl[0]
            else:
                break

        def flat(lis):
            flatList = []
            for element in lis:
                if type(element) is list:
                    flatList += flat(element)
                else:
                    flatList.append(element)
            return flatList

        qarr_list = flat(qarr_arr)
        qarr = cls.from_list(qarr_list)
        qarr = qarr.reshape_bdims(*bdims)
        return qarr

    # Properties ----
    @property
    def qtype(self):
        """Quantum type of this array (ket, bra, or operator)."""
        return self._qdims.qtype

    @property
    def dtype(self):
        """Data type of the underlying storage array."""
        return self._impl.dtype()

    @property
    def dims(self):
        """Quantum dimensions as ``((row_dims...), (col_dims...))``."""
        return self._qdims.dims

    @property
    def bdims(self):
        """Tuple of batch dimension sizes (empty tuple = non-batched)."""
        return self._bdims

    @property
    def qdims(self):
        """The ``Qdims`` metadata object for this array."""
        return self._qdims

    @property
    def space_dims(self):
        """Hilbert space dimensions for the relevant side (ket row / bra col)."""
        if self.qtype in [Qtypes.oper, Qtypes.ket]:
            return self.dims[0]
        elif self.qtype == Qtypes.bra:
            return self.dims[1]
        else:
            # TODO: not reached for some reason
            raise ValueError("Unsupported qtype.")

    @property
    def data(self):
        """The raw underlying data (dense ``jnp.ndarray`` or ``sparse.BCOO``)."""
        return self._impl.data

    @property
    def shaped_data(self):
        """Data reshaped to ``bdims + dims[0] + dims[1]``."""
        return self.data.reshape(self.bdims + self.dims[0] + self.dims[1])

    @property
    def shape(self):
        """Shape of the underlying data array."""
        return self.data.shape

    @property
    def is_batched(self):
        """True if this array has one or more batch dimensions."""
        return len(self.bdims) > 0

    @property
    def is_sparse_bcoo(self):
        """True if the storage backend is ``SparseBCOOImpl`` (BCOO)."""
        return self._impl.impl_type == QarrayImplType.SPARSE_BCOO

    @property
    def is_dense(self):
        """True if the storage backend is ``DenseImpl``."""
        return self._impl.impl_type == QarrayImplType.DENSE

    @property
    def is_sparse_dia(self):
        """True if the storage backend is ``SparseDiaImpl``."""
        return self._impl.impl_type == QarrayImplType.SPARSE_DIA

    @property
    def impl_type(self):
        """The ``QarrayImplType`` member of the current storage backend."""
        return self._impl.impl_type

    def to_sparse_bcoo(self) -> "Qarray[SparseBCOOImpl]":
        """Return a BCOO-sparse-backed copy of this array.

        If the array is already sparse BCOO, returns self unchanged.

        Returns:
            A ``Qarray[SparseBCOOImpl]``.
        """
        if self.is_sparse_bcoo:
            return self
        new_impl = self._impl.to_sparse_bcoo()
        return Qarray(new_impl, self._qdims, self._bdims)

    def to_sparse_dia(self) -> "Qarray":
        """Return a SparseDIA-backed copy of this array.

        If the array is already SparseDIA, returns self unchanged.

        Returns:
            A ``Qarray[SparseDiaImpl]``.
        """
        if self.is_sparse_dia:
            return self
        new_impl = self._impl.to_sparse_dia()
        return Qarray(new_impl, self._qdims, self._bdims)

    def to_dense(self) -> "Qarray[DenseImpl]":
        """Return a dense-backed copy of this array.

        If the array is already dense, returns self unchanged.

        Returns:
            A ``Qarray[DenseImpl]``.
        """
        if self.is_dense:
            return self
        new_impl = self._impl.to_dense()
        return Qarray(new_impl, self._qdims, self._bdims)

    def __getitem__(self, index):
        if len(self.bdims) > 0:
            return Qarray.create(
                self.data[index],
                dims=self.dims,
                implementation=self.impl_type,
            )
        else:
            raise ValueError("Cannot index a non-batched Qarray.")

    def reshape_bdims(self, *args):
        """Reshape the batch dimensions of this ``Qarray``.

        Args:
            *args: New batch dimension sizes.

        Returns:
            A new ``Qarray`` with the requested batch shape.
        """
        new_bdims = tuple(args)

        if prod(new_bdims) == 0:
            new_shape = new_bdims
        else:
            new_shape = new_bdims + (prod(self.dims[0]),) + (-1,)

        # Preserve implementation type
        implementation = self.impl_type
        return Qarray.create(
            self.data.reshape(new_shape),
            dims=self.dims,
            bdims=new_bdims,
            implementation=implementation,
        )

    def space_to_qdims(self, space_dims: List[int]):
        """Convert Hilbert space dimensions to full quantum dims tuple.

        Args:
            space_dims: Sequence of per-subsystem Hilbert space sizes, or a
                full ``((row_dims), (col_dims))`` tuple (returned unchanged).

        Returns:
            A ``((row_dims...), (col_dims...))`` tuple.

        Raises:
            ValueError: If ``self.qtype`` is not ket, bra, or oper.
        """
        if isinstance(space_dims[0], (list, tuple)):
            return space_dims

        if self.qtype in [Qtypes.oper, Qtypes.ket]:
            return (tuple(space_dims), tuple([1 for _ in range(len(space_dims))]))
        elif self.qtype == Qtypes.bra:
            return (tuple([1 for _ in range(len(space_dims))]), tuple(space_dims))
        else:
            raise ValueError("Unsupported qtype for space_to_qdims conversion.")

    def reshape_qdims(self, *args):
        """Reshape the quantum dimensions of the Qarray.

        Note that this does not take in qdims but rather the new Hilbert space
        dimensions.

        Args:
            *args: New Hilbert dimensions for the Qarray.

        Returns:
            Qarray: reshaped Qarray.
        """

        new_space_dims = tuple(args)
        current_space_dims = self.space_dims
        assert prod(new_space_dims) == prod(current_space_dims)

        new_qdims = self.space_to_qdims(new_space_dims)
        new_bdims = self.bdims

        # Preserve implementation type
        implementation = self.impl_type
        return Qarray.create(self.data, dims=new_qdims, bdims=new_bdims, implementation=implementation)

    def resize(self, new_shape):
        """Resize the Qarray to a new shape.

        TODO: review and maybe deprecate this method.

        Args:
            new_shape: Target shape tuple.

        Returns:
            A new ``Qarray`` with data resized via ``jnp.resize``.
        """
        dims = self.dims
        data = jnp.resize(self.data, new_shape)
        # Preserve implementation type
        implementation = self.impl_type
        return Qarray.create(
            data,
            dims=dims,
            implementation=implementation,
        )

    def __len__(self):
        """Length along the first batch dimension.

        Returns:
            Size of the leading batch dimension.

        Raises:
            ValueError: If the array is not batched.
        """
        if len(self.bdims) > 0:
            return self.data.shape[0]
        else:
            raise ValueError("Cannot get length of a non-batched Qarray.")

    def __eq__(self, other):
        if not isinstance(other, Qarray):
            raise ValueError("Cannot calculate equality of a Qarray with a non-Qarray.")

        if self.dims != other.dims:
            return False

        if self.bdims != other.bdims:
            return False

        if self.is_sparse_bcoo and other.is_sparse_bcoo:
            # Fast structural path: same sparsity pattern → compare values only (no todense)
            if (self.data.indices.shape == other.data.indices.shape
                    and bool(jnp.all(self.data.indices == other.data.indices))):
                return bool(jnp.allclose(self.data.data, other.data.data))
            # Different patterns: fall back to dense comparison (unavoidable)
            return bool(jnp.all(self.data.todense() == other.data.todense()))

        # At least one dense: convert sparse side to dense for comparison
        self_data  = self.data.todense()  if hasattr(self.data,  'todense') else self.data
        other_data = other.data.todense() if hasattr(other.data, 'todense') else other.data
        return bool(jnp.all(self_data == other_data))

    def __ne__(self, other):
        return not self.__eq__(other)

    # Elementary Math ----
    def __matmul__(self, other):
        if not isinstance(other, Qarray):
            return NotImplemented

        _qdims_new = self._qdims @ other._qdims
        new_impl = self._impl.matmul(other._impl)

        return Qarray.create(
            new_impl.data,
            dims=_qdims_new.dims,
            implementation=new_impl.impl_type,
        )

    def __mul__(self, other):
        if isinstance(other, Qarray):
            return self.__matmul__(other)

        other = other + 0.0j
        if not robust_isscalar(other) and len(other.shape) > 0:  # not a scalar
            other = other.reshape(other.shape + (1, 1))

        new_impl = self._impl.mul(other)
        return Qarray.create(
            new_impl.data,
            dims=self._qdims.dims,
            implementation=new_impl.impl_type,
        )

    def __rmul__(self, other):
        return self.__mul__(other)

    def __neg__(self):
        return self.__mul__(-1)

    def __truediv__(self, other):
        """Divide by a scalar.

        Args:
            other: Scalar divisor.

        Returns:
            A new ``Qarray`` with all elements divided by *other*.

        Raises:
            ValueError: If *other* is a ``Qarray``.
        """
        if isinstance(other, Qarray):
            raise ValueError("Cannot divide a Qarray by another Qarray.")

        return self.__mul__(1 / other)

    def __add__(self, other):
        if isinstance(other, Qarray):
            if self.dims != other.dims:
                msg = (
                    "Dimensions are incompatible: "
                    + repr(self.dims)
                    + " and "
                    + repr(other.dims)
                )
                raise ValueError(msg)
            new_impl = self._impl.add(other._impl)
            return Qarray.create(
                new_impl.data,
                dims=self.dims,
                implementation=new_impl.impl_type,
            )

        if robust_isscalar(other) and other == 0:
            return self.copy()

        if self.data.shape[-2] == self.data.shape[-1]:
            other = other + 0.0j
            if not robust_isscalar(other) and len(other.shape) > 0:  # not a scalar
                other = other.reshape(other.shape + (1, 1))
            eye_data = self._impl._eye_data(self.data.shape[-2], dtype=self.data.dtype)
            other = Qarray.create(
                other * eye_data,
                dims=self.dims,
                implementation=self.impl_type
            )
            return self.__add__(other)

        return NotImplemented

    def __radd__(self, other):
        return self.__add__(other)

    def __sub__(self, other):
        if isinstance(other, Qarray):
            if self.dims != other.dims:
                msg = (
                    "Dimensions are incompatible: "
                    + repr(self.dims)
                    + " and "
                    + repr(other.dims)
                )
                raise ValueError(msg)
            new_impl = self._impl.sub(other._impl)
            return Qarray.create(
                new_impl.data,
                dims=self.dims,
                implementation=new_impl.impl_type,
            )

        if robust_isscalar(other) and other == 0:
            return self.copy()

        if self.data.shape[-2] == self.data.shape[-1]:
            other = other + 0.0j

            if not robust_isscalar(other) and len(other.shape) > 0:  # not a scalar
                other = other.reshape(other.shape + (1, 1))
            eye_data = self._impl._eye_data(self.data.shape[-2], dtype=self.data.dtype)
            other = Qarray.create(
                other * eye_data,
                dims=self.dims,
                implementation=self.impl_type
            )
            return self.__sub__(other)

        return NotImplemented

    def __rsub__(self, other):
        return self.__neg__().__add__(other)

    def __xor__(self, other):
        if not isinstance(other, Qarray):
            return NotImplemented
        return tensor(self, other)

    def __rxor__(self, other):
        if not isinstance(other, Qarray):
            return NotImplemented
        return tensor(other, self)

    def __pow__(self, other):
        if not isinstance(other, int):
            return NotImplemented

        return powm(self, other)

    # String Representation ----
    def _str_header(self):
        """Build the one-line header string for ``__str__`` and ``__repr__``."""
        impl_type = self.impl_type.value
        out = ", ".join(
            [
                "Quantum array: dims = " + str(self.dims),
                "bdims = " + str(self.bdims),
                "shape = " + str(self.data.shape),
                "type = " + str(self.qtype),
                "impl = " + impl_type,
            ]
        )
        return out

    def __str__(self):
        return self._str_header() + "\nQarray data =\n" + str(self.data)

    @property
    def header(self):
        """One-line header string describing dimensions, shape, and backend."""
        return self._str_header()

    def __repr__(self):
        return self.__str__()

    # Utilities ----
    def copy(self, memo=None):
        """Return a deep copy of this ``Qarray``.

        Args:
            memo: Optional memo dict forwarded to ``deepcopy``.

        Returns:
            A new ``Qarray`` with independent copies of all data.
        """
        return self.__deepcopy__(memo)

    def __deepcopy__(self, memo):
        """Need to override this when defining __getattr__."""

        return Qarray(
            _impl=deepcopy(self._impl, memo=memo),
            _qdims=deepcopy(self._qdims, memo=memo),
            _bdims=deepcopy(self._bdims, memo=memo),
        )

    def __getattr__(self, method_name):
        if "__" == method_name[:2]:
            # NOTE: we return NotImplemented for binary special methods logic in python, plus things like __jax_array__
            return lambda *args, **kwargs: NotImplemented

        modules = [jnp, jnp.linalg, jsp, jsp.linalg]

        method_f = None
        for mod in modules:
            method_f = getattr(mod, method_name, None)
            if method_f is not None:
                break

        if method_f is None:
            raise NotImplementedError(
                f"Method {method_name} does not exist. No backup method found in {modules}."
            )

        def func(*args, **kwargs):
            # For operations that might not be supported in sparse, convert to dense
            if self.is_sparse_bcoo:
                dense_self = self.to_dense()
                res = method_f(dense_self.data, *args, **kwargs)
            else:
                res = method_f(self.data, *args, **kwargs)

            if getattr(res, "shape", None) is None or res.shape != self.data.shape:
                return res
            else:
                # Preserve implementation type
                return Qarray.create(res, dims=self._qdims.dims, implementation=self.impl_type)

        return func

    # Conversions / Reshaping ----
    def dag(self):
        """Conjugate transpose of this array."""
        return dag(self)

    def to_dm(self):
        """Convert a ket to a density matrix via outer product."""
        return ket2dm(self)

    def is_dm(self):
        """Return True if this array is an operator (density-matrix type)."""
        return self.qtype == Qtypes.oper

    def is_vec(self):
        """Return True if this array is a ket or bra."""
        return self.qtype == Qtypes.ket or self.qtype == Qtypes.bra

    def to_ket(self):
        """Convert a bra to a ket (no-op for kets)."""
        return to_ket(self)

    def transpose(self, *args):
        """Transpose subsystem indices."""
        return transpose(self, *args)

    def keep_only_diag_elements(self):
        """Zero out all off-diagonal elements."""
        return keep_only_diag_elements(self)

    # Math Functions ----
    def unit(self):
        """Return the normalised (unit-norm) version of this array."""
        return unit(self)

    def norm(self):
        """Compute the norm of this array."""
        return norm(self)

    def frobenius_norm(self):
        """Compute the Frobenius norm directly from the implementation.

        Returns:
            The Frobenius norm as a scalar.
        """
        return self._impl.frobenius_norm()

    def real(self):
        """Element-wise real part.

        Returns:
            A new ``Qarray`` containing the real parts of each element.
        """
        new_impl = self._impl.real()
        return Qarray.create(
            new_impl.data,
            dims=self.dims,
            implementation=new_impl.impl_type,
        )

    def imag(self):
        """Element-wise imaginary part.

        Returns:
            A new ``Qarray`` containing the imaginary parts of each element.
        """
        new_impl = self._impl.imag()

        return Qarray.create(
            new_impl.data,
            dims=self.dims,
            implementation=new_impl.impl_type,
        )

    def conj(self):
        """Element-wise complex conjugate.

        Returns:
            A new ``Qarray`` containing the complex-conjugated elements.
        """
        new_impl = self._impl.conj()
        return Qarray.create(
            new_impl.data,
            dims=self.dims,
            implementation=new_impl.impl_type,
        )

    def expm(self):
        """Matrix exponential."""
        return expm(self)

    def powm(self, n):
        """Matrix power.

        Args:
            n: Exponent (integer or float).

        Returns:
            This array raised to the *n*-th matrix power.
        """
        return powm(self, n)

    def cosm(self):
        """Matrix cosine."""
        return cosm(self)

    def sinm(self):
        """Matrix sine."""
        return sinm(self)

    def tr(self, **kwargs):
        """Full trace."""
        return tr(self, **kwargs)

    def trace(self, **kwargs):
        """Full trace (alias for :meth:`tr`)."""
        return tr(self, **kwargs)

    def ptrace(self, indx):
        """Partial trace over subsystem *indx*.

        Args:
            indx: Index of the subsystem to trace out.

        Returns:
            Reduced density matrix.
        """
        return ptrace(self, indx)

    def eigenstates(self):
        """Eigenvalues and eigenstates of this operator."""
        return eigenstates(self)

    def eigenenergies(self):
        """Eigenvalues of this operator."""
        return eigenenergies(self)

    def eigenvalues(self):
        """Eigenvalues of this operator (alias for :meth:`eigenenergies`)."""
        return eigenenergies(self)

    def collapse(self, mode="sum"):
        """Collapse batch dimensions.

        Args:
            mode: Collapse strategy — currently only ``"sum"`` is supported.

        Returns:
            A non-batched ``Qarray``.
        """
        return collapse(self, mode=mode)

bdims property

Tuple of batch dimension sizes (empty tuple = non-batched).

data property

The raw underlying data (dense jnp.ndarray or sparse.BCOO).

dims property

Quantum dimensions as ((row_dims...), (col_dims...)).

dtype property

Data type of the underlying storage array.

header property

One-line header string describing dimensions, shape, and backend.

impl_type property

The QarrayImplType member of the current storage backend.

is_batched property

True if this array has one or more batch dimensions.

is_dense property

True if the storage backend is DenseImpl.

is_sparse_bcoo property

True if the storage backend is SparseBCOOImpl (BCOO).

is_sparse_dia property

True if the storage backend is SparseDiaImpl.

qdims property

The Qdims metadata object for this array.

qtype property

Quantum type of this array (ket, bra, or operator).

shape property

Shape of the underlying data array.

shaped_data property

Data reshaped to bdims + dims[0] + dims[1].

space_dims property

Hilbert space dimensions for the relevant side (ket row / bra col).

__deepcopy__(memo)

Need to override this when defining getattr.

Source code in jaxquantum/core/qarray.py
1359
1360
1361
1362
1363
1364
1365
1366
def __deepcopy__(self, memo):
    """Need to override this when defining __getattr__."""

    return Qarray(
        _impl=deepcopy(self._impl, memo=memo),
        _qdims=deepcopy(self._qdims, memo=memo),
        _bdims=deepcopy(self._bdims, memo=memo),
    )

__len__()

Length along the first batch dimension.

Returns:

Type Description

Size of the leading batch dimension.

Raises:

Type Description
ValueError

If the array is not batched.

Source code in jaxquantum/core/qarray.py
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
def __len__(self):
    """Length along the first batch dimension.

    Returns:
        Size of the leading batch dimension.

    Raises:
        ValueError: If the array is not batched.
    """
    if len(self.bdims) > 0:
        return self.data.shape[0]
    else:
        raise ValueError("Cannot get length of a non-batched Qarray.")

__truediv__(other)

Divide by a scalar.

Parameters:

Name Type Description Default
other

Scalar divisor.

required

Returns:

Type Description

A new Qarray with all elements divided by other.

Raises:

Type Description
ValueError

If other is a Qarray.

Source code in jaxquantum/core/qarray.py
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
def __truediv__(self, other):
    """Divide by a scalar.

    Args:
        other: Scalar divisor.

    Returns:
        A new ``Qarray`` with all elements divided by *other*.

    Raises:
        ValueError: If *other* is a ``Qarray``.
    """
    if isinstance(other, Qarray):
        raise ValueError("Cannot divide a Qarray by another Qarray.")

    return self.__mul__(1 / other)

collapse(mode='sum')

Collapse batch dimensions.

Parameters:

Name Type Description Default
mode

Collapse strategy — currently only "sum" is supported.

'sum'

Returns:

Type Description

A non-batched Qarray.

Source code in jaxquantum/core/qarray.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
def collapse(self, mode="sum"):
    """Collapse batch dimensions.

    Args:
        mode: Collapse strategy — currently only ``"sum"`` is supported.

    Returns:
        A non-batched ``Qarray``.
    """
    return collapse(self, mode=mode)

conj()

Element-wise complex conjugate.

Returns:

Type Description

A new Qarray containing the complex-conjugated elements.

Source code in jaxquantum/core/qarray.py
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
def conj(self):
    """Element-wise complex conjugate.

    Returns:
        A new ``Qarray`` containing the complex-conjugated elements.
    """
    new_impl = self._impl.conj()
    return Qarray.create(
        new_impl.data,
        dims=self.dims,
        implementation=new_impl.impl_type,
    )

copy(memo=None)

Return a deep copy of this Qarray.

Parameters:

Name Type Description Default
memo

Optional memo dict forwarded to deepcopy.

None

Returns:

Type Description

A new Qarray with independent copies of all data.

Source code in jaxquantum/core/qarray.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
def copy(self, memo=None):
    """Return a deep copy of this ``Qarray``.

    Args:
        memo: Optional memo dict forwarded to ``deepcopy``.

    Returns:
        A new ``Qarray`` with independent copies of all data.
    """
    return self.__deepcopy__(memo)

cosm()

Matrix cosine.

Source code in jaxquantum/core/qarray.py
1503
1504
1505
def cosm(self):
    """Matrix cosine."""
    return cosm(self)

create(data, dims=None, bdims=None, implementation=QarrayImplType.DENSE) classmethod

create(data, dims=None, bdims=None, implementation: Literal[QarrayImplType.DENSE] = QarrayImplType.DENSE) -> 'Qarray[DenseImpl]'
create(data, dims=None, bdims=None, implementation: Literal[QarrayImplType.SPARSE_BCOO] = ...) -> 'Qarray[SparseBCOOImpl]'
create(data, dims=None, bdims=None, implementation=...) -> 'Qarray[DenseImpl]'

Create a Qarray from raw data.

Handles shape normalisation, dimension inference, and tidying of small values.

Parameters:

Name Type Description Default
data

Input data array (dense array-like or sparse.BCOO).

required
dims

Quantum dimensions as ((row_dims...), (col_dims...)). Inferred from data shape when None.

None
bdims

Tuple of batch dimension sizes. Inferred from the leading dimensions of data when None.

None
implementation

Storage backend — QarrayImplType.DENSE (default) or QarrayImplType.SPARSE_BCOO, or the equivalent string "dense" / "sparse_bcoo".

DENSE

Returns:

Type Description

A new Qarray backed by the requested implementation.

Source code in jaxquantum/core/qarray.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
@classmethod
def create(cls, data, dims=None, bdims=None, implementation=QarrayImplType.DENSE):
    """Create a ``Qarray`` from raw data.

    Handles shape normalisation, dimension inference, and tidying of small
    values.

    Args:
        data: Input data array (dense array-like or ``sparse.BCOO``).
        dims: Quantum dimensions as ``((row_dims...), (col_dims...))``.
            Inferred from *data* shape when ``None``.
        bdims: Tuple of batch dimension sizes.  Inferred from the leading
            dimensions of *data* when ``None``.
        implementation: Storage backend — ``QarrayImplType.DENSE``
            (default) or ``QarrayImplType.SPARSE_BCOO``, or the equivalent
            string ``"dense"`` / ``"sparse_bcoo"``.

    Returns:
        A new ``Qarray`` backed by the requested implementation.
    """
    # Step 1: Prepare data ----
    data = robust_asarray(data)

    if len(data.shape) == 1 and data.shape[0] > 0:
        data = data.reshape(data.shape[0], 1)

    if len(data.shape) >= 2:
        if data.shape[-2] != data.shape[-1] and not (
            data.shape[-2] == 1 or data.shape[-1] == 1
        ):
            data = data.reshape(*data.shape[:-1], data.shape[-1], 1)

    if bdims is not None:
        if len(data.shape) - len(bdims) == 1:
            data = data.reshape(*data.shape[:-1], data.shape[-1], 1)
    # ----

    # Step 2: Prepare dimensions ----
    if bdims is None:
        bdims = tuple(data.shape[:-2])

    if dims is None:
        dims = ((data.shape[-2],), (data.shape[-1],))

    if not isinstance(dims[0], (list, tuple)):
        # This handles the case where only the hilbert space dimensions are sent in.
        if data.shape[-1] == 1:
            dims = (tuple(dims), tuple([1 for _ in dims]))
        elif data.shape[-2] == 1:
            dims = (tuple([1 for _ in dims]), tuple(dims))
        else:
            dims = (tuple(dims), tuple(dims))
    else:
        dims = (tuple(dims[0]), tuple(dims[1]))

    check_dims(dims, bdims, data.shape)

    qdims = Qdims(dims)

    # NOTE: Constantly tidying up on Qarray creation might be a bit overkill.
    # It increases the compilation time, but only very slightly
    # increased the runtime of the jit compiled function.
    # We could instead use this tidy up where we think we need it.

    impl_class = QarrayImplType(implementation).get_impl_class()
    impl = impl_class.from_data(data)
    impl = impl.tidy_up(SETTINGS["auto_tidyup_atol"])

    return cls(impl, qdims, bdims)

dag()

Conjugate transpose of this array.

Source code in jaxquantum/core/qarray.py
1403
1404
1405
def dag(self):
    """Conjugate transpose of this array."""
    return dag(self)

eigenenergies()

Eigenvalues of this operator.

Source code in jaxquantum/core/qarray.py
1534
1535
1536
def eigenenergies(self):
    """Eigenvalues of this operator."""
    return eigenenergies(self)

eigenstates()

Eigenvalues and eigenstates of this operator.

Source code in jaxquantum/core/qarray.py
1530
1531
1532
def eigenstates(self):
    """Eigenvalues and eigenstates of this operator."""
    return eigenstates(self)

eigenvalues()

Eigenvalues of this operator (alias for :meth:eigenenergies).

Source code in jaxquantum/core/qarray.py
1538
1539
1540
def eigenvalues(self):
    """Eigenvalues of this operator (alias for :meth:`eigenenergies`)."""
    return eigenenergies(self)

expm()

Matrix exponential.

Source code in jaxquantum/core/qarray.py
1488
1489
1490
def expm(self):
    """Matrix exponential."""
    return expm(self)

frobenius_norm()

Compute the Frobenius norm directly from the implementation.

Returns:

Type Description

The Frobenius norm as a scalar.

Source code in jaxquantum/core/qarray.py
1440
1441
1442
1443
1444
1445
1446
def frobenius_norm(self):
    """Compute the Frobenius norm directly from the implementation.

    Returns:
        The Frobenius norm as a scalar.
    """
    return self._impl.frobenius_norm()

from_array(qarr_arr) classmethod

from_array(qarr_arr: 'Qarray[DenseImpl]') -> 'Qarray[DenseImpl]'
from_array(qarr_arr: 'Qarray[SparseBCOOImpl]') -> 'Qarray[SparseBCOOImpl]'

Create a Qarray from a (possibly nested) list of Qarray objects.

Parameters:

Name Type Description Default
qarr_arr

A Qarray (returned as-is) or a nested list of Qarray objects.

required

Returns:

Type Description
Qarray

A Qarray with batch dimensions matching the nesting structure

Qarray

of qarr_arr.

Source code in jaxquantum/core/qarray.py
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
@classmethod
def from_array(cls, qarr_arr) -> Qarray:
    """Create a ``Qarray`` from a (possibly nested) list of ``Qarray`` objects.

    Args:
        qarr_arr: A ``Qarray`` (returned as-is) or a nested list of
            ``Qarray`` objects.

    Returns:
        A ``Qarray`` with batch dimensions matching the nesting structure
        of *qarr_arr*.
    """
    if isinstance(qarr_arr, Qarray):
        return qarr_arr

    bdims = ()
    lvl = qarr_arr
    while not isinstance(lvl, Qarray):
        bdims = bdims + (len(lvl),)
        if len(lvl) > 0:
            lvl = lvl[0]
        else:
            break

    def flat(lis):
        flatList = []
        for element in lis:
            if type(element) is list:
                flatList += flat(element)
            else:
                flatList.append(element)
        return flatList

    qarr_list = flat(qarr_arr)
    qarr = cls.from_list(qarr_list)
    qarr = qarr.reshape_bdims(*bdims)
    return qarr

from_list(qarr_list) classmethod

from_list(qarr_list: List['Qarray[DenseImpl]']) -> 'Qarray[DenseImpl]'
from_list(qarr_list: List['Qarray[SparseBCOOImpl]']) -> 'Qarray[SparseBCOOImpl]'

Create a batched Qarray from a list of same-shaped Qarray objects.

The output implementation is determined by the element with the highest PROMOTION_ORDER: if all inputs are sparse the result is sparse; if any input is dense (or types are mixed) all inputs are promoted to dense and the result is dense.

Parameters:

Name Type Description Default
qarr_list List[Qarray]

List of Qarray objects with identical dims and bdims. May be empty.

required

Returns:

Type Description
Qarray

A Qarray with an extra leading batch dimension of size

Qarray

len(qarr_list).

Raises:

Type Description
ValueError

If the elements have mismatched dims or bdims.

Source code in jaxquantum/core/qarray.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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
@classmethod
def from_list(cls, qarr_list: List[Qarray]) -> Qarray:
    """Create a batched ``Qarray`` from a list of same-shaped ``Qarray`` objects.

    The output implementation is determined by the element with the highest
    ``PROMOTION_ORDER``: if all inputs are sparse the result is sparse; if
    any input is dense (or types are mixed) all inputs are promoted to dense
    and the result is dense.

    Args:
        qarr_list: List of ``Qarray`` objects with identical ``dims`` and
            ``bdims``.  May be empty.

    Returns:
        A ``Qarray`` with an extra leading batch dimension of size
        ``len(qarr_list)``.

    Raises:
        ValueError: If the elements have mismatched ``dims`` or ``bdims``.
    """
    if len(qarr_list) == 0:
        dims = ((), ())
        bdims = (0,)
        return cls.create(jnp.array([]), dims=dims, bdims=bdims)

    dims = qarr_list[0].dims
    bdims = qarr_list[0].bdims

    if not all(qarr.dims == dims and qarr.bdims == bdims for qarr in qarr_list):
        raise ValueError("All Qarrays in the list must have the same dimensions.")

    new_bdims = (len(qarr_list),) + bdims

    # Pick the target type: highest PROMOTION_ORDER wins (dense beats sparse).
    target_impl_type = max(
        (q.impl_type for q in qarr_list),
        key=lambda t: t.get_impl_class().PROMOTION_ORDER,
    )

    if target_impl_type == QarrayImplType.SPARSE_DIA:
        # All inputs are SparseDIA — batch without densifying.
        # Compute union of offsets across all operators, then remap each
        # operator's _diags rows into the union shape and stack.
        from jaxquantum.core.sparse_dia import SparseDiaData  # lazy to avoid circular
        union_offsets = tuple(sorted(
            set().union(*[set(q._impl._offsets) for q in qarr_list])
        ))
        union_idx = {k: i for i, k in enumerate(union_offsets)}
        n = qarr_list[0]._impl._diags.shape[-1]
        dtype = jnp.result_type(*[q._impl._diags.dtype for q in qarr_list])
        remapped = []
        for q in qarr_list:
            row = jnp.zeros((len(union_offsets), n), dtype=dtype)
            for i_src, k in enumerate(q._impl._offsets):
                row = row.at[union_idx[k], :].set(q._impl._diags[i_src, :])
            remapped.append(row)
        stacked = jnp.stack(remapped, axis=0)  # (n_ops, n_union_diags, N)
        raw = SparseDiaData(offsets=union_offsets, diags=stacked)
        return cls.create(raw, dims=dims, bdims=new_bdims, implementation=QarrayImplType.SPARSE_DIA)

    if target_impl_type == QarrayImplType.SPARSE_BCOO:
        # All inputs are sparse BCOO — stack via dense intermediates then re-sparsify.
        data = jnp.array([q.data.todense() for q in qarr_list])
        return cls.create(data, dims=dims, bdims=new_bdims, implementation=QarrayImplType.SPARSE_BCOO)

    # Target is dense: promote any sparse inputs before stacking.
    data = jnp.array([q.to_dense().data for q in qarr_list])
    return cls.create(data, dims=dims, bdims=new_bdims, implementation=QarrayImplType.DENSE)

from_sparse_bcoo(data, dims=None, bdims=None) classmethod

from_sparse_bcoo(data, dims=None, bdims=None) -> 'Qarray[SparseBCOOImpl]'

Create a Qarray directly from a sparse BCOO array without densifying.

Parameters:

Name Type Description Default
data

A sparse.BCOO or array-like to store as sparse BCOO.

required
dims

Quantum dimensions. Inferred when None.

None
bdims

Batch dimensions. Inferred when None.

None

Returns:

Type Description

A Qarray[SparseBCOOImpl].

Source code in jaxquantum/core/qarray.py
761
762
763
764
765
766
767
768
769
770
771
772
773
@classmethod
def from_sparse_bcoo(cls, data, dims=None, bdims=None):
    """Create a ``Qarray`` directly from a sparse BCOO array without densifying.

    Args:
        data: A ``sparse.BCOO`` or array-like to store as sparse BCOO.
        dims: Quantum dimensions.  Inferred when ``None``.
        bdims: Batch dimensions.  Inferred when ``None``.

    Returns:
        A ``Qarray[SparseBCOOImpl]``.
    """
    return cls.create(data, dims=dims, bdims=bdims, implementation=QarrayImplType.SPARSE_BCOO)

from_sparse_dia(data, dims=None, bdims=None) classmethod

Create a SparseDIA-backed Qarray.

Accepts either a dense array-like (diagonals are auto-detected) or a :class:~jaxquantum.core.sparse_dia.SparseDiaData container.

Parameters:

Name Type Description Default
data

Dense array of shape (*batch, n, n) or a SparseDiaData.

required
dims

Quantum dimensions ((row_dims,), (col_dims,)).

None
bdims

Batch dimension sizes.

None

Returns:

Type Description
'Qarray'

A Qarray backed by SparseDiaImpl.

Source code in jaxquantum/core/qarray.py
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
@classmethod
def from_sparse_dia(cls, data, dims=None, bdims=None) -> "Qarray":
    """Create a SparseDIA-backed ``Qarray``.

    Accepts either a dense array-like (diagonals are auto-detected) or a
    :class:`~jaxquantum.core.sparse_dia.SparseDiaData` container.

    Args:
        data: Dense array of shape (*batch, n, n) or a ``SparseDiaData``.
        dims: Quantum dimensions ``((row_dims,), (col_dims,))``.
        bdims: Batch dimension sizes.

    Returns:
        A ``Qarray`` backed by ``SparseDiaImpl``.
    """
    return cls.create(data, dims=dims, bdims=bdims, implementation=QarrayImplType.SPARSE_DIA)

imag()

Element-wise imaginary part.

Returns:

Type Description

A new Qarray containing the imaginary parts of each element.

Source code in jaxquantum/core/qarray.py
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
def imag(self):
    """Element-wise imaginary part.

    Returns:
        A new ``Qarray`` containing the imaginary parts of each element.
    """
    new_impl = self._impl.imag()

    return Qarray.create(
        new_impl.data,
        dims=self.dims,
        implementation=new_impl.impl_type,
    )

is_dm()

Return True if this array is an operator (density-matrix type).

Source code in jaxquantum/core/qarray.py
1411
1412
1413
def is_dm(self):
    """Return True if this array is an operator (density-matrix type)."""
    return self.qtype == Qtypes.oper

is_vec()

Return True if this array is a ket or bra.

Source code in jaxquantum/core/qarray.py
1415
1416
1417
def is_vec(self):
    """Return True if this array is a ket or bra."""
    return self.qtype == Qtypes.ket or self.qtype == Qtypes.bra

keep_only_diag_elements()

Zero out all off-diagonal elements.

Source code in jaxquantum/core/qarray.py
1427
1428
1429
def keep_only_diag_elements(self):
    """Zero out all off-diagonal elements."""
    return keep_only_diag_elements(self)

norm()

Compute the norm of this array.

Source code in jaxquantum/core/qarray.py
1436
1437
1438
def norm(self):
    """Compute the norm of this array."""
    return norm(self)

powm(n)

Matrix power.

Parameters:

Name Type Description Default
n

Exponent (integer or float).

required

Returns:

Type Description

This array raised to the n-th matrix power.

Source code in jaxquantum/core/qarray.py
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
def powm(self, n):
    """Matrix power.

    Args:
        n: Exponent (integer or float).

    Returns:
        This array raised to the *n*-th matrix power.
    """
    return powm(self, n)

ptrace(indx)

Partial trace over subsystem indx.

Parameters:

Name Type Description Default
indx

Index of the subsystem to trace out.

required

Returns:

Type Description

Reduced density matrix.

Source code in jaxquantum/core/qarray.py
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
def ptrace(self, indx):
    """Partial trace over subsystem *indx*.

    Args:
        indx: Index of the subsystem to trace out.

    Returns:
        Reduced density matrix.
    """
    return ptrace(self, indx)

real()

Element-wise real part.

Returns:

Type Description

A new Qarray containing the real parts of each element.

Source code in jaxquantum/core/qarray.py
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
def real(self):
    """Element-wise real part.

    Returns:
        A new ``Qarray`` containing the real parts of each element.
    """
    new_impl = self._impl.real()
    return Qarray.create(
        new_impl.data,
        dims=self.dims,
        implementation=new_impl.impl_type,
    )

reshape_bdims(*args)

Reshape the batch dimensions of this Qarray.

Parameters:

Name Type Description Default
*args

New batch dimension sizes.

()

Returns:

Type Description

A new Qarray with the requested batch shape.

Source code in jaxquantum/core/qarray.py
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def reshape_bdims(self, *args):
    """Reshape the batch dimensions of this ``Qarray``.

    Args:
        *args: New batch dimension sizes.

    Returns:
        A new ``Qarray`` with the requested batch shape.
    """
    new_bdims = tuple(args)

    if prod(new_bdims) == 0:
        new_shape = new_bdims
    else:
        new_shape = new_bdims + (prod(self.dims[0]),) + (-1,)

    # Preserve implementation type
    implementation = self.impl_type
    return Qarray.create(
        self.data.reshape(new_shape),
        dims=self.dims,
        bdims=new_bdims,
        implementation=implementation,
    )

reshape_qdims(*args)

Reshape the quantum dimensions of the Qarray.

Note that this does not take in qdims but rather the new Hilbert space dimensions.

Parameters:

Name Type Description Default
*args

New Hilbert dimensions for the Qarray.

()

Returns:

Name Type Description
Qarray

reshaped Qarray.

Source code in jaxquantum/core/qarray.py
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
def reshape_qdims(self, *args):
    """Reshape the quantum dimensions of the Qarray.

    Note that this does not take in qdims but rather the new Hilbert space
    dimensions.

    Args:
        *args: New Hilbert dimensions for the Qarray.

    Returns:
        Qarray: reshaped Qarray.
    """

    new_space_dims = tuple(args)
    current_space_dims = self.space_dims
    assert prod(new_space_dims) == prod(current_space_dims)

    new_qdims = self.space_to_qdims(new_space_dims)
    new_bdims = self.bdims

    # Preserve implementation type
    implementation = self.impl_type
    return Qarray.create(self.data, dims=new_qdims, bdims=new_bdims, implementation=implementation)

resize(new_shape)

Resize the Qarray to a new shape.

TODO: review and maybe deprecate this method.

Parameters:

Name Type Description Default
new_shape

Target shape tuple.

required

Returns:

Type Description

A new Qarray with data resized via jnp.resize.

Source code in jaxquantum/core/qarray.py
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
def resize(self, new_shape):
    """Resize the Qarray to a new shape.

    TODO: review and maybe deprecate this method.

    Args:
        new_shape: Target shape tuple.

    Returns:
        A new ``Qarray`` with data resized via ``jnp.resize``.
    """
    dims = self.dims
    data = jnp.resize(self.data, new_shape)
    # Preserve implementation type
    implementation = self.impl_type
    return Qarray.create(
        data,
        dims=dims,
        implementation=implementation,
    )

sinm()

Matrix sine.

Source code in jaxquantum/core/qarray.py
1507
1508
1509
def sinm(self):
    """Matrix sine."""
    return sinm(self)

space_to_qdims(space_dims)

Convert Hilbert space dimensions to full quantum dims tuple.

Parameters:

Name Type Description Default
space_dims List[int]

Sequence of per-subsystem Hilbert space sizes, or a full ((row_dims), (col_dims)) tuple (returned unchanged).

required

Returns:

Type Description

A ((row_dims...), (col_dims...)) tuple.

Raises:

Type Description
ValueError

If self.qtype is not ket, bra, or oper.

Source code in jaxquantum/core/qarray.py
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
def space_to_qdims(self, space_dims: List[int]):
    """Convert Hilbert space dimensions to full quantum dims tuple.

    Args:
        space_dims: Sequence of per-subsystem Hilbert space sizes, or a
            full ``((row_dims), (col_dims))`` tuple (returned unchanged).

    Returns:
        A ``((row_dims...), (col_dims...))`` tuple.

    Raises:
        ValueError: If ``self.qtype`` is not ket, bra, or oper.
    """
    if isinstance(space_dims[0], (list, tuple)):
        return space_dims

    if self.qtype in [Qtypes.oper, Qtypes.ket]:
        return (tuple(space_dims), tuple([1 for _ in range(len(space_dims))]))
    elif self.qtype == Qtypes.bra:
        return (tuple([1 for _ in range(len(space_dims))]), tuple(space_dims))
    else:
        raise ValueError("Unsupported qtype for space_to_qdims conversion.")

to_dense()

Return a dense-backed copy of this array.

If the array is already dense, returns self unchanged.

Returns:

Type Description
'Qarray[DenseImpl]'

A Qarray[DenseImpl].

Source code in jaxquantum/core/qarray.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
def to_dense(self) -> "Qarray[DenseImpl]":
    """Return a dense-backed copy of this array.

    If the array is already dense, returns self unchanged.

    Returns:
        A ``Qarray[DenseImpl]``.
    """
    if self.is_dense:
        return self
    new_impl = self._impl.to_dense()
    return Qarray(new_impl, self._qdims, self._bdims)

to_dm()

Convert a ket to a density matrix via outer product.

Source code in jaxquantum/core/qarray.py
1407
1408
1409
def to_dm(self):
    """Convert a ket to a density matrix via outer product."""
    return ket2dm(self)

to_ket()

Convert a bra to a ket (no-op for kets).

Source code in jaxquantum/core/qarray.py
1419
1420
1421
def to_ket(self):
    """Convert a bra to a ket (no-op for kets)."""
    return to_ket(self)

to_sparse_bcoo()

Return a BCOO-sparse-backed copy of this array.

If the array is already sparse BCOO, returns self unchanged.

Returns:

Type Description
'Qarray[SparseBCOOImpl]'

A Qarray[SparseBCOOImpl].

Source code in jaxquantum/core/qarray.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
def to_sparse_bcoo(self) -> "Qarray[SparseBCOOImpl]":
    """Return a BCOO-sparse-backed copy of this array.

    If the array is already sparse BCOO, returns self unchanged.

    Returns:
        A ``Qarray[SparseBCOOImpl]``.
    """
    if self.is_sparse_bcoo:
        return self
    new_impl = self._impl.to_sparse_bcoo()
    return Qarray(new_impl, self._qdims, self._bdims)

to_sparse_dia()

Return a SparseDIA-backed copy of this array.

If the array is already SparseDIA, returns self unchanged.

Returns:

Type Description
'Qarray'

A Qarray[SparseDiaImpl].

Source code in jaxquantum/core/qarray.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def to_sparse_dia(self) -> "Qarray":
    """Return a SparseDIA-backed copy of this array.

    If the array is already SparseDIA, returns self unchanged.

    Returns:
        A ``Qarray[SparseDiaImpl]``.
    """
    if self.is_sparse_dia:
        return self
    new_impl = self._impl.to_sparse_dia()
    return Qarray(new_impl, self._qdims, self._bdims)

tr(**kwargs)

Full trace.

Source code in jaxquantum/core/qarray.py
1511
1512
1513
def tr(self, **kwargs):
    """Full trace."""
    return tr(self, **kwargs)

trace(**kwargs)

Full trace (alias for :meth:tr).

Source code in jaxquantum/core/qarray.py
1515
1516
1517
def trace(self, **kwargs):
    """Full trace (alias for :meth:`tr`)."""
    return tr(self, **kwargs)

transpose(*args)

Transpose subsystem indices.

Source code in jaxquantum/core/qarray.py
1423
1424
1425
def transpose(self, *args):
    """Transpose subsystem indices."""
    return transpose(self, *args)

unit()

Return the normalised (unit-norm) version of this array.

Source code in jaxquantum/core/qarray.py
1432
1433
1434
def unit(self):
    """Return the normalised (unit-norm) version of this array."""
    return unit(self)

QarrayImpl

Bases: ABC

Abstract base class defining the interface every storage backend must implement.

A QarrayImpl wraps a raw data array (dense jnp.ndarray or sparse BCOO) and provides the mathematical primitives used by Qarray. Concrete subclasses must implement every @abstractmethod.

Attributes:

Name Type Description
PROMOTION_ORDER int

Integer priority used by _coerce to decide which side to promote when operands have different types. Higher means "more general" (DenseImpl = 1, SparseBCOOImpl = 0).

Source code in jaxquantum/core/qarray.py
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
class QarrayImpl(ABC):
    """Abstract base class defining the interface every storage backend must implement.

    A ``QarrayImpl`` wraps a raw data array (dense ``jnp.ndarray`` or sparse
    ``BCOO``) and provides the mathematical primitives used by ``Qarray``.
    Concrete subclasses must implement every ``@abstractmethod``.

    Attributes:
        PROMOTION_ORDER: Integer priority used by ``_coerce`` to decide which
            side to promote when operands have different types.  Higher means
            "more general" (``DenseImpl = 1``, ``SparseBCOOImpl = 0``).
    """

    PROMOTION_ORDER: int = 0  # override in subclasses; higher = more general
    # Current hierarchy: SparseDiaImpl=0, SparseBCOOImpl=1, DenseImpl=2

    @abstractmethod
    def get_data(self) -> Array:
        """Return the underlying raw data array."""
        pass

    @property
    def data(self) -> Array:
        """The underlying raw data array."""
        return self.get_data()

    @property
    def impl_type(self) -> QarrayImplType:
        """The ``QarrayImplType`` member corresponding to this instance."""
        return QarrayImplType.from_impl_class(type(self))

    @classmethod
    @abstractmethod
    def from_data(cls, data) -> "QarrayImpl":
        """Wrap raw data in this impl type.

        Args:
            data: Raw array data (dense ``jnp.ndarray`` or ``sparse.BCOO``).

        Returns:
            A new instance of this implementation wrapping *data*.
        """
        pass

    @abstractmethod
    def matmul(self, other: "QarrayImpl") -> "QarrayImpl":
        """Matrix multiplication with *other*.

        Args:
            other: Right-hand operand.

        Returns:
            Result of ``self @ other`` as a ``QarrayImpl``.
        """
        pass

    @abstractmethod
    def add(self, other: "QarrayImpl") -> "QarrayImpl":
        """Element-wise addition with *other*.

        Args:
            other: Right-hand operand.

        Returns:
            Result of ``self + other`` as a ``QarrayImpl``.
        """
        pass

    @abstractmethod
    def sub(self, other: "QarrayImpl") -> "QarrayImpl":
        """Element-wise subtraction of *other*.

        Args:
            other: Right-hand operand.

        Returns:
            Result of ``self - other`` as a ``QarrayImpl``.
        """
        pass

    @abstractmethod
    def mul(self, scalar) -> "QarrayImpl":
        """Scalar multiplication.

        Args:
            scalar: Scalar value to multiply by.

        Returns:
            Result of ``scalar * self`` as a ``QarrayImpl``.
        """
        pass

    @abstractmethod
    def dag(self) -> "QarrayImpl":
        """Conjugate transpose.

        Returns:
            The conjugate transpose of this array as a ``QarrayImpl``.
        """
        pass

    @abstractmethod
    def to_dense(self) -> "DenseImpl":
        """Convert to a ``DenseImpl``.

        Returns:
            A ``DenseImpl`` wrapping the same data.
        """
        pass

    @abstractmethod
    def to_sparse_bcoo(self) -> "SparseBCOOImpl":
        """Convert to a ``SparseBCOOImpl`` (BCOO).

        Returns:
            A ``SparseBCOOImpl`` wrapping the same data.
        """
        pass

    def to_sparse_dia(self) -> "QarrayImpl":
        """Convert to a ``SparseDiaImpl``.

        Default implementation goes through dense and auto-detects diagonals.
        Subclasses may override for a more direct path.

        Returns:
            A ``SparseDiaImpl`` wrapping the same data.
        """
        # Import here to avoid circular imports at module load time
        from jaxquantum.core.sparse_dia import SparseDiaImpl
        return SparseDiaImpl.from_data(self.to_dense()._data)

    @abstractmethod
    def shape(self) -> tuple:
        """Shape of the underlying data array.

        Returns:
            Tuple of dimension sizes.
        """
        pass

    @abstractmethod
    def dtype(self):
        """Data type of the underlying array.

        Returns:
            A numpy/JAX dtype object.
        """
        pass

    @abstractmethod
    def __deepcopy__(self, memo=None):
        pass

    @abstractmethod
    def tidy_up(self, atol):
        """Zero out values whose magnitude is below *atol*.

        Args:
            atol: Absolute tolerance threshold.

        Returns:
            A new ``QarrayImpl`` with small values zeroed.
        """
        pass

    @abstractmethod
    def kron(self, other: "QarrayImpl") -> "QarrayImpl":
        """Kronecker (tensor) product with another implementation.

        Args:
            other: Right-hand operand.  Mixed-type pairs are handled by
                ``_coerce`` — the result has the higher ``PROMOTION_ORDER``
                type (dense wins over sparse).

        Returns:
            A new ``QarrayImpl`` containing the Kronecker product.
        """
        pass

    @classmethod
    @abstractmethod
    def _eye_data(cls, n: int, dtype=None):
        """Create identity matrix data of size n.

        Args:
            n: Matrix size.
            dtype: Optional data type for the identity entries.

        Returns:
            Raw identity matrix data in the format appropriate for this impl.
        """
        pass

    @classmethod
    @abstractmethod
    def can_handle_data(cls, arr) -> bool:
        """Return True if *arr* is a raw data type natively handled by this impl.

        Used by the module-level :func:`dag_data` dispatcher to route raw
        arrays to the correct backend without any isinstance chain outside the
        impl classes.

        Args:
            arr: Raw array — e.g. ``jnp.ndarray`` for ``DenseImpl`` or
                ``sparse.BCOO`` for ``SparseBCOOImpl``.

        Returns:
            True if this impl can operate on *arr* without conversion.
        """
        pass

    @classmethod
    @abstractmethod
    def dag_data(cls, arr):
        """Conjugate transpose of raw data in this impl's native format.

        Implementations must handle batched arrays (last two axes are
        swapped) and must not densify sparse arrays.

        Args:
            arr: Raw array in this impl's native format.

        Returns:
            Conjugate transpose with the last two axes swapped.
        """
        pass

    def _promote_to(self, target_cls: type) -> "QarrayImpl":
        """Convert this impl to *target_cls* by passing through dense.

        Args:
            target_cls: The destination ``QarrayImpl`` subclass.

        Returns:
            An instance of *target_cls* holding equivalent data.
        """
        if isinstance(self, target_cls):
            return self
        return target_cls.from_data(self.to_dense()._data)

    def _coerce(self, other: "QarrayImpl") -> "tuple[QarrayImpl, QarrayImpl]":
        """Coerce *self* and *other* to the same implementation type.

        The impl type with the higher ``PROMOTION_ORDER`` wins; the other side
        is promoted via :meth:`_promote_to`.

        Args:
            other: The other operand.

        Returns:
            A pair ``(a, b)`` of the same ``QarrayImpl`` subclass, suitable
            for a binary operation.
        """
        if type(self) is type(other):
            return self, other
        if self.PROMOTION_ORDER >= other.PROMOTION_ORDER:
            return self, other._promote_to(type(self))
        return self._promote_to(type(other)), other

data property

The underlying raw data array.

impl_type property

The QarrayImplType member corresponding to this instance.

add(other) abstractmethod

Element-wise addition with other.

Parameters:

Name Type Description Default
other 'QarrayImpl'

Right-hand operand.

required

Returns:

Type Description
'QarrayImpl'

Result of self + other as a QarrayImpl.

Source code in jaxquantum/core/qarray.py
194
195
196
197
198
199
200
201
202
203
204
@abstractmethod
def add(self, other: "QarrayImpl") -> "QarrayImpl":
    """Element-wise addition with *other*.

    Args:
        other: Right-hand operand.

    Returns:
        Result of ``self + other`` as a ``QarrayImpl``.
    """
    pass

can_handle_data(arr) abstractmethod classmethod

Return True if arr is a raw data type natively handled by this impl.

Used by the module-level :func:dag_data dispatcher to route raw arrays to the correct backend without any isinstance chain outside the impl classes.

Parameters:

Name Type Description Default
arr

Raw array — e.g. jnp.ndarray for DenseImpl or sparse.BCOO for SparseBCOOImpl.

required

Returns:

Type Description
bool

True if this impl can operate on arr without conversion.

Source code in jaxquantum/core/qarray.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
@classmethod
@abstractmethod
def can_handle_data(cls, arr) -> bool:
    """Return True if *arr* is a raw data type natively handled by this impl.

    Used by the module-level :func:`dag_data` dispatcher to route raw
    arrays to the correct backend without any isinstance chain outside the
    impl classes.

    Args:
        arr: Raw array — e.g. ``jnp.ndarray`` for ``DenseImpl`` or
            ``sparse.BCOO`` for ``SparseBCOOImpl``.

    Returns:
        True if this impl can operate on *arr* without conversion.
    """
    pass

dag() abstractmethod

Conjugate transpose.

Returns:

Type Description
'QarrayImpl'

The conjugate transpose of this array as a QarrayImpl.

Source code in jaxquantum/core/qarray.py
230
231
232
233
234
235
236
237
@abstractmethod
def dag(self) -> "QarrayImpl":
    """Conjugate transpose.

    Returns:
        The conjugate transpose of this array as a ``QarrayImpl``.
    """
    pass

dag_data(arr) abstractmethod classmethod

Conjugate transpose of raw data in this impl's native format.

Implementations must handle batched arrays (last two axes are swapped) and must not densify sparse arrays.

Parameters:

Name Type Description Default
arr

Raw array in this impl's native format.

required

Returns:

Type Description

Conjugate transpose with the last two axes swapped.

Source code in jaxquantum/core/qarray.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
@classmethod
@abstractmethod
def dag_data(cls, arr):
    """Conjugate transpose of raw data in this impl's native format.

    Implementations must handle batched arrays (last two axes are
    swapped) and must not densify sparse arrays.

    Args:
        arr: Raw array in this impl's native format.

    Returns:
        Conjugate transpose with the last two axes swapped.
    """
    pass

dtype() abstractmethod

Data type of the underlying array.

Returns:

Type Description

A numpy/JAX dtype object.

Source code in jaxquantum/core/qarray.py
279
280
281
282
283
284
285
286
@abstractmethod
def dtype(self):
    """Data type of the underlying array.

    Returns:
        A numpy/JAX dtype object.
    """
    pass

from_data(data) abstractmethod classmethod

Wrap raw data in this impl type.

Parameters:

Name Type Description Default
data

Raw array data (dense jnp.ndarray or sparse.BCOO).

required

Returns:

Type Description
'QarrayImpl'

A new instance of this implementation wrapping data.

Source code in jaxquantum/core/qarray.py
169
170
171
172
173
174
175
176
177
178
179
180
@classmethod
@abstractmethod
def from_data(cls, data) -> "QarrayImpl":
    """Wrap raw data in this impl type.

    Args:
        data: Raw array data (dense ``jnp.ndarray`` or ``sparse.BCOO``).

    Returns:
        A new instance of this implementation wrapping *data*.
    """
    pass

get_data() abstractmethod

Return the underlying raw data array.

Source code in jaxquantum/core/qarray.py
154
155
156
157
@abstractmethod
def get_data(self) -> Array:
    """Return the underlying raw data array."""
    pass

kron(other) abstractmethod

Kronecker (tensor) product with another implementation.

Parameters:

Name Type Description Default
other 'QarrayImpl'

Right-hand operand. Mixed-type pairs are handled by _coerce — the result has the higher PROMOTION_ORDER type (dense wins over sparse).

required

Returns:

Type Description
'QarrayImpl'

A new QarrayImpl containing the Kronecker product.

Source code in jaxquantum/core/qarray.py
304
305
306
307
308
309
310
311
312
313
314
315
316
@abstractmethod
def kron(self, other: "QarrayImpl") -> "QarrayImpl":
    """Kronecker (tensor) product with another implementation.

    Args:
        other: Right-hand operand.  Mixed-type pairs are handled by
            ``_coerce`` — the result has the higher ``PROMOTION_ORDER``
            type (dense wins over sparse).

    Returns:
        A new ``QarrayImpl`` containing the Kronecker product.
    """
    pass

matmul(other) abstractmethod

Matrix multiplication with other.

Parameters:

Name Type Description Default
other 'QarrayImpl'

Right-hand operand.

required

Returns:

Type Description
'QarrayImpl'

Result of self @ other as a QarrayImpl.

Source code in jaxquantum/core/qarray.py
182
183
184
185
186
187
188
189
190
191
192
@abstractmethod
def matmul(self, other: "QarrayImpl") -> "QarrayImpl":
    """Matrix multiplication with *other*.

    Args:
        other: Right-hand operand.

    Returns:
        Result of ``self @ other`` as a ``QarrayImpl``.
    """
    pass

mul(scalar) abstractmethod

Scalar multiplication.

Parameters:

Name Type Description Default
scalar

Scalar value to multiply by.

required

Returns:

Type Description
'QarrayImpl'

Result of scalar * self as a QarrayImpl.

Source code in jaxquantum/core/qarray.py
218
219
220
221
222
223
224
225
226
227
228
@abstractmethod
def mul(self, scalar) -> "QarrayImpl":
    """Scalar multiplication.

    Args:
        scalar: Scalar value to multiply by.

    Returns:
        Result of ``scalar * self`` as a ``QarrayImpl``.
    """
    pass

shape() abstractmethod

Shape of the underlying data array.

Returns:

Type Description
tuple

Tuple of dimension sizes.

Source code in jaxquantum/core/qarray.py
270
271
272
273
274
275
276
277
@abstractmethod
def shape(self) -> tuple:
    """Shape of the underlying data array.

    Returns:
        Tuple of dimension sizes.
    """
    pass

sub(other) abstractmethod

Element-wise subtraction of other.

Parameters:

Name Type Description Default
other 'QarrayImpl'

Right-hand operand.

required

Returns:

Type Description
'QarrayImpl'

Result of self - other as a QarrayImpl.

Source code in jaxquantum/core/qarray.py
206
207
208
209
210
211
212
213
214
215
216
@abstractmethod
def sub(self, other: "QarrayImpl") -> "QarrayImpl":
    """Element-wise subtraction of *other*.

    Args:
        other: Right-hand operand.

    Returns:
        Result of ``self - other`` as a ``QarrayImpl``.
    """
    pass

tidy_up(atol) abstractmethod

Zero out values whose magnitude is below atol.

Parameters:

Name Type Description Default
atol

Absolute tolerance threshold.

required

Returns:

Type Description

A new QarrayImpl with small values zeroed.

Source code in jaxquantum/core/qarray.py
292
293
294
295
296
297
298
299
300
301
302
@abstractmethod
def tidy_up(self, atol):
    """Zero out values whose magnitude is below *atol*.

    Args:
        atol: Absolute tolerance threshold.

    Returns:
        A new ``QarrayImpl`` with small values zeroed.
    """
    pass

to_dense() abstractmethod

Convert to a DenseImpl.

Returns:

Type Description
'DenseImpl'

A DenseImpl wrapping the same data.

Source code in jaxquantum/core/qarray.py
239
240
241
242
243
244
245
246
@abstractmethod
def to_dense(self) -> "DenseImpl":
    """Convert to a ``DenseImpl``.

    Returns:
        A ``DenseImpl`` wrapping the same data.
    """
    pass

to_sparse_bcoo() abstractmethod

Convert to a SparseBCOOImpl (BCOO).

Returns:

Type Description
'SparseBCOOImpl'

A SparseBCOOImpl wrapping the same data.

Source code in jaxquantum/core/qarray.py
248
249
250
251
252
253
254
255
@abstractmethod
def to_sparse_bcoo(self) -> "SparseBCOOImpl":
    """Convert to a ``SparseBCOOImpl`` (BCOO).

    Returns:
        A ``SparseBCOOImpl`` wrapping the same data.
    """
    pass

to_sparse_dia()

Convert to a SparseDiaImpl.

Default implementation goes through dense and auto-detects diagonals. Subclasses may override for a more direct path.

Returns:

Type Description
'QarrayImpl'

A SparseDiaImpl wrapping the same data.

Source code in jaxquantum/core/qarray.py
257
258
259
260
261
262
263
264
265
266
267
268
def to_sparse_dia(self) -> "QarrayImpl":
    """Convert to a ``SparseDiaImpl``.

    Default implementation goes through dense and auto-detects diagonals.
    Subclasses may override for a more direct path.

    Returns:
        A ``SparseDiaImpl`` wrapping the same data.
    """
    # Import here to avoid circular imports at module load time
    from jaxquantum.core.sparse_dia import SparseDiaImpl
    return SparseDiaImpl.from_data(self.to_dense()._data)

QarrayImplType

Bases: Enum

Enumeration of available Qarray storage backends.

Each member maps one-to-one with a concrete QarrayImpl subclass. New backends should call QarrayImplType.register(MyImpl, QarrayImplType.MY_TYPE) immediately after defining their impl class.

Members

DENSE: Standard JAX dense array (jnp.ndarray). SPARSE_BCOO: JAX experimental BCOO sparse array. SPARSE_DIA: Diagonal sparse array.

Source code in jaxquantum/core/qarray.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class QarrayImplType(Enum):
    """Enumeration of available Qarray storage backends.

    Each member maps one-to-one with a concrete ``QarrayImpl`` subclass.
    New backends should call ``QarrayImplType.register(MyImpl, QarrayImplType.MY_TYPE)``
    immediately after defining their impl class.

    Members:
        DENSE: Standard JAX dense array (``jnp.ndarray``).
        SPARSE_BCOO: JAX experimental BCOO sparse array.
        SPARSE_DIA: Diagonal sparse array.
    """

    DENSE = "dense"
    SPARSE_BCOO = "sparse_bcoo"
    SPARSE_DIA = "sparse_dia"

    @classmethod
    def register(cls, impl_class, member):
        """Register an implementation class with a QarrayImplType member.

        Args:
            impl_class: The concrete ``QarrayImpl`` subclass to register.
            member: The ``QarrayImplType`` enum member to associate with it.
        """
        _IMPL_REGISTRY[impl_class] = member

    @classmethod
    def has(cls, x) -> bool:
        """Return True if x corresponds to a member of QarrayImplType.

        Accepts an existing ``QarrayImplType`` member, a string equal to the
        member name or value (case-insensitive), or an implementation class
        (e.g. ``DenseImpl``, ``SparseBCOOImpl``) that has been registered.

        Args:
            x: Value to test — a ``QarrayImplType``, ``str``, or impl class.

        Returns:
            True if ``x`` maps to a known ``QarrayImplType`` member.
        """
        if isinstance(x, cls):
            return True

        if isinstance(x, str):
            xl = x.lower()
            return any(xl == member.value or xl == member.name.lower() for member in cls)

        # Try mapping from an implementation class to an enum member
        try:
            cls.from_impl_class(x)
            return True
        except Exception:
            return False

    @classmethod
    def from_impl_class(cls, impl_class) -> "QarrayImplType":
        """Return the ``QarrayImplType`` member associated with *impl_class*.

        Args:
            impl_class: A concrete ``QarrayImpl`` subclass that has been
                registered via :meth:`register`.

        Returns:
            The corresponding ``QarrayImplType`` member.

        Raises:
            ValueError: If *impl_class* is not in the registry.
        """
        if impl_class in _IMPL_REGISTRY:
            return _IMPL_REGISTRY[impl_class]
        raise ValueError(f"Unknown implementation class: {impl_class}")

    def get_impl_class(self):
        """Return the implementation class registered for this member.

        Returns:
            The concrete ``QarrayImpl`` subclass associated with this member.

        Raises:
            ValueError: If no class has been registered for this member.
        """
        for cls_key, member in _IMPL_REGISTRY.items():
            if member is self:
                return cls_key
        raise ValueError(f"No impl class registered for {self}")

from_impl_class(impl_class) classmethod

Return the QarrayImplType member associated with impl_class.

Parameters:

Name Type Description Default
impl_class

A concrete QarrayImpl subclass that has been registered via :meth:register.

required

Returns:

Type Description
'QarrayImplType'

The corresponding QarrayImplType member.

Raises:

Type Description
ValueError

If impl_class is not in the registry.

Source code in jaxquantum/core/qarray.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@classmethod
def from_impl_class(cls, impl_class) -> "QarrayImplType":
    """Return the ``QarrayImplType`` member associated with *impl_class*.

    Args:
        impl_class: A concrete ``QarrayImpl`` subclass that has been
            registered via :meth:`register`.

    Returns:
        The corresponding ``QarrayImplType`` member.

    Raises:
        ValueError: If *impl_class* is not in the registry.
    """
    if impl_class in _IMPL_REGISTRY:
        return _IMPL_REGISTRY[impl_class]
    raise ValueError(f"Unknown implementation class: {impl_class}")

get_impl_class()

Return the implementation class registered for this member.

Returns:

Type Description

The concrete QarrayImpl subclass associated with this member.

Raises:

Type Description
ValueError

If no class has been registered for this member.

Source code in jaxquantum/core/qarray.py
106
107
108
109
110
111
112
113
114
115
116
117
118
def get_impl_class(self):
    """Return the implementation class registered for this member.

    Returns:
        The concrete ``QarrayImpl`` subclass associated with this member.

    Raises:
        ValueError: If no class has been registered for this member.
    """
    for cls_key, member in _IMPL_REGISTRY.items():
        if member is self:
            return cls_key
    raise ValueError(f"No impl class registered for {self}")

has(x) classmethod

Return True if x corresponds to a member of QarrayImplType.

Accepts an existing QarrayImplType member, a string equal to the member name or value (case-insensitive), or an implementation class (e.g. DenseImpl, SparseBCOOImpl) that has been registered.

Parameters:

Name Type Description Default
x

Value to test — a QarrayImplType, str, or impl class.

required

Returns:

Type Description
bool

True if x maps to a known QarrayImplType member.

Source code in jaxquantum/core/qarray.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@classmethod
def has(cls, x) -> bool:
    """Return True if x corresponds to a member of QarrayImplType.

    Accepts an existing ``QarrayImplType`` member, a string equal to the
    member name or value (case-insensitive), or an implementation class
    (e.g. ``DenseImpl``, ``SparseBCOOImpl``) that has been registered.

    Args:
        x: Value to test — a ``QarrayImplType``, ``str``, or impl class.

    Returns:
        True if ``x`` maps to a known ``QarrayImplType`` member.
    """
    if isinstance(x, cls):
        return True

    if isinstance(x, str):
        xl = x.lower()
        return any(xl == member.value or xl == member.name.lower() for member in cls)

    # Try mapping from an implementation class to an enum member
    try:
        cls.from_impl_class(x)
        return True
    except Exception:
        return False

register(impl_class, member) classmethod

Register an implementation class with a QarrayImplType member.

Parameters:

Name Type Description Default
impl_class

The concrete QarrayImpl subclass to register.

required
member

The QarrayImplType enum member to associate with it.

required
Source code in jaxquantum/core/qarray.py
50
51
52
53
54
55
56
57
58
@classmethod
def register(cls, impl_class, member):
    """Register an implementation class with a QarrayImplType member.

    Args:
        impl_class: The concrete ``QarrayImpl`` subclass to register.
        member: The ``QarrayImplType`` enum member to associate with it.
    """
    _IMPL_REGISTRY[impl_class] = member

QuantumStateTomography

Source code in jaxquantum/core/measurements.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
class QuantumStateTomography:
    def __init__(
        self,
        rho_guess: Qarray,
        measurement_basis: Qarray,
        measurement_results: jnp.ndarray,
        complete_basis: Optional[Qarray] = None,
        true_rho: Optional[Qarray] = None,
    ):
        """
        Reconstruct a quantum state from measurement results using quantum state tomography.
        The tomography can be performed either by direct inversion or by maximum likelihood estimation.

        Args:
            rho_guess (Qarray): The initial guess for the quantum state.
            measurement_basis (Qarray): The basis in which measurements are performed.
            measurement_results (jnp.ndarray): The results of the measurements.
            complete_basis (Optional[Qarray]): The complete basis for state 
            reconstruction used when using direct inversion. 
            Defaults to the measurement basis if not provided.
            true_rho (Optional[Qarray]): The true quantum state, if known.

        """
        self.rho_guess = rho_guess.data
        self.measurement_basis = measurement_basis.data
        self.measurement_results = measurement_results
        self.complete_basis = (
            complete_basis.data
            if (complete_basis is not None)
            else measurement_basis.data
        )
        self.true_rho = true_rho
        self._result = None

    @property
    def result(self) -> Optional[MLETomographyResult]:
        return self._result


    def quantum_state_tomography_mle(
        self, L1_reg_strength: float = 0.0, epochs: int = 10000, lr: float = 5e-3
    ) -> MLETomographyResult:
        """Perform quantum state tomography using maximum likelihood 
        estimation (MLE).

        This method reconstructs the quantum state from measurement results 
        by optimizing
        a likelihood function using gradient descent. The optimization 
        ensures the 
        resulting density matrix is positive semi-definite with trace 1.

        Args:
            L1_reg_strength (float, optional): Strength of L1 
            regularization. Defaults to 0.0.
            epochs (int, optional): Number of optimization iterations. 
            Defaults to 10000.
            lr (float, optional): Learning rate for the Adam optimizer. 
            Defaults to 5e-3.

        Returns:
            MLETomographyResult: Named tuple containing:
                - rho: Reconstructed quantum state as Qarray
                - params_history: List of parameter values during optimization
                - loss_history: List of loss values during optimization
                - grads_history: List of gradient values during optimization
                - infidelity_history: List of infidelities if true_rho was 
                provided, None otherwise
        """

        dim = self.rho_guess.shape[0]
        optimizer = optax.adam(lr)

        # Initialize parameters from the initial guess for the density matrix
        params = _parametrize_density_matrix(self.rho_guess, dim)
        opt_state = optimizer.init(params)

        compute_infidelity_flag = self.true_rho is not None

        # Provide a dummy array if no true_rho is available. It won't be used.
        true_rho_data_or_dummy = (
            self.true_rho.data
            if compute_infidelity_flag
            else jnp.empty((dim, dim), dtype=jnp.complex64)
        )

        final_carry, history = _run_tomography_scan(
            initial_params=params,
            initial_opt_state=opt_state,
            true_rho_data=true_rho_data_or_dummy,
            measurement_basis=self.measurement_basis,
            measurement_results=self.measurement_results,
            dim=dim,
            epochs=epochs,
            optimizer=optimizer,
            compute_infidelity=compute_infidelity_flag,
            L1_reg_strength=L1_reg_strength,
        )

        final_params, _ = final_carry

        rho = Qarray.create(_reconstruct_density_matrix(final_params, dim))

        self._result = MLETomographyResult(
            rho=rho,
            params_history=history["params"],
            loss_history=history["loss"],
            grads_history=history["grads"],
            infidelity_history=history["infidelity"]
            if compute_infidelity_flag
            else None,
        )
        return self._result

    def quantum_state_tomography_direct(
        self,
    ) -> Qarray:

        """Perform quantum state tomography using direct inversion.

        This method reconstructs the quantum state from measurement results by 
        directly solving a system of linear equations. The method assumes that
        the measurement basis is complete and the measurement results are 
        noise-free.

        Returns:
            Qarray: Reconstructed quantum state.
        """

    # Compute overlaps of measurement and complete operator bases
        A = jnp.einsum("ijk,ljk->il", self.complete_basis, self.measurement_basis)
        # Solve the linear system to find the coefficients
        coefficients = jnp.linalg.solve(A, self.measurement_results)
        # Reconstruct the density matrix
        rho = jnp.einsum("i, ijk->jk", coefficients, self.complete_basis)

        return Qarray.create(rho)

    def plot_results(self):
        if self._result is None:
            raise ValueError(
                "No results to plot. Run quantum_state_tomography_mle first."
            )

        fig, ax = plt.subplots(1, figsize=(5, 4))
        if self._result.infidelity_history is not None:
            ax2 = ax.twinx()

        ax.plot(self._result.loss_history, color="C0")
        ax.set_xlabel("Epoch")
        ax.set_ylabel("$\\mathcal{L}$", color="C0")
        ax.set_yscale("log")

        if self._result.infidelity_history is not None:
            ax2.plot(self._result.infidelity_history, color="C1")
            ax2.set_yscale("log")
            ax2.set_ylabel("$1-\\mathcal{F}$", color="C1")
            plt.grid(False)

        plt.show()

__init__(rho_guess, measurement_basis, measurement_results, complete_basis=None, true_rho=None)

Reconstruct a quantum state from measurement results using quantum state tomography. The tomography can be performed either by direct inversion or by maximum likelihood estimation.

Parameters:

Name Type Description Default
rho_guess Qarray

The initial guess for the quantum state.

required
measurement_basis Qarray

The basis in which measurements are performed.

required
measurement_results ndarray

The results of the measurements.

required
complete_basis Optional[Qarray]

The complete basis for state

None
true_rho Optional[Qarray]

The true quantum state, if known.

None
Source code in jaxquantum/core/measurements.py
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
def __init__(
    self,
    rho_guess: Qarray,
    measurement_basis: Qarray,
    measurement_results: jnp.ndarray,
    complete_basis: Optional[Qarray] = None,
    true_rho: Optional[Qarray] = None,
):
    """
    Reconstruct a quantum state from measurement results using quantum state tomography.
    The tomography can be performed either by direct inversion or by maximum likelihood estimation.

    Args:
        rho_guess (Qarray): The initial guess for the quantum state.
        measurement_basis (Qarray): The basis in which measurements are performed.
        measurement_results (jnp.ndarray): The results of the measurements.
        complete_basis (Optional[Qarray]): The complete basis for state 
        reconstruction used when using direct inversion. 
        Defaults to the measurement basis if not provided.
        true_rho (Optional[Qarray]): The true quantum state, if known.

    """
    self.rho_guess = rho_guess.data
    self.measurement_basis = measurement_basis.data
    self.measurement_results = measurement_results
    self.complete_basis = (
        complete_basis.data
        if (complete_basis is not None)
        else measurement_basis.data
    )
    self.true_rho = true_rho
    self._result = None

quantum_state_tomography_direct()

Perform quantum state tomography using direct inversion.

This method reconstructs the quantum state from measurement results by directly solving a system of linear equations. The method assumes that the measurement basis is complete and the measurement results are noise-free.

Returns:

Name Type Description
Qarray Qarray

Reconstructed quantum state.

Source code in jaxquantum/core/measurements.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def quantum_state_tomography_direct(
    self,
) -> Qarray:

    """Perform quantum state tomography using direct inversion.

    This method reconstructs the quantum state from measurement results by 
    directly solving a system of linear equations. The method assumes that
    the measurement basis is complete and the measurement results are 
    noise-free.

    Returns:
        Qarray: Reconstructed quantum state.
    """

# Compute overlaps of measurement and complete operator bases
    A = jnp.einsum("ijk,ljk->il", self.complete_basis, self.measurement_basis)
    # Solve the linear system to find the coefficients
    coefficients = jnp.linalg.solve(A, self.measurement_results)
    # Reconstruct the density matrix
    rho = jnp.einsum("i, ijk->jk", coefficients, self.complete_basis)

    return Qarray.create(rho)

quantum_state_tomography_mle(L1_reg_strength=0.0, epochs=10000, lr=0.005)

Perform quantum state tomography using maximum likelihood estimation (MLE).

This method reconstructs the quantum state from measurement results by optimizing a likelihood function using gradient descent. The optimization ensures the resulting density matrix is positive semi-definite with trace 1.

Parameters:

Name Type Description Default
L1_reg_strength float

Strength of L1

0.0
epochs int

Number of optimization iterations.

10000
lr float

Learning rate for the Adam optimizer.

0.005

Returns:

Name Type Description
MLETomographyResult MLETomographyResult

Named tuple containing: - rho: Reconstructed quantum state as Qarray - params_history: List of parameter values during optimization - loss_history: List of loss values during optimization - grads_history: List of gradient values during optimization - infidelity_history: List of infidelities if true_rho was provided, None otherwise

Source code in jaxquantum/core/measurements.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def quantum_state_tomography_mle(
    self, L1_reg_strength: float = 0.0, epochs: int = 10000, lr: float = 5e-3
) -> MLETomographyResult:
    """Perform quantum state tomography using maximum likelihood 
    estimation (MLE).

    This method reconstructs the quantum state from measurement results 
    by optimizing
    a likelihood function using gradient descent. The optimization 
    ensures the 
    resulting density matrix is positive semi-definite with trace 1.

    Args:
        L1_reg_strength (float, optional): Strength of L1 
        regularization. Defaults to 0.0.
        epochs (int, optional): Number of optimization iterations. 
        Defaults to 10000.
        lr (float, optional): Learning rate for the Adam optimizer. 
        Defaults to 5e-3.

    Returns:
        MLETomographyResult: Named tuple containing:
            - rho: Reconstructed quantum state as Qarray
            - params_history: List of parameter values during optimization
            - loss_history: List of loss values during optimization
            - grads_history: List of gradient values during optimization
            - infidelity_history: List of infidelities if true_rho was 
            provided, None otherwise
    """

    dim = self.rho_guess.shape[0]
    optimizer = optax.adam(lr)

    # Initialize parameters from the initial guess for the density matrix
    params = _parametrize_density_matrix(self.rho_guess, dim)
    opt_state = optimizer.init(params)

    compute_infidelity_flag = self.true_rho is not None

    # Provide a dummy array if no true_rho is available. It won't be used.
    true_rho_data_or_dummy = (
        self.true_rho.data
        if compute_infidelity_flag
        else jnp.empty((dim, dim), dtype=jnp.complex64)
    )

    final_carry, history = _run_tomography_scan(
        initial_params=params,
        initial_opt_state=opt_state,
        true_rho_data=true_rho_data_or_dummy,
        measurement_basis=self.measurement_basis,
        measurement_results=self.measurement_results,
        dim=dim,
        epochs=epochs,
        optimizer=optimizer,
        compute_infidelity=compute_infidelity_flag,
        L1_reg_strength=L1_reg_strength,
    )

    final_params, _ = final_carry

    rho = Qarray.create(_reconstruct_density_matrix(final_params, dim))

    self._result = MLETomographyResult(
        rho=rho,
        params_history=history["params"],
        loss_history=history["loss"],
        grads_history=history["grads"],
        infidelity_history=history["infidelity"]
        if compute_infidelity_flag
        else None,
    )
    return self._result

SparseBCOOImpl

Bases: QarrayImpl

Sparse implementation using JAX experimental BCOO sparse arrays.

Attributes:

Name Type Description
_data BCOO

The underlying sparse.BCOO array.

Source code in jaxquantum/core/sparse_bcoo.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
@struct.dataclass
class SparseBCOOImpl(QarrayImpl):
    """Sparse implementation using JAX experimental BCOO sparse arrays.

    Attributes:
        _data: The underlying ``sparse.BCOO`` array.
    """

    _data: sparse.BCOO

    PROMOTION_ORDER = 1  # noqa: RUF012 — not a struct field; no annotation intentional

    @classmethod
    def from_data(cls, data) -> "SparseBCOOImpl":
        """Wrap *data* in a new ``SparseBCOOImpl``, converting to BCOO if needed.

        Args:
            data: A ``sparse.BCOO`` or array-like input.

        Returns:
            A ``SparseBCOOImpl`` wrapping a BCOO representation of *data*.
        """
        return cls(_data=cls._to_sparse(data))

    def get_data(self) -> Array:
        """Return the underlying BCOO sparse array."""
        return self._data

    def matmul(self, other: QarrayImpl) -> QarrayImpl:
        """Matrix multiply ``self @ other``.

        When *other* is a ``DenseImpl``, JAX's native BCOO @ dense path is
        used (no self-densification).  When *other* is also a
        ``SparseBCOOImpl``, a sparse @ sparse product is performed.

        Args:
            other: Right-hand operand.

        Returns:
            A ``DenseImpl`` (sparse @ dense) or ``SparseBCOOImpl`` (sparse @
            sparse) containing the matrix product.
        """
        if isinstance(other, DenseImpl):
            return DenseImpl(self._data @ other._data)
        a, b = self._coerce(other)
        if a is not self:
            return a.matmul(b)
        return SparseBCOOImpl(self._data @ b._data)

    def add(self, other: QarrayImpl) -> QarrayImpl:
        """Element-wise addition ``self + other``, coercing types as needed.

        Args:
            other: Right-hand operand.

        Returns:
            A ``SparseBCOOImpl`` (both sparse) or ``DenseImpl`` (mixed) sum.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.add(b)
        x, y = self._data, b._data
        if x.indices.dtype != y.indices.dtype:
            y = sparse.BCOO((y.data, y.indices.astype(x.indices.dtype)), shape=y.shape)
        return SparseBCOOImpl(x + y)

    def sub(self, other: QarrayImpl) -> QarrayImpl:
        """Element-wise subtraction ``self - other``, coercing types as needed.

        Args:
            other: Right-hand operand.

        Returns:
            A ``SparseBCOOImpl`` (both sparse) or ``DenseImpl`` (mixed) difference.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.sub(b)
        x, y = self._data, b._data
        if x.indices.dtype != y.indices.dtype:
            y = sparse.BCOO((y.data, y.indices.astype(x.indices.dtype)), shape=y.shape)
        return SparseBCOOImpl(x - y)

    def mul(self, scalar) -> QarrayImpl:
        """Scalar multiplication.

        Args:
            scalar: Scalar value.

        Returns:
            A ``SparseBCOOImpl`` with each stored value multiplied by *scalar*.
        """
        return SparseBCOOImpl(scalar * self._data)

    def dag(self) -> QarrayImpl:
        """Conjugate transpose without densifying.

        Transposes the last two dimensions of the BCOO array and conjugates
        the stored values.

        Returns:
            A ``SparseBCOOImpl`` containing the conjugate transpose.
        """
        ndim = self._data.ndim
        if ndim >= 2:
            permutation = tuple(range(ndim - 2)) + (ndim - 1, ndim - 2)
            transposed_data = sparse.bcoo_transpose(self._data, permutation=permutation)
        else:
            transposed_data = self._data

        conjugated_data = sparse.BCOO(
            (jnp.conj(transposed_data.data), transposed_data.indices),
            shape=transposed_data.shape,
        )
        return SparseBCOOImpl(conjugated_data)

    def to_dense(self) -> "DenseImpl":
        """Convert to a ``DenseImpl`` via ``todense()``.

        Returns:
            A ``DenseImpl`` with the same values as this sparse array.
        """
        return DenseImpl(self._data.todense())

    @classmethod
    def _to_sparse(cls, data) -> sparse.BCOO:
        """Convert *data* to a ``sparse.BCOO``, returning it unchanged if already sparse.

        Args:
            data: A ``sparse.BCOO`` or array-like.

        Returns:
            A ``sparse.BCOO`` representation of *data*.
        """
        if isinstance(data, sparse.BCOO):
            return data
        return sparse.BCOO.fromdense(data)

    def to_sparse_bcoo(self) -> "SparseBCOOImpl":
        """Return self (already sparse BCOO).

        Returns:
            This ``SparseBCOOImpl`` instance unchanged.
        """
        return self

    def shape(self) -> tuple:
        """Shape of the underlying BCOO array.

        Returns:
            Tuple of dimension sizes.
        """
        return self._data.shape

    def dtype(self):
        """Data type of the underlying BCOO array.

        Returns:
            The dtype of ``_data``.
        """
        return self._data.dtype

    def frobenius_norm(self) -> float:
        """Compute the Frobenius norm directly from stored values.

        Returns:
            The Frobenius norm as a scalar.
        """
        return jnp.sqrt(jnp.sum(jnp.abs(self._data.data) ** 2))

    @classmethod
    def _real(cls, data):
        """Return a BCOO array with only the real parts of the stored values."""
        return sparse.BCOO((jnp.real(data.data), data.indices), shape=data.shape)

    def real(self) -> QarrayImpl:
        """Element-wise real part.

        Returns:
            A ``SparseBCOOImpl`` containing the real parts of stored values.
        """
        return SparseBCOOImpl(SparseBCOOImpl._real(self._data))

    @classmethod
    def _imag(cls, data):
        """Return a BCOO array with only the imaginary parts of the stored values."""
        return sparse.BCOO((jnp.imag(data.data), data.indices), shape=data.shape)

    def imag(self) -> QarrayImpl:
        """Element-wise imaginary part.

        Returns:
            A ``SparseBCOOImpl`` containing the imaginary parts of stored values.
        """
        return SparseBCOOImpl(SparseBCOOImpl._imag(self._data))

    @classmethod
    def _conj(cls, data):
        """Return a BCOO array with complex-conjugated stored values."""
        return sparse.BCOO((jnp.conj(data.data), data.indices), shape=data.shape)

    def conj(self) -> QarrayImpl:
        """Element-wise complex conjugate.

        Returns:
            A ``SparseBCOOImpl`` containing the complex-conjugated stored values.
        """
        return SparseBCOOImpl(SparseBCOOImpl._conj(self._data))

    @classmethod
    def _abs(cls, data):
        """Return a BCOO array with absolute values of stored entries."""
        return sparse.sparsify(jnp.abs)(data)

    def abs(self) -> QarrayImpl:
        """Element-wise absolute value.

        Returns:
            A ``SparseBCOOImpl`` containing the absolute values of stored entries.
        """
        return SparseBCOOImpl(SparseBCOOImpl._abs(self._data))

    @classmethod
    def _eye_data(cls, n: int, dtype=None):
        """Create an ``n x n`` identity matrix as a sparse BCOO with O(n) memory.

        Args:
            n: Matrix size.
            dtype: Optional data type.

        Returns:
            A ``sparse.BCOO`` identity matrix of shape ``(n, n)``.
        """
        return sparse.eye(n, dtype=dtype)

    @classmethod
    def can_handle_data(cls, arr) -> bool:
        """Return True when *arr* is a ``sparse.BCOO`` array.

        Args:
            arr: Raw array.

        Returns:
            True if *arr* is a ``sparse.BCOO`` instance.
        """
        return isinstance(arr, sparse.BCOO)

    @classmethod
    def dag_data(cls, arr: sparse.BCOO) -> sparse.BCOO:
        """Conjugate transpose for BCOO sparse arrays without densifying.

        Args:
            arr: A ``sparse.BCOO`` array with ``ndim >= 2``.

        Returns:
            A ``sparse.BCOO`` containing the conjugate transpose.
        """
        ndim = arr.ndim
        permutation = tuple(range(ndim - 2)) + (ndim - 1, ndim - 2)
        transposed = sparse.bcoo_transpose(arr, permutation=permutation)
        return sparse.BCOO(
            (jnp.conj(transposed.data), transposed.indices),
            shape=transposed.shape,
        )

    def trace(self) -> Array:
        """Compute the trace of the last two matrix dimensions without densifying.

        Returns:
            Trace value(s).
        """
        indices = self._data.indices
        values = self._data.data
        ndim = indices.shape[-1]

        is_diag = indices[:, -2] == indices[:, -1]

        if ndim == 2:
            return jnp.sum(values * is_diag)
        else:
            batch_shape = self._data.shape[:-2]
            B = int(jnp.prod(jnp.array(batch_shape)))
            strides = [1]
            for s in reversed(batch_shape[1:]):
                strides.insert(0, strides[0] * s)
            strides = jnp.array(strides, dtype=jnp.int32)
            flat_batch_idx = jnp.sum(indices[:, :-2] * strides, axis=-1)
            result = jnp.zeros(B, dtype=values.dtype).at[flat_batch_idx].add(
                values * is_diag
            )
            return result.reshape(batch_shape)

    def keep_only_diag(self) -> "SparseBCOOImpl":
        """Zero out off-diagonal stored entries without densifying.

        Returns:
            A ``SparseBCOOImpl`` with only diagonal entries non-zero.
        """
        indices = self._data.indices
        values = self._data.data
        is_diag = indices[:, -2] == indices[:, -1]
        new_values = values * is_diag
        return SparseBCOOImpl(sparse.BCOO((new_values, indices), shape=self._data.shape))

    def l2_norm_batched(self, bdims: tuple) -> Array:
        """Compute the L2 norm per batch element without densifying.

        Args:
            bdims: Tuple of batch dimension sizes.

        Returns:
            Scalar or array of L2 norms.
        """
        values = self._data.data
        indices = self._data.indices
        n_batch_dims = len(bdims)
        sq = jnp.abs(values) ** 2

        if n_batch_dims == 0:
            return jnp.sqrt(jnp.sum(sq))
        else:
            B = int(jnp.prod(jnp.array(bdims)))
            strides = [1]
            for s in reversed(bdims[1:]):
                strides.insert(0, strides[0] * s)
            strides = jnp.array(strides, dtype=jnp.int32)
            flat_batch_idx = jnp.sum(indices[:, :n_batch_dims] * strides, axis=-1)
            sum_sq = (
                jnp.zeros(B, dtype=jnp.float64)
                .at[flat_batch_idx]
                .add(sq)
            )
            return jnp.sqrt(sum_sq).reshape(bdims)

    def __deepcopy__(self, memo=None):
        return SparseBCOOImpl(_data=deepcopy(self._data, memo))

    def tidy_up(self, atol) -> "SparseBCOOImpl":
        """Zero out stored values whose real or imaginary magnitude is below *atol*.

        Args:
            atol: Absolute tolerance threshold.

        Returns:
            A new ``SparseBCOOImpl`` with small values zeroed.
        """
        values = self._data.data
        re = jnp.real(values)
        im = jnp.imag(values)
        new_values = re * (jnp.abs(re) > atol) + 1j * im * (jnp.abs(im) > atol)
        return SparseBCOOImpl(
            sparse.BCOO((new_values, self._data.indices), shape=self._data.shape)
        )

    def kron(self, other: "QarrayImpl") -> "QarrayImpl":
        """Kronecker product using ``sparsify(jnp.kron)`` — stays sparse.

        Args:
            other: Right-hand operand.

        Returns:
            A ``SparseBCOOImpl`` containing the Kronecker product when both
            operands are sparse; a ``DenseImpl`` when types differ.
        """
        a, b = self._coerce(other)
        if a is not self:
            return a.kron(b)
        sparse_kron = sparse.sparsify(jnp.kron)
        return SparseBCOOImpl(sparse_kron(self._data, b._data))

abs()

Element-wise absolute value.

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl containing the absolute values of stored entries.

Source code in jaxquantum/core/sparse_bcoo.py
233
234
235
236
237
238
239
def abs(self) -> QarrayImpl:
    """Element-wise absolute value.

    Returns:
        A ``SparseBCOOImpl`` containing the absolute values of stored entries.
    """
    return SparseBCOOImpl(SparseBCOOImpl._abs(self._data))

add(other)

Element-wise addition self + other, coercing types as needed.

Parameters:

Name Type Description Default
other QarrayImpl

Right-hand operand.

required

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl (both sparse) or DenseImpl (mixed) sum.

Source code in jaxquantum/core/sparse_bcoo.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def add(self, other: QarrayImpl) -> QarrayImpl:
    """Element-wise addition ``self + other``, coercing types as needed.

    Args:
        other: Right-hand operand.

    Returns:
        A ``SparseBCOOImpl`` (both sparse) or ``DenseImpl`` (mixed) sum.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.add(b)
    x, y = self._data, b._data
    if x.indices.dtype != y.indices.dtype:
        y = sparse.BCOO((y.data, y.indices.astype(x.indices.dtype)), shape=y.shape)
    return SparseBCOOImpl(x + y)

can_handle_data(arr) classmethod

Return True when arr is a sparse.BCOO array.

Parameters:

Name Type Description Default
arr

Raw array.

required

Returns:

Type Description
bool

True if arr is a sparse.BCOO instance.

Source code in jaxquantum/core/sparse_bcoo.py
254
255
256
257
258
259
260
261
262
263
264
@classmethod
def can_handle_data(cls, arr) -> bool:
    """Return True when *arr* is a ``sparse.BCOO`` array.

    Args:
        arr: Raw array.

    Returns:
        True if *arr* is a ``sparse.BCOO`` instance.
    """
    return isinstance(arr, sparse.BCOO)

conj()

Element-wise complex conjugate.

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl containing the complex-conjugated stored values.

Source code in jaxquantum/core/sparse_bcoo.py
220
221
222
223
224
225
226
def conj(self) -> QarrayImpl:
    """Element-wise complex conjugate.

    Returns:
        A ``SparseBCOOImpl`` containing the complex-conjugated stored values.
    """
    return SparseBCOOImpl(SparseBCOOImpl._conj(self._data))

dag()

Conjugate transpose without densifying.

Transposes the last two dimensions of the BCOO array and conjugates the stored values.

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl containing the conjugate transpose.

Source code in jaxquantum/core/sparse_bcoo.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def dag(self) -> QarrayImpl:
    """Conjugate transpose without densifying.

    Transposes the last two dimensions of the BCOO array and conjugates
    the stored values.

    Returns:
        A ``SparseBCOOImpl`` containing the conjugate transpose.
    """
    ndim = self._data.ndim
    if ndim >= 2:
        permutation = tuple(range(ndim - 2)) + (ndim - 1, ndim - 2)
        transposed_data = sparse.bcoo_transpose(self._data, permutation=permutation)
    else:
        transposed_data = self._data

    conjugated_data = sparse.BCOO(
        (jnp.conj(transposed_data.data), transposed_data.indices),
        shape=transposed_data.shape,
    )
    return SparseBCOOImpl(conjugated_data)

dag_data(arr) classmethod

Conjugate transpose for BCOO sparse arrays without densifying.

Parameters:

Name Type Description Default
arr BCOO

A sparse.BCOO array with ndim >= 2.

required

Returns:

Type Description
BCOO

A sparse.BCOO containing the conjugate transpose.

Source code in jaxquantum/core/sparse_bcoo.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
@classmethod
def dag_data(cls, arr: sparse.BCOO) -> sparse.BCOO:
    """Conjugate transpose for BCOO sparse arrays without densifying.

    Args:
        arr: A ``sparse.BCOO`` array with ``ndim >= 2``.

    Returns:
        A ``sparse.BCOO`` containing the conjugate transpose.
    """
    ndim = arr.ndim
    permutation = tuple(range(ndim - 2)) + (ndim - 1, ndim - 2)
    transposed = sparse.bcoo_transpose(arr, permutation=permutation)
    return sparse.BCOO(
        (jnp.conj(transposed.data), transposed.indices),
        shape=transposed.shape,
    )

dtype()

Data type of the underlying BCOO array.

Returns:

Type Description

The dtype of _data.

Source code in jaxquantum/core/sparse_bcoo.py
173
174
175
176
177
178
179
def dtype(self):
    """Data type of the underlying BCOO array.

    Returns:
        The dtype of ``_data``.
    """
    return self._data.dtype

frobenius_norm()

Compute the Frobenius norm directly from stored values.

Returns:

Type Description
float

The Frobenius norm as a scalar.

Source code in jaxquantum/core/sparse_bcoo.py
181
182
183
184
185
186
187
def frobenius_norm(self) -> float:
    """Compute the Frobenius norm directly from stored values.

    Returns:
        The Frobenius norm as a scalar.
    """
    return jnp.sqrt(jnp.sum(jnp.abs(self._data.data) ** 2))

from_data(data) classmethod

Wrap data in a new SparseBCOOImpl, converting to BCOO if needed.

Parameters:

Name Type Description Default
data

A sparse.BCOO or array-like input.

required

Returns:

Type Description
'SparseBCOOImpl'

A SparseBCOOImpl wrapping a BCOO representation of data.

Source code in jaxquantum/core/sparse_bcoo.py
31
32
33
34
35
36
37
38
39
40
41
@classmethod
def from_data(cls, data) -> "SparseBCOOImpl":
    """Wrap *data* in a new ``SparseBCOOImpl``, converting to BCOO if needed.

    Args:
        data: A ``sparse.BCOO`` or array-like input.

    Returns:
        A ``SparseBCOOImpl`` wrapping a BCOO representation of *data*.
    """
    return cls(_data=cls._to_sparse(data))

get_data()

Return the underlying BCOO sparse array.

Source code in jaxquantum/core/sparse_bcoo.py
43
44
45
def get_data(self) -> Array:
    """Return the underlying BCOO sparse array."""
    return self._data

imag()

Element-wise imaginary part.

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl containing the imaginary parts of stored values.

Source code in jaxquantum/core/sparse_bcoo.py
207
208
209
210
211
212
213
def imag(self) -> QarrayImpl:
    """Element-wise imaginary part.

    Returns:
        A ``SparseBCOOImpl`` containing the imaginary parts of stored values.
    """
    return SparseBCOOImpl(SparseBCOOImpl._imag(self._data))

keep_only_diag()

Zero out off-diagonal stored entries without densifying.

Returns:

Type Description
'SparseBCOOImpl'

A SparseBCOOImpl with only diagonal entries non-zero.

Source code in jaxquantum/core/sparse_bcoo.py
311
312
313
314
315
316
317
318
319
320
321
def keep_only_diag(self) -> "SparseBCOOImpl":
    """Zero out off-diagonal stored entries without densifying.

    Returns:
        A ``SparseBCOOImpl`` with only diagonal entries non-zero.
    """
    indices = self._data.indices
    values = self._data.data
    is_diag = indices[:, -2] == indices[:, -1]
    new_values = values * is_diag
    return SparseBCOOImpl(sparse.BCOO((new_values, indices), shape=self._data.shape))

kron(other)

Kronecker product using sparsify(jnp.kron) — stays sparse.

Parameters:

Name Type Description Default
other 'QarrayImpl'

Right-hand operand.

required

Returns:

Type Description
'QarrayImpl'

A SparseBCOOImpl containing the Kronecker product when both

'QarrayImpl'

operands are sparse; a DenseImpl when types differ.

Source code in jaxquantum/core/sparse_bcoo.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def kron(self, other: "QarrayImpl") -> "QarrayImpl":
    """Kronecker product using ``sparsify(jnp.kron)`` — stays sparse.

    Args:
        other: Right-hand operand.

    Returns:
        A ``SparseBCOOImpl`` containing the Kronecker product when both
        operands are sparse; a ``DenseImpl`` when types differ.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.kron(b)
    sparse_kron = sparse.sparsify(jnp.kron)
    return SparseBCOOImpl(sparse_kron(self._data, b._data))

l2_norm_batched(bdims)

Compute the L2 norm per batch element without densifying.

Parameters:

Name Type Description Default
bdims tuple

Tuple of batch dimension sizes.

required

Returns:

Type Description
Array

Scalar or array of L2 norms.

Source code in jaxquantum/core/sparse_bcoo.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def l2_norm_batched(self, bdims: tuple) -> Array:
    """Compute the L2 norm per batch element without densifying.

    Args:
        bdims: Tuple of batch dimension sizes.

    Returns:
        Scalar or array of L2 norms.
    """
    values = self._data.data
    indices = self._data.indices
    n_batch_dims = len(bdims)
    sq = jnp.abs(values) ** 2

    if n_batch_dims == 0:
        return jnp.sqrt(jnp.sum(sq))
    else:
        B = int(jnp.prod(jnp.array(bdims)))
        strides = [1]
        for s in reversed(bdims[1:]):
            strides.insert(0, strides[0] * s)
        strides = jnp.array(strides, dtype=jnp.int32)
        flat_batch_idx = jnp.sum(indices[:, :n_batch_dims] * strides, axis=-1)
        sum_sq = (
            jnp.zeros(B, dtype=jnp.float64)
            .at[flat_batch_idx]
            .add(sq)
        )
        return jnp.sqrt(sum_sq).reshape(bdims)

matmul(other)

Matrix multiply self @ other.

When other is a DenseImpl, JAX's native BCOO @ dense path is used (no self-densification). When other is also a SparseBCOOImpl, a sparse @ sparse product is performed.

Parameters:

Name Type Description Default
other QarrayImpl

Right-hand operand.

required

Returns:

Type Description
QarrayImpl

A DenseImpl (sparse @ dense) or SparseBCOOImpl (sparse @

QarrayImpl

sparse) containing the matrix product.

Source code in jaxquantum/core/sparse_bcoo.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def matmul(self, other: QarrayImpl) -> QarrayImpl:
    """Matrix multiply ``self @ other``.

    When *other* is a ``DenseImpl``, JAX's native BCOO @ dense path is
    used (no self-densification).  When *other* is also a
    ``SparseBCOOImpl``, a sparse @ sparse product is performed.

    Args:
        other: Right-hand operand.

    Returns:
        A ``DenseImpl`` (sparse @ dense) or ``SparseBCOOImpl`` (sparse @
        sparse) containing the matrix product.
    """
    if isinstance(other, DenseImpl):
        return DenseImpl(self._data @ other._data)
    a, b = self._coerce(other)
    if a is not self:
        return a.matmul(b)
    return SparseBCOOImpl(self._data @ b._data)

mul(scalar)

Scalar multiplication.

Parameters:

Name Type Description Default
scalar

Scalar value.

required

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl with each stored value multiplied by scalar.

Source code in jaxquantum/core/sparse_bcoo.py
102
103
104
105
106
107
108
109
110
111
def mul(self, scalar) -> QarrayImpl:
    """Scalar multiplication.

    Args:
        scalar: Scalar value.

    Returns:
        A ``SparseBCOOImpl`` with each stored value multiplied by *scalar*.
    """
    return SparseBCOOImpl(scalar * self._data)

real()

Element-wise real part.

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl containing the real parts of stored values.

Source code in jaxquantum/core/sparse_bcoo.py
194
195
196
197
198
199
200
def real(self) -> QarrayImpl:
    """Element-wise real part.

    Returns:
        A ``SparseBCOOImpl`` containing the real parts of stored values.
    """
    return SparseBCOOImpl(SparseBCOOImpl._real(self._data))

shape()

Shape of the underlying BCOO array.

Returns:

Type Description
tuple

Tuple of dimension sizes.

Source code in jaxquantum/core/sparse_bcoo.py
165
166
167
168
169
170
171
def shape(self) -> tuple:
    """Shape of the underlying BCOO array.

    Returns:
        Tuple of dimension sizes.
    """
    return self._data.shape

sub(other)

Element-wise subtraction self - other, coercing types as needed.

Parameters:

Name Type Description Default
other QarrayImpl

Right-hand operand.

required

Returns:

Type Description
QarrayImpl

A SparseBCOOImpl (both sparse) or DenseImpl (mixed) difference.

Source code in jaxquantum/core/sparse_bcoo.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def sub(self, other: QarrayImpl) -> QarrayImpl:
    """Element-wise subtraction ``self - other``, coercing types as needed.

    Args:
        other: Right-hand operand.

    Returns:
        A ``SparseBCOOImpl`` (both sparse) or ``DenseImpl`` (mixed) difference.
    """
    a, b = self._coerce(other)
    if a is not self:
        return a.sub(b)
    x, y = self._data, b._data
    if x.indices.dtype != y.indices.dtype:
        y = sparse.BCOO((y.data, y.indices.astype(x.indices.dtype)), shape=y.shape)
    return SparseBCOOImpl(x - y)

tidy_up(atol)

Zero out stored values whose real or imaginary magnitude is below atol.

Parameters:

Name Type Description Default
atol

Absolute tolerance threshold.

required

Returns:

Type Description
'SparseBCOOImpl'

A new SparseBCOOImpl with small values zeroed.

Source code in jaxquantum/core/sparse_bcoo.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def tidy_up(self, atol) -> "SparseBCOOImpl":
    """Zero out stored values whose real or imaginary magnitude is below *atol*.

    Args:
        atol: Absolute tolerance threshold.

    Returns:
        A new ``SparseBCOOImpl`` with small values zeroed.
    """
    values = self._data.data
    re = jnp.real(values)
    im = jnp.imag(values)
    new_values = re * (jnp.abs(re) > atol) + 1j * im * (jnp.abs(im) > atol)
    return SparseBCOOImpl(
        sparse.BCOO((new_values, self._data.indices), shape=self._data.shape)
    )

to_dense()

Convert to a DenseImpl via todense().

Returns:

Type Description
'DenseImpl'

A DenseImpl with the same values as this sparse array.

Source code in jaxquantum/core/sparse_bcoo.py
135
136
137
138
139
140
141
def to_dense(self) -> "DenseImpl":
    """Convert to a ``DenseImpl`` via ``todense()``.

    Returns:
        A ``DenseImpl`` with the same values as this sparse array.
    """
    return DenseImpl(self._data.todense())

to_sparse_bcoo()

Return self (already sparse BCOO).

Returns:

Type Description
'SparseBCOOImpl'

This SparseBCOOImpl instance unchanged.

Source code in jaxquantum/core/sparse_bcoo.py
157
158
159
160
161
162
163
def to_sparse_bcoo(self) -> "SparseBCOOImpl":
    """Return self (already sparse BCOO).

    Returns:
        This ``SparseBCOOImpl`` instance unchanged.
    """
    return self

trace()

Compute the trace of the last two matrix dimensions without densifying.

Returns:

Type Description
Array

Trace value(s).

Source code in jaxquantum/core/sparse_bcoo.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def trace(self) -> Array:
    """Compute the trace of the last two matrix dimensions without densifying.

    Returns:
        Trace value(s).
    """
    indices = self._data.indices
    values = self._data.data
    ndim = indices.shape[-1]

    is_diag = indices[:, -2] == indices[:, -1]

    if ndim == 2:
        return jnp.sum(values * is_diag)
    else:
        batch_shape = self._data.shape[:-2]
        B = int(jnp.prod(jnp.array(batch_shape)))
        strides = [1]
        for s in reversed(batch_shape[1:]):
            strides.insert(0, strides[0] * s)
        strides = jnp.array(strides, dtype=jnp.int32)
        flat_batch_idx = jnp.sum(indices[:, :-2] * strides, axis=-1)
        result = jnp.zeros(B, dtype=values.dtype).at[flat_batch_idx].add(
            values * is_diag
        )
        return result.reshape(batch_shape)

SparseDiaData

Lightweight pytree-compatible container for sparse-diagonal raw data.

Returned by SparseDiaImpl.get_data() and consumed by SparseDiaImpl.from_data(). Registered as a JAX pytree via Flax's @struct.dataclass; offsets is not a pytree leaf (it is static compile-time metadata).

Attributes:

Name Type Description
offsets tuple

Static tuple of diagonal offsets (pytree_node=False).

diags Array

JAX array of shape (*batch, n_diags, n) containing the padded diagonal values.

Source code in jaxquantum/core/sparse_dia.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
@struct.dataclass
class SparseDiaData:
    """Lightweight pytree-compatible container for sparse-diagonal raw data.

    Returned by ``SparseDiaImpl.get_data()`` and consumed by
    ``SparseDiaImpl.from_data()``.  Registered as a JAX pytree via Flax's
    ``@struct.dataclass``; ``offsets`` is *not* a pytree leaf (it is static
    compile-time metadata).

    Attributes:
        offsets: Static tuple of diagonal offsets (pytree_node=False).
        diags:   JAX array of shape (*batch, n_diags, n) containing the
                 padded diagonal values.
    """

    offsets: tuple = struct.field(pytree_node=False)
    diags: Array

    # Class-level marker (not a dataclass field — no type annotation).
    # Used by DenseImpl.can_handle_data to exclude SparseDiaData without
    # a direct import (which would be circular).
    _is_sparse_dia = True

    @property
    def shape(self) -> tuple:
        """Shape of the represented square matrix (*batch, n, n)."""
        n = self.diags.shape[-1]
        return (*self.diags.shape[:-2], n, n)

    @property
    def dtype(self):
        """Dtype of the stored diagonal values."""
        return self.diags.dtype

    def __mul__(self, scalar):
        return SparseDiaData(offsets=self.offsets, diags=self.diags * scalar)

    def __rmul__(self, scalar):
        return SparseDiaData(offsets=self.offsets, diags=scalar * self.diags)

    def __getitem__(self, index):
        """Index into the batch dimension(s), preserving offsets."""
        return SparseDiaData(offsets=self.offsets, diags=self.diags[index])

    def __len__(self):
        """Number of elements along the leading batch dimension."""
        return self.shape[0]

    def reshape(self, *new_shape):
        """Reshape batch dimensions while preserving diagonal structure.

        ``new_shape`` must end with ``(N, N)`` (the matrix dims are unchanged).
        Only the leading batch dims are reshaped.
        """
        new_batch = new_shape[:-2]
        n = self.diags.shape[-1]
        new_diags = self.diags.reshape(*new_batch, len(self.offsets), n)
        return SparseDiaData(offsets=self.offsets, diags=new_diags)

    def __matmul__(self, other):
        """SparseDIA @ dense → dense (used by mesolve ODE RHS)."""
        # _sparsedia_matmul_dense is defined later in this module; Python
        # resolves the name at call time so forward reference is fine.
        return _sparsedia_matmul_dense(self.offsets, self.diags, other)

    def __rmatmul__(self, other):
        """dense @ SparseDIA → dense (used by mesolve ODE RHS)."""
        return _sparsedia_rmatmul_dense(other, self.offsets, self.diags)

dtype property

Dtype of the stored diagonal values.

shape property

Shape of the represented square matrix (*batch, n, n).

__getitem__(index)

Index into the batch dimension(s), preserving offsets.

Source code in jaxquantum/core/sparse_dia.py
105
106
107
def __getitem__(self, index):
    """Index into the batch dimension(s), preserving offsets."""
    return SparseDiaData(offsets=self.offsets, diags=self.diags[index])

__len__()

Number of elements along the leading batch dimension.

Source code in jaxquantum/core/sparse_dia.py
109
110
111
def __len__(self):
    """Number of elements along the leading batch dimension."""
    return self.shape[0]

__matmul__(other)

SparseDIA @ dense → dense (used by mesolve ODE RHS).

Source code in jaxquantum/core/sparse_dia.py
124
125
126
127
128
def __matmul__(self, other):
    """SparseDIA @ dense → dense (used by mesolve ODE RHS)."""
    # _sparsedia_matmul_dense is defined later in this module; Python
    # resolves the name at call time so forward reference is fine.
    return _sparsedia_matmul_dense(self.offsets, self.diags, other)

__rmatmul__(other)

dense @ SparseDIA → dense (used by mesolve ODE RHS).

Source code in jaxquantum/core/sparse_dia.py
130
131
132
def __rmatmul__(self, other):
    """dense @ SparseDIA → dense (used by mesolve ODE RHS)."""
    return _sparsedia_rmatmul_dense(other, self.offsets, self.diags)

reshape(*new_shape)

Reshape batch dimensions while preserving diagonal structure.

new_shape must end with (N, N) (the matrix dims are unchanged). Only the leading batch dims are reshaped.

Source code in jaxquantum/core/sparse_dia.py
113
114
115
116
117
118
119
120
121
122
def reshape(self, *new_shape):
    """Reshape batch dimensions while preserving diagonal structure.

    ``new_shape`` must end with ``(N, N)`` (the matrix dims are unchanged).
    Only the leading batch dims are reshaped.
    """
    new_batch = new_shape[:-2]
    n = self.diags.shape[-1]
    new_diags = self.diags.reshape(*new_batch, len(self.offsets), n)
    return SparseDiaData(offsets=self.offsets, diags=new_diags)

SparseDiaImpl

Bases: QarrayImpl

Sparse-diagonal backend storing only diagonal values.

Data layout::

_offsets  : tuple[int, ...]          — static (pytree_node=False)
_diags    : Array[*batch, n_diags, n] — JAX-traced values

For offset k, the convention is: * k ≥ 0 : valid data at _diags[..., i, k:], zeros at [0:k] * k < 0 : valid data at _diags[..., i, :n+k], zeros at [n+k:]

In both cases: A[row, row+k] = _diags[..., i, row+k]

Source code in jaxquantum/core/sparse_dia.py
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
@struct.dataclass
class SparseDiaImpl(QarrayImpl):
    """Sparse-diagonal backend storing only diagonal values.

    Data layout::

        _offsets  : tuple[int, ...]          — static (pytree_node=False)
        _diags    : Array[*batch, n_diags, n] — JAX-traced values

    For offset k, the convention is:
        * k ≥ 0 : valid data at ``_diags[..., i, k:]``, zeros at ``[0:k]``
        * k < 0 : valid data at ``_diags[..., i, :n+k]``, zeros at ``[n+k:]``

    In both cases: ``A[row, row+k] = _diags[..., i, row+k]``
    """

    _offsets: tuple = struct.field(pytree_node=False)
    _diags: Array

    PROMOTION_ORDER = 0  # noqa: RUF012 — not a struct field

    # ------------------------------------------------------------------
    # Construction
    # ------------------------------------------------------------------

    @classmethod
    def from_data(cls, data) -> "SparseDiaImpl":
        """Wrap *data* in a new ``SparseDiaImpl``.

        Accepts either a :class:`SparseDiaData` container (direct wrap) or
        a dense array-like (auto-detect non-zero diagonals via numpy, safe
        to call before JIT).

        Args:
            data: A :class:`SparseDiaData` or dense array of shape
                (*batch, n, n).

        Returns:
            A new ``SparseDiaImpl`` instance.
        """
        if isinstance(data, SparseDiaData):
            return cls(_offsets=data.offsets, _diags=data.diags)
        offsets, diags_np = _dense_to_sparsedia(np.asarray(data))
        return cls(_offsets=offsets, _diags=jnp.array(diags_np))

    @classmethod
    def from_diags(cls, offsets: tuple, diags: Array) -> "SparseDiaImpl":
        """Directly construct from sorted offsets and padded diagonal array.

        This is the preferred factory when diagonal structure is known in
        advance (e.g., when building ``destroy`` or ``create`` operators).

        Args:
            offsets: Tuple of integer diagonal offsets (need not be sorted;
                will be sorted internally).
            diags:   JAX array of shape (*batch, n_diags, n) with padded
                     diagonal values matching *offsets*.

        Returns:
            A new ``SparseDiaImpl`` instance.
        """
        return cls(_offsets=tuple(sorted(offsets)), _diags=diags)

    # ------------------------------------------------------------------
    # QarrayImpl abstract methods
    # ------------------------------------------------------------------

    def get_data(self) -> SparseDiaData:
        """Return a :class:`SparseDiaData` container with the raw diagonal data."""
        return SparseDiaData(offsets=self._offsets, diags=self._diags)

    def shape(self) -> tuple:
        """Shape of the represented square matrix (including batch dims)."""
        n = self._diags.shape[-1]
        return (*self._diags.shape[:-2], n, n)

    def dtype(self):
        """Dtype of the stored diagonal values."""
        return self._diags.dtype

    def __deepcopy__(self, memo=None):
        return SparseDiaImpl(
            _offsets=deepcopy(self._offsets),
            _diags=self._diags,
        )

    # ------------------------------------------------------------------
    # Arithmetic
    # ------------------------------------------------------------------

    def mul(self, scalar) -> "SparseDiaImpl":
        """Scalar multiplication — scales all diagonal values."""
        return SparseDiaImpl(_offsets=self._offsets, _diags=scalar * self._diags)

    def neg(self) -> "SparseDiaImpl":
        """Negation."""
        return SparseDiaImpl(_offsets=self._offsets, _diags=-self._diags)

    def add(self, other: QarrayImpl) -> QarrayImpl:
        """Element-wise addition.

        SparseDIA + SparseDIA stays SparseDIA (union of offsets, static).
        Otherwise coerces to the higher-order type.
        """
        if isinstance(other, SparseDiaImpl):
            return _sparsedia_add(self, other)
        a, b = self._coerce(other)
        if a is not self:
            return a.add(b)
        return a.add(b)

    def sub(self, other: QarrayImpl) -> QarrayImpl:
        """Element-wise subtraction."""
        if isinstance(other, SparseDiaImpl):
            return _sparsedia_add(self, other, subtract=True)
        a, b = self._coerce(other)
        if a is not self:
            return a.sub(b)
        return a.sub(b)

    def matmul(self, other: QarrayImpl) -> QarrayImpl:
        """Matrix multiplication.

        * SparseDIA @ SparseDIA → SparseDIA  (O(d₁·d₂·n))
        * SparseDIA @ Dense    → Dense       (O(d·n²), no densification of self)
        * Others               → coerce then delegate
        """
        if isinstance(other, DenseImpl):
            return DenseImpl(_sparsedia_matmul_dense(
                self._offsets, self._diags, other._data
            ))
        if isinstance(other, SparseDiaImpl):
            offsets, diags = _sparsedia_matmul_sparsedia(
                self._offsets, self._diags,
                other._offsets, other._diags,
            )
            return SparseDiaImpl(_offsets=offsets, _diags=diags)
        a, b = self._coerce(other)
        if a is not self:
            return a.matmul(b)
        return a.matmul(b)

    def dag(self) -> "SparseDiaImpl":
        """Conjugate transpose without densification.

        Negates every offset and rearranges the stored values so that the
        padding convention remains consistent.
        """
        new_offsets = tuple(-k for k in self._offsets)
        new_diags = jnp.zeros_like(self._diags)
        for i, k in enumerate(self._offsets):
            s = _dia_slice(k)    # valid data slice for offset k
            sm = _dia_slice(-k)  # valid data slice for offset -k (the new position)
            new_diags = new_diags.at[..., i, sm].set(jnp.conj(self._diags[..., i, s]))
        return SparseDiaImpl(_offsets=new_offsets, _diags=new_diags)

    def kron(self, other: QarrayImpl) -> QarrayImpl:
        """Kronecker product.

        SparseDIA ⊗ SparseDIA stays SparseDIA: output offset for pair
        (kA, kB) is ``kA * m + kB`` where m = dim(B).  Fully vectorised —
        no loops at JAX level.
        """
        if isinstance(other, SparseDiaImpl):
            return _sparsedia_kron(self, other)
        a, b = self._coerce(other)
        if a is not self:
            return a.kron(b)
        return a.kron(b)

    def tidy_up(self, atol) -> "SparseDiaImpl":
        """Zero diagonal values whose magnitude is below *atol*."""
        diags = self._diags
        real_part = jnp.where(jnp.abs(jnp.real(diags)) < atol, 0.0, jnp.real(diags))
        if jnp.issubdtype(diags.dtype, jnp.complexfloating):
            imag_part = jnp.where(jnp.abs(jnp.imag(diags)) < atol, 0.0, jnp.imag(diags))
            new_diags = (real_part + 1j * imag_part).astype(diags.dtype)
        else:
            new_diags = real_part.astype(diags.dtype)
        return SparseDiaImpl(_offsets=self._offsets, _diags=new_diags)

    # ------------------------------------------------------------------
    # Conversions
    # ------------------------------------------------------------------

    def to_dense(self) -> "DenseImpl":
        """Convert to a ``DenseImpl`` by summing diagonal contributions."""
        n = self._diags.shape[-1]
        batch_shape = self._diags.shape[:-2]
        result = jnp.zeros((*batch_shape, n, n), dtype=self._diags.dtype)
        for i, k in enumerate(self._offsets):
            s = _dia_slice(k)
            length = n - abs(k)
            if length <= 0:
                continue
            vals = self._diags[..., i, s]
            row_idx = jnp.arange(length) + max(-k, 0)
            col_idx = row_idx + k
            result = result.at[..., row_idx, col_idx].set(vals)
        return DenseImpl(result)

    def to_sparse_bcoo(self) -> "SparseBCOOImpl":
        """Convert to a ``SparseBCOOImpl`` (BCOO) via dense."""
        return self.to_dense().to_sparse_bcoo()

    def to_sparse_dia(self) -> "SparseDiaImpl":
        """Return self (already SparseDIA)."""
        return self

    # ------------------------------------------------------------------
    # Class-method interface
    # ------------------------------------------------------------------

    @classmethod
    def _eye_data(cls, n: int, dtype=None):
        """Return an n×n identity as a dense JAX array.

        ``from_data`` will automatically convert it to SparseDIA format
        when the implementation type is ``SPARSE_DIA``.
        """
        return jnp.eye(n, dtype=dtype)

    @classmethod
    def can_handle_data(cls, arr) -> bool:
        """Return True only for :class:`SparseDiaData` objects."""
        return isinstance(arr, SparseDiaData)

    @classmethod
    def dag_data(cls, arr: SparseDiaData) -> SparseDiaData:
        """Conjugate transpose of raw :class:`SparseDiaData` without densification."""
        impl = SparseDiaImpl(_offsets=arr.offsets, _diags=arr.diags)
        result = impl.dag()
        return result.get_data()

    # ------------------------------------------------------------------
    # Extra sparse-native methods (no densification)
    # ------------------------------------------------------------------

    def trace(self):
        """Compute trace directly from the main diagonal (offset 0).

        Returns:
            Scalar trace (sum of main diagonal values).
        """
        if 0 in self._offsets:
            i = self._offsets.index(0)
            return jnp.sum(self._diags[..., i, :], axis=-1)
        return jnp.zeros(self._diags.shape[:-2], dtype=self._diags.dtype)

    def frobenius_norm(self):
        """Frobenius norm computed directly from stored diagonal values."""
        return jnp.sqrt(jnp.sum(jnp.abs(self._diags) ** 2))

    def real(self) -> "SparseDiaImpl":
        """Element-wise real part of stored values."""
        return SparseDiaImpl(
            _offsets=self._offsets,
            _diags=jnp.real(self._diags).astype(self._diags.dtype),
        )

    def imag(self) -> "SparseDiaImpl":
        """Element-wise imaginary part of stored values."""
        return SparseDiaImpl(
            _offsets=self._offsets,
            _diags=jnp.imag(self._diags).astype(self._diags.dtype),
        )

    def conj(self) -> "SparseDiaImpl":
        """Element-wise complex conjugate of stored values."""
        return SparseDiaImpl(_offsets=self._offsets, _diags=jnp.conj(self._diags))

    def powm(self, n: int) -> "SparseDiaImpl":
        """Integer matrix power staying SparseDIA via binary exponentiation.

        Uses O(log n) SparseDIA @ SparseDIA multiplications rather than
        densifying.  A^0 returns the identity operator.

        Args:
            n: Non-negative integer exponent.

        Returns:
            A ``SparseDiaImpl`` equal to this matrix raised to the *n*-th power.

        Raises:
            ValueError: If *n* is negative.
        """
        if n < 0:
            raise ValueError("powm requires n >= 0")
        if n == 0:
            size = self._diags.shape[-1]
            eye_diags = jnp.ones((*self._diags.shape[:-2], 1, size), dtype=self._diags.dtype)
            return SparseDiaImpl(_offsets=(0,), _diags=eye_diags)
        if n == 1:
            return self
        half = self.powm(n // 2)
        squared = half.matmul(half)  # SparseDIA @ SparseDIA → SparseDIA
        return squared if n % 2 == 0 else self.matmul(squared)

add(other)

Element-wise addition.

SparseDIA + SparseDIA stays SparseDIA (union of offsets, static). Otherwise coerces to the higher-order type.

Source code in jaxquantum/core/sparse_dia.py
280
281
282
283
284
285
286
287
288
289
290
291
def add(self, other: QarrayImpl) -> QarrayImpl:
    """Element-wise addition.

    SparseDIA + SparseDIA stays SparseDIA (union of offsets, static).
    Otherwise coerces to the higher-order type.
    """
    if isinstance(other, SparseDiaImpl):
        return _sparsedia_add(self, other)
    a, b = self._coerce(other)
    if a is not self:
        return a.add(b)
    return a.add(b)

can_handle_data(arr) classmethod

Return True only for :class:SparseDiaData objects.

Source code in jaxquantum/core/sparse_dia.py
404
405
406
407
@classmethod
def can_handle_data(cls, arr) -> bool:
    """Return True only for :class:`SparseDiaData` objects."""
    return isinstance(arr, SparseDiaData)

conj()

Element-wise complex conjugate of stored values.

Source code in jaxquantum/core/sparse_dia.py
449
450
451
def conj(self) -> "SparseDiaImpl":
    """Element-wise complex conjugate of stored values."""
    return SparseDiaImpl(_offsets=self._offsets, _diags=jnp.conj(self._diags))

dag()

Conjugate transpose without densification.

Negates every offset and rearranges the stored values so that the padding convention remains consistent.

Source code in jaxquantum/core/sparse_dia.py
324
325
326
327
328
329
330
331
332
333
334
335
336
def dag(self) -> "SparseDiaImpl":
    """Conjugate transpose without densification.

    Negates every offset and rearranges the stored values so that the
    padding convention remains consistent.
    """
    new_offsets = tuple(-k for k in self._offsets)
    new_diags = jnp.zeros_like(self._diags)
    for i, k in enumerate(self._offsets):
        s = _dia_slice(k)    # valid data slice for offset k
        sm = _dia_slice(-k)  # valid data slice for offset -k (the new position)
        new_diags = new_diags.at[..., i, sm].set(jnp.conj(self._diags[..., i, s]))
    return SparseDiaImpl(_offsets=new_offsets, _diags=new_diags)

dag_data(arr) classmethod

Conjugate transpose of raw :class:SparseDiaData without densification.

Source code in jaxquantum/core/sparse_dia.py
409
410
411
412
413
414
@classmethod
def dag_data(cls, arr: SparseDiaData) -> SparseDiaData:
    """Conjugate transpose of raw :class:`SparseDiaData` without densification."""
    impl = SparseDiaImpl(_offsets=arr.offsets, _diags=arr.diags)
    result = impl.dag()
    return result.get_data()

dtype()

Dtype of the stored diagonal values.

Source code in jaxquantum/core/sparse_dia.py
258
259
260
def dtype(self):
    """Dtype of the stored diagonal values."""
    return self._diags.dtype

frobenius_norm()

Frobenius norm computed directly from stored diagonal values.

Source code in jaxquantum/core/sparse_dia.py
431
432
433
def frobenius_norm(self):
    """Frobenius norm computed directly from stored diagonal values."""
    return jnp.sqrt(jnp.sum(jnp.abs(self._diags) ** 2))

from_data(data) classmethod

Wrap data in a new SparseDiaImpl.

Accepts either a :class:SparseDiaData container (direct wrap) or a dense array-like (auto-detect non-zero diagonals via numpy, safe to call before JIT).

Parameters:

Name Type Description Default
data

A :class:SparseDiaData or dense array of shape (*batch, n, n).

required

Returns:

Type Description
'SparseDiaImpl'

A new SparseDiaImpl instance.

Source code in jaxquantum/core/sparse_dia.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
@classmethod
def from_data(cls, data) -> "SparseDiaImpl":
    """Wrap *data* in a new ``SparseDiaImpl``.

    Accepts either a :class:`SparseDiaData` container (direct wrap) or
    a dense array-like (auto-detect non-zero diagonals via numpy, safe
    to call before JIT).

    Args:
        data: A :class:`SparseDiaData` or dense array of shape
            (*batch, n, n).

    Returns:
        A new ``SparseDiaImpl`` instance.
    """
    if isinstance(data, SparseDiaData):
        return cls(_offsets=data.offsets, _diags=data.diags)
    offsets, diags_np = _dense_to_sparsedia(np.asarray(data))
    return cls(_offsets=offsets, _diags=jnp.array(diags_np))

from_diags(offsets, diags) classmethod

Directly construct from sorted offsets and padded diagonal array.

This is the preferred factory when diagonal structure is known in advance (e.g., when building destroy or create operators).

Parameters:

Name Type Description Default
offsets tuple

Tuple of integer diagonal offsets (need not be sorted; will be sorted internally).

required
diags Array

JAX array of shape (batch, n_diags, n) with padded diagonal values matching *offsets.

required

Returns:

Type Description
'SparseDiaImpl'

A new SparseDiaImpl instance.

Source code in jaxquantum/core/sparse_dia.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
@classmethod
def from_diags(cls, offsets: tuple, diags: Array) -> "SparseDiaImpl":
    """Directly construct from sorted offsets and padded diagonal array.

    This is the preferred factory when diagonal structure is known in
    advance (e.g., when building ``destroy`` or ``create`` operators).

    Args:
        offsets: Tuple of integer diagonal offsets (need not be sorted;
            will be sorted internally).
        diags:   JAX array of shape (*batch, n_diags, n) with padded
                 diagonal values matching *offsets*.

    Returns:
        A new ``SparseDiaImpl`` instance.
    """
    return cls(_offsets=tuple(sorted(offsets)), _diags=diags)

get_data()

Return a :class:SparseDiaData container with the raw diagonal data.

Source code in jaxquantum/core/sparse_dia.py
249
250
251
def get_data(self) -> SparseDiaData:
    """Return a :class:`SparseDiaData` container with the raw diagonal data."""
    return SparseDiaData(offsets=self._offsets, diags=self._diags)

imag()

Element-wise imaginary part of stored values.

Source code in jaxquantum/core/sparse_dia.py
442
443
444
445
446
447
def imag(self) -> "SparseDiaImpl":
    """Element-wise imaginary part of stored values."""
    return SparseDiaImpl(
        _offsets=self._offsets,
        _diags=jnp.imag(self._diags).astype(self._diags.dtype),
    )

kron(other)

Kronecker product.

SparseDIA ⊗ SparseDIA stays SparseDIA: output offset for pair (kA, kB) is kA * m + kB where m = dim(B). Fully vectorised — no loops at JAX level.

Source code in jaxquantum/core/sparse_dia.py
338
339
340
341
342
343
344
345
346
347
348
349
350
def kron(self, other: QarrayImpl) -> QarrayImpl:
    """Kronecker product.

    SparseDIA ⊗ SparseDIA stays SparseDIA: output offset for pair
    (kA, kB) is ``kA * m + kB`` where m = dim(B).  Fully vectorised —
    no loops at JAX level.
    """
    if isinstance(other, SparseDiaImpl):
        return _sparsedia_kron(self, other)
    a, b = self._coerce(other)
    if a is not self:
        return a.kron(b)
    return a.kron(b)

matmul(other)

Matrix multiplication.

  • SparseDIA @ SparseDIA → SparseDIA (O(d₁·d₂·n))
  • SparseDIA @ Dense → Dense (O(d·n²), no densification of self)
  • Others → coerce then delegate
Source code in jaxquantum/core/sparse_dia.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def matmul(self, other: QarrayImpl) -> QarrayImpl:
    """Matrix multiplication.

    * SparseDIA @ SparseDIA → SparseDIA  (O(d₁·d₂·n))
    * SparseDIA @ Dense    → Dense       (O(d·n²), no densification of self)
    * Others               → coerce then delegate
    """
    if isinstance(other, DenseImpl):
        return DenseImpl(_sparsedia_matmul_dense(
            self._offsets, self._diags, other._data
        ))
    if isinstance(other, SparseDiaImpl):
        offsets, diags = _sparsedia_matmul_sparsedia(
            self._offsets, self._diags,
            other._offsets, other._diags,
        )
        return SparseDiaImpl(_offsets=offsets, _diags=diags)
    a, b = self._coerce(other)
    if a is not self:
        return a.matmul(b)
    return a.matmul(b)

mul(scalar)

Scalar multiplication — scales all diagonal values.

Source code in jaxquantum/core/sparse_dia.py
272
273
274
def mul(self, scalar) -> "SparseDiaImpl":
    """Scalar multiplication — scales all diagonal values."""
    return SparseDiaImpl(_offsets=self._offsets, _diags=scalar * self._diags)

neg()

Negation.

Source code in jaxquantum/core/sparse_dia.py
276
277
278
def neg(self) -> "SparseDiaImpl":
    """Negation."""
    return SparseDiaImpl(_offsets=self._offsets, _diags=-self._diags)

powm(n)

Integer matrix power staying SparseDIA via binary exponentiation.

Uses O(log n) SparseDIA @ SparseDIA multiplications rather than densifying. A^0 returns the identity operator.

Parameters:

Name Type Description Default
n int

Non-negative integer exponent.

required

Returns:

Type Description
'SparseDiaImpl'

A SparseDiaImpl equal to this matrix raised to the n-th power.

Raises:

Type Description
ValueError

If n is negative.

Source code in jaxquantum/core/sparse_dia.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def powm(self, n: int) -> "SparseDiaImpl":
    """Integer matrix power staying SparseDIA via binary exponentiation.

    Uses O(log n) SparseDIA @ SparseDIA multiplications rather than
    densifying.  A^0 returns the identity operator.

    Args:
        n: Non-negative integer exponent.

    Returns:
        A ``SparseDiaImpl`` equal to this matrix raised to the *n*-th power.

    Raises:
        ValueError: If *n* is negative.
    """
    if n < 0:
        raise ValueError("powm requires n >= 0")
    if n == 0:
        size = self._diags.shape[-1]
        eye_diags = jnp.ones((*self._diags.shape[:-2], 1, size), dtype=self._diags.dtype)
        return SparseDiaImpl(_offsets=(0,), _diags=eye_diags)
    if n == 1:
        return self
    half = self.powm(n // 2)
    squared = half.matmul(half)  # SparseDIA @ SparseDIA → SparseDIA
    return squared if n % 2 == 0 else self.matmul(squared)

real()

Element-wise real part of stored values.

Source code in jaxquantum/core/sparse_dia.py
435
436
437
438
439
440
def real(self) -> "SparseDiaImpl":
    """Element-wise real part of stored values."""
    return SparseDiaImpl(
        _offsets=self._offsets,
        _diags=jnp.real(self._diags).astype(self._diags.dtype),
    )

shape()

Shape of the represented square matrix (including batch dims).

Source code in jaxquantum/core/sparse_dia.py
253
254
255
256
def shape(self) -> tuple:
    """Shape of the represented square matrix (including batch dims)."""
    n = self._diags.shape[-1]
    return (*self._diags.shape[:-2], n, n)

sub(other)

Element-wise subtraction.

Source code in jaxquantum/core/sparse_dia.py
293
294
295
296
297
298
299
300
def sub(self, other: QarrayImpl) -> QarrayImpl:
    """Element-wise subtraction."""
    if isinstance(other, SparseDiaImpl):
        return _sparsedia_add(self, other, subtract=True)
    a, b = self._coerce(other)
    if a is not self:
        return a.sub(b)
    return a.sub(b)

tidy_up(atol)

Zero diagonal values whose magnitude is below atol.

Source code in jaxquantum/core/sparse_dia.py
352
353
354
355
356
357
358
359
360
361
def tidy_up(self, atol) -> "SparseDiaImpl":
    """Zero diagonal values whose magnitude is below *atol*."""
    diags = self._diags
    real_part = jnp.where(jnp.abs(jnp.real(diags)) < atol, 0.0, jnp.real(diags))
    if jnp.issubdtype(diags.dtype, jnp.complexfloating):
        imag_part = jnp.where(jnp.abs(jnp.imag(diags)) < atol, 0.0, jnp.imag(diags))
        new_diags = (real_part + 1j * imag_part).astype(diags.dtype)
    else:
        new_diags = real_part.astype(diags.dtype)
    return SparseDiaImpl(_offsets=self._offsets, _diags=new_diags)

to_dense()

Convert to a DenseImpl by summing diagonal contributions.

Source code in jaxquantum/core/sparse_dia.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def to_dense(self) -> "DenseImpl":
    """Convert to a ``DenseImpl`` by summing diagonal contributions."""
    n = self._diags.shape[-1]
    batch_shape = self._diags.shape[:-2]
    result = jnp.zeros((*batch_shape, n, n), dtype=self._diags.dtype)
    for i, k in enumerate(self._offsets):
        s = _dia_slice(k)
        length = n - abs(k)
        if length <= 0:
            continue
        vals = self._diags[..., i, s]
        row_idx = jnp.arange(length) + max(-k, 0)
        col_idx = row_idx + k
        result = result.at[..., row_idx, col_idx].set(vals)
    return DenseImpl(result)

to_sparse_bcoo()

Convert to a SparseBCOOImpl (BCOO) via dense.

Source code in jaxquantum/core/sparse_dia.py
383
384
385
def to_sparse_bcoo(self) -> "SparseBCOOImpl":
    """Convert to a ``SparseBCOOImpl`` (BCOO) via dense."""
    return self.to_dense().to_sparse_bcoo()

to_sparse_dia()

Return self (already SparseDIA).

Source code in jaxquantum/core/sparse_dia.py
387
388
389
def to_sparse_dia(self) -> "SparseDiaImpl":
    """Return self (already SparseDIA)."""
    return self

trace()

Compute trace directly from the main diagonal (offset 0).

Returns:

Type Description

Scalar trace (sum of main diagonal values).

Source code in jaxquantum/core/sparse_dia.py
420
421
422
423
424
425
426
427
428
429
def trace(self):
    """Compute trace directly from the main diagonal (offset 0).

    Returns:
        Scalar trace (sum of main diagonal values).
    """
    if 0 in self._offsets:
        i = self._offsets.index(0)
        return jnp.sum(self._diags[..., i, :], axis=-1)
    return jnp.zeros(self._diags.shape[:-2], dtype=self._diags.dtype)

Ec_to_inv_pF(Ec)

GHz -> 1/picoFarad

Source code in jaxquantum/utils/units.py
81
82
83
84
85
86
87
88
def Ec_to_inv_pF(Ec):
    """
    GHz -> 1/picoFarad
    """
    joule = GHz_to_joule(Ec)
    Gjoule = joule / 1e9
    inv_nFarad = Gjoule / ((constants.e) ** 2 / (2))
    return inv_nFarad * 1e-3

as_series(*arrs)

Return arguments as a list of 1-d arrays.

The returned list contains array(s) of dtype double, complex double, or object. A 1-d argument of shape (N,) is parsed into N arrays of size one; a 2-d argument of shape (M,N) is parsed into M arrays of size N (i.e., is "parsed by row"); and a higher dimensional array raises a Value Error if it is not first reshaped into either a 1-d or 2-d array.

Parameters

arrs : array_like 1- or 2-d array_like trim : boolean, optional When True, trailing zeros are removed from the inputs. When False, the inputs are passed through intact.

Returns

a1, a2,... : 1-D arrays A copy of the input data as 1-d arrays.

Source code in jaxquantum/utils/hermgauss.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def as_series(*arrs):
    """Return arguments as a list of 1-d arrays.

    The returned list contains array(s) of dtype double, complex double, or
    object.  A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of
    size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays
    of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array
    raises a Value Error if it is not first reshaped into either a 1-d or 2-d
    array.

    Parameters
    ----------
    arrs : array_like
        1- or 2-d array_like
    trim : boolean, optional
        When True, trailing zeros are removed from the inputs.
        When False, the inputs are passed through intact.

    Returns
    -------
    a1, a2,... : 1-D arrays
        A copy of the input data as 1-d arrays.

    """
    arrays = tuple(jnp.array(a, ndmin=1) for a in arrs)
    arrays = promote_dtypes_inexact(*arrays)
    if len(arrays) == 1:
        return arrays[0]
    return tuple(arrays)

basis(N, k, implementation=QarrayImplType.DENSE)

Creates a |k> (i.e. fock state) ket in a specified Hilbert Space.

Parameters:

Name Type Description Default
N int

Hilbert space dimension

required
k int

fock number

required
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description

Fock State |k>

Source code in jaxquantum/core/operators.py
261
262
263
264
265
266
267
268
269
270
271
272
def basis(N: int, k: int, implementation: QarrayImplType = QarrayImplType.DENSE):
    """Creates a |k> (i.e. fock state) ket in a specified Hilbert Space.

    Args:
        N: Hilbert space dimension
        k: fock number
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        Fock State |k>
    """
    return Qarray.create(one_hot(k, N).reshape(N, 1), implementation=implementation)

basis_like(A, ks)

Creates a |k> (i.e. fock state) ket with the same space dims as A.

Parameters:

Name Type Description Default
A Qarray

state or operator.

required
k

fock number.

required

Returns:

Type Description
Qarray

Fock State |k> with the same space dims as A.

Source code in jaxquantum/core/operators.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def basis_like(A: Qarray, ks: List[int]) -> Qarray:
    """Creates a |k> (i.e. fock state) ket with the same space dims as A.

    Args:
        A: state or operator.
        k: fock number.

    Returns:
        Fock State |k> with the same space dims as A.
    """
    space_dims = A.space_dims
    assert len(space_dims) == len(ks), "len(ks) must be equal to len(space_dims)"

    kets = []
    for j, k in enumerate(ks):
        kets.append(basis(space_dims[j], k))
    return tensor(*kets)

cf_wigner(psi, xvec, yvec)

Wigner function for a state vector or density matrix at points xvec + i * yvec.

Parameters

Qarray

A state vector or density matrix.

array_like

x-coordinates at which to calculate the Wigner function.

array_like

y-coordinates at which to calculate the Wigner function.

Returns

array

Values representing the Wigner function calculated over the specified range [xvec,yvec].

Source code in jaxquantum/core/cfunctions.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def cf_wigner(psi, xvec, yvec):
    """Wigner function for a state vector or density matrix at points
    `xvec + i * yvec`.

    Parameters
    ----------

    state : Qarray
        A state vector or density matrix.

    xvec : array_like
        x-coordinates at which to calculate the Wigner function.

    yvec : array_like
        y-coordinates at which to calculate the Wigner function.


    Returns
    -------

    W : array
        Values representing the Wigner function calculated over the specified
        range [xvec,yvec].


    """
    N = psi.dims[0][0]
    x, y = jnp.meshgrid(xvec, yvec)
    alpha = x + 1.0j * y
    displacement = jqt.displace(N, alpha)

    vmapped_overlap = [vmap(vmap(jqt.overlap, in_axes=(None, 0)), in_axes=(
        None, 0))]
    for _ in psi.bdims:
        vmapped_overlap.append(vmap(vmapped_overlap[-1], in_axes=(0, None)))

    cf = vmapped_overlap[-1](psi, displacement)
    return cf

coherent(N, α)

Coherent state.

Parameters:

Name Type Description Default
N int

Hilbert Space Size.

required
α complex

coherent state amplitude.

required
Return

Coherent state |α⟩.

Source code in jaxquantum/core/operators.py
288
289
290
291
292
293
294
295
296
297
298
def coherent(N: int, α: complex) -> Qarray:
    """Coherent state.

    Args:
        N: Hilbert Space Size.
        α: coherent state amplitude.

    Return:
        Coherent state |α⟩.
    """
    return displace(N, α) @ basis(N, 0)

collapse(qarr, mode='sum')

Collapse the batch dimensions of qarr.

Parameters:

Name Type Description Default
qarr Qarray

Quantum array with optional batch dimensions.

required
mode

Collapse strategy. Only "sum" is currently supported.

'sum'

Returns:

Type Description
Qarray

A non-batched Qarray obtained by summing over all batch axes.

Source code in jaxquantum/core/qarray.py
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
def collapse(qarr: Qarray, mode="sum") -> Qarray:
    """Collapse the batch dimensions of *qarr*.

    Args:
        qarr: Quantum array with optional batch dimensions.
        mode: Collapse strategy.  Only ``"sum"`` is currently supported.

    Returns:
        A non-batched ``Qarray`` obtained by summing over all batch axes.
    """

    if mode == "sum":
        if len(qarr.bdims) == 0:
            return qarr

        batch_axes = list(range(len(qarr.bdims)))

        # Preserve implementation type
        implementation = qarr.impl_type
        return Qarray.create(jnp.sum(qarr.data, axis=batch_axes), dims=qarr.dims, implementation=implementation)

comb(N, k)

NCk

TODO: replace with jsp.special.comb once issue is closed:

https://github.com/google/jax/issues/9709

Parameters:

Name Type Description Default
N

total items

required
k

of items to choose

required

Returns:

Name Type Description
NCk

N choose k

Source code in jaxquantum/utils/utils.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def comb(N, k):
    """
    NCk

    #TODO: replace with jsp.special.comb once issue is closed:
    https://github.com/google/jax/issues/9709

    Args:
        N: total items
        k: # of items to choose

    Returns:
        NCk: N choose k
    """
    one = 1
    N_plus_1 = lax.add(N, one)
    k_plus_1 = lax.add(k, one)
    return lax.exp(
        lax.sub(
            gammaln(N_plus_1), lax.add(gammaln(k_plus_1), gammaln(lax.sub(N_plus_1, k)))
        )
    )

concatenate(qarr_list, axis=0)

Concatenate a list of Qarrays along a specified axis.

Parameters:

Name Type Description Default
qarr_list List[Qarray]

List of Qarrays to concatenate.

required
axis int

Axis along which to concatenate. Default is 0.

0

Returns:

Type Description
Qarray

Concatenated Qarray.

Source code in jaxquantum/core/qarray.py
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
def concatenate(qarr_list: List[Qarray], axis: int = 0) -> Qarray:
    """Concatenate a list of Qarrays along a specified axis.

    Args:
        qarr_list: List of Qarrays to concatenate.
        axis: Axis along which to concatenate. Default is 0.

    Returns:
        Concatenated Qarray.
    """

    non_empty_qarr_list = [qarr for qarr in qarr_list if len(qarr.data) != 0]

    if len(non_empty_qarr_list) == 0:
        return Qarray.from_list([])

    concatenated_data = jnp.concatenate(
        [qarr.data for qarr in non_empty_qarr_list], axis=axis
    )

    dims = non_empty_qarr_list[0].dims
    return Qarray.create(concatenated_data, dims=dims)

cosm(qarr)

Matrix cosine of a Qarray.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array (converted to dense internally).

required

Returns:

Type Description
Qarray

A dense Qarray containing the matrix cosine.

Source code in jaxquantum/core/qarray.py
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
def cosm(qarr: Qarray) -> Qarray:
    """Matrix cosine of a ``Qarray``.

    Args:
        qarr: Input quantum array (converted to dense internally).

    Returns:
        A dense ``Qarray`` containing the matrix cosine.
    """
    dims = qarr.dims
    # Convert to dense for cosm
    dense_data = qarr.to_dense().data
    data = cosm_data(dense_data)
    return Qarray.create(data, dims=dims)

cosm_data(data, **kwargs)

Matrix cosine of a raw array.

Parameters:

Name Type Description Default
data Array

Dense matrix array.

required
**kwargs

Unused; kept for API consistency.

{}

Returns:

Type Description
Array

The matrix cosine computed as (expm(i*A) + expm(-i*A)) / 2.

Source code in jaxquantum/core/qarray.py
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
def cosm_data(data: Array, **kwargs) -> Array:
    """Matrix cosine of a raw array.

    Args:
        data: Dense matrix array.
        **kwargs: Unused; kept for API consistency.

    Returns:
        The matrix cosine computed as ``(expm(i*A) + expm(-i*A)) / 2``.
    """
    return (expm_data(1j * data) + expm_data(-1j * data)) / 2

create(N, implementation=QarrayImplType.DENSE)

creation operator

Parameters:

Name Type Description Default
N

Hilbert space size

required
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description
Qarray

creation operator in Hilber Space of size N

Source code in jaxquantum/core/operators.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def create(N, implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """creation operator

    Args:
        N: Hilbert space size
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        creation operator in Hilber Space of size N
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        # Single subdiagonal at offset -1; Convention A: 1 trailing zero.
        diags = jnp.zeros((1, N), dtype=jnp.float64)
        diags = diags.at[0, :N - 1].set(jnp.sqrt(jnp.arange(1, N, dtype=jnp.float64)))
        return _make_sparsedia(offsets=(-1,), diags=diags)
    return Qarray.create(jnp.diag(jnp.sqrt(jnp.arange(1, N)), k=-1), implementation=implementation)

dag(qarr)

Conjugate transpose of qarr.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required

Returns:

Type Description
Qarray

The conjugate transpose with swapped dims.

Source code in jaxquantum/core/qarray.py
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
def dag(qarr: Qarray) -> Qarray:
    """Conjugate transpose of *qarr*.

    Args:
        qarr: Input quantum array.

    Returns:
        The conjugate transpose with swapped ``dims``.
    """
    dims = qarr.dims[::-1]
    new_impl = qarr._impl.dag()
    return Qarray.create(
        new_impl.data,
        dims=dims,
        implementation=new_impl.impl_type,
    )

dag_data(arr)

Conjugate transpose of a raw array, dispatching to the right backend.

Iterates through registered :class:QarrayImpl subclasses and delegates to the first one whose :meth:~QarrayImpl.can_handle_data returns True. Adding a new backend automatically extends this function — no changes required here.

Parameters:

Name Type Description Default
arr

Input array (jnp.ndarray, sparse.BCOO, or any type handled by a registered impl). For 1-D dense arrays only conjugation is applied (no transpose).

required

Returns:

Type Description
Array

Conjugate transpose with the last two axes swapped.

Raises:

Type Description
TypeError

If no registered impl can handle arr.

Source code in jaxquantum/core/qarray.py
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
def dag_data(arr) -> Array:
    """Conjugate transpose of a raw array, dispatching to the right backend.

    Iterates through registered :class:`QarrayImpl` subclasses and delegates
    to the first one whose :meth:`~QarrayImpl.can_handle_data` returns True.
    Adding a new backend automatically extends this function — no changes
    required here.

    Args:
        arr: Input array (``jnp.ndarray``, ``sparse.BCOO``, or any type
            handled by a registered impl).  For 1-D dense arrays only
            conjugation is applied (no transpose).

    Returns:
        Conjugate transpose with the last two axes swapped.

    Raises:
        TypeError: If no registered impl can handle *arr*.
    """
    for impl_class in _IMPL_REGISTRY:
        if impl_class.can_handle_data(arr):
            return impl_class.dag_data(arr)
    raise TypeError(f"dag_data: no registered impl can handle type {type(arr)}")

destroy(N, implementation=QarrayImplType.DENSE)

annihilation operator

Parameters:

Name Type Description Default
N

Hilbert space size

required
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description
Qarray

annilation operator in Hilber Space of size N

Source code in jaxquantum/core/operators.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def destroy(N, implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """annihilation operator

    Args:
        N: Hilbert space size
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        annilation operator in Hilber Space of size N
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        # Single superdiagonal at offset +1; Convention A: 1 leading zero.
        diags = jnp.zeros((1, N), dtype=jnp.float64)
        diags = diags.at[0, 1:].set(jnp.sqrt(jnp.arange(1, N, dtype=jnp.float64)))
        return _make_sparsedia(offsets=(1,), diags=diags)
    return Qarray.create(jnp.diag(jnp.sqrt(jnp.arange(1, N)), k=1), implementation=implementation)

displace(N, α)

Displacement operator

Parameters:

Name Type Description Default
N

Hilbert Space Size

required
α

Phase space displacement

required

Returns:

Type Description
Qarray

Displace operator D(α)

Source code in jaxquantum/core/operators.py
222
223
224
225
226
227
228
229
230
231
232
233
def displace(N, α) -> Qarray:
    """Displacement operator

    Args:
        N: Hilbert Space Size
        α: Phase space displacement

    Returns:
        Displace operator D(α)
    """
    a = destroy(N)
    return (α * a.dag() - jnp.conj(α) * a).expm()

eigenenergies(qarr)

Eigenvalues of a quantum array.

Parameters:

Name Type Description Default
qarr Qarray

Hermitian operator (converted to dense internally).

required

Returns:

Type Description
Array

Sorted eigenvalues as a JAX array.

Source code in jaxquantum/core/qarray.py
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
def eigenenergies(qarr: Qarray) -> Array:
    """Eigenvalues of a quantum array.

    Args:
        qarr: Hermitian operator (converted to dense internally).

    Returns:
        Sorted eigenvalues as a JAX array.
    """
    # Convert to dense for eigenenergies
    dense_qarr = qarr.to_dense()
    evals = jnp.linalg.eigvalsh(dense_qarr.data)
    return evals

eigenstates(qarr)

Eigenstates of a quantum array.

Parameters:

Name Type Description Default
qarr Qarray

Hermitian operator (converted to dense internally).

required

Returns:

Type Description
Qarray

A tuple (eigenvalues, eigenstates_qarray) where eigenvalues are

Qarray

sorted in ascending order.

Source code in jaxquantum/core/qarray.py
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
def eigenstates(qarr: Qarray) -> Qarray:
    """Eigenstates of a quantum array.

    Args:
        qarr: Hermitian operator (converted to dense internally).

    Returns:
        A tuple ``(eigenvalues, eigenstates_qarray)`` where eigenvalues are
        sorted in ascending order.
    """
    # Convert to dense for eigenstates
    dense_qarr = qarr.to_dense()

    evals, evecs = jnp.linalg.eigh(dense_qarr.data)
    idxs_sorted = jnp.argsort(evals, axis=-1)

    dims = ket_from_op_dims(qarr.dims)

    evals = jnp.take_along_axis(evals, idxs_sorted, axis=-1)
    evecs = jnp.take_along_axis(evecs, idxs_sorted[..., None, :], axis=-1)

    # numpy returns [batch, :, i] as the i-th eigenvector
    # we want [batch, i, :] as the i-th eigenvector
    evecs = jnp.swapaxes(evecs, -2, -1)

    evecs = Qarray.create(
        evecs,
        dims=dims,
        bdims=evecs.shape[:-1],
    )

    return evals, evecs

expm(qarr, **kwargs)

Matrix exponential of a Qarray.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array (converted to dense internally).

required
**kwargs

Forwarded to jsp.linalg.expm.

{}

Returns:

Type Description
Qarray

A dense Qarray containing the matrix exponential.

Source code in jaxquantum/core/qarray.py
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
def expm(qarr: Qarray, **kwargs) -> Qarray:
    """Matrix exponential of a ``Qarray``.

    Args:
        qarr: Input quantum array (converted to dense internally).
        **kwargs: Forwarded to ``jsp.linalg.expm``.

    Returns:
        A dense ``Qarray`` containing the matrix exponential.
    """
    dims = qarr.dims
    # Convert to dense for expm
    dense_data = qarr.to_dense().data
    data = expm_data(dense_data, **kwargs)
    return Qarray.create(data, dims=dims)

expm_data(data, **kwargs)

Matrix exponential of a raw array.

Parameters:

Name Type Description Default
data Array

Dense matrix array.

required
**kwargs

Forwarded to jsp.linalg.expm.

{}

Returns:

Type Description
Array

The matrix exponential.

Source code in jaxquantum/core/qarray.py
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
def expm_data(data: Array, **kwargs) -> Array:
    """Matrix exponential of a raw array.

    Args:
        data: Dense matrix array.
        **kwargs: Forwarded to ``jsp.linalg.expm``.

    Returns:
        The matrix exponential.
    """
    return jsp.linalg.expm(data, **kwargs)

extract_dims(arr, dims=None)

Extract dims from a JAX array or Qarray.

Parameters:

Name Type Description Default
arr Array

JAX array or Qarray.

required
dims Optional[Union[DIMS_TYPE, List[int]]]

Qarray dims.

None

Returns:

Type Description

Qarray dims.

Source code in jaxquantum/core/conversions.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def extract_dims(arr: Array, dims: Optional[Union[DIMS_TYPE, List[int]]] = None):
    """Extract dims from a JAX array or Qarray.

    Args:
        arr: JAX array or Qarray.
        dims: Qarray dims.

    Returns:
        Qarray dims.
    """
    if isinstance(dims[0], Number):
        is_op = arr.shape[-2] == arr.shape[-1]
        if is_op:
            dims = [dims, dims]
        else:
            dims = [dims, [1] * len(dims)]  # defaults to ket
    return dims

fidelity(rho, sigma, force_positivity=False)

Fidelity between two states.

Parameters:

Name Type Description Default
rho Qarray

state.

required
sigma Qarray

state.

required
force_positivity bool

force the states to be positive semidefinite

False

Returns:

Type Description
ndarray

Fidelity between rho and sigma.

Source code in jaxquantum/core/measurements.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def fidelity(rho: Qarray, sigma: Qarray, force_positivity: bool=False) -> (
        jnp.ndarray):
    """Fidelity between two states.

    Args:
        rho: state.
        sigma: state.
        force_positivity: force the states to be positive semidefinite

    Returns:
        Fidelity between rho and sigma.
    """
    rho = rho.to_dm()
    sigma = sigma.to_dm()

    sqrt_rho = powm(rho, 0.5, clip_eigvals=force_positivity)

    return jnp.real(((powm(sqrt_rho @ sigma @ sqrt_rho, 0.5,
                           clip_eigvals=force_positivity)).tr())
                    ** 2)

hadamard(implementation=QarrayImplType.DENSE)

H

Returns:

Name Type Description
H Qarray

Hadamard gate

Source code in jaxquantum/core/operators.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def hadamard(implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """H

    Returns:
        H: Hadamard gate
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        s = 1.0 / jnp.sqrt(2.0)
        # offset -1: valid at [0]   → diag[0]=A[1,0]=s, diag[1]=0 (trailing zero)
        # offset  0: valid at [0:2] → diag[0]=A[0,0]=s, diag[1]=A[1,1]=-s
        # offset +1: valid at [1]   → diag[0]=0 (leading zero), diag[1]=A[0,1]=s
        diags = jnp.array([[s, 0.0], [s, -s], [0.0, s]])
        return _make_sparsedia(offsets=(-1, 0, 1), diags=diags)
    return Qarray.create(jnp.array([[1, 1], [1, -1]]) / jnp.sqrt(2), implementation=implementation)

hermcompanion(c)

Return the scaled companion matrix of c.

The basis polynomials are scaled so that the companion matrix is symmetric when c is an Hermite basis polynomial. This provides better eigenvalue estimates than the unscaled case and for basis polynomials the eigenvalues are guaranteed to be real if jax.numpy.linalg.eigvalsh is used to obtain them.

Parameters

c : array_like 1-D array of Hermite series coefficients ordered from low to high degree.

Returns

mat : ndarray Scaled companion matrix of dimensions (deg, deg).

Source code in jaxquantum/utils/hermgauss.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@jit
def hermcompanion(c):
    """Return the scaled companion matrix of c.

    The basis polynomials are scaled so that the companion matrix is
    symmetric when `c` is an Hermite basis polynomial. This provides
    better eigenvalue estimates than the unscaled case and for basis
    polynomials the eigenvalues are guaranteed to be real if
    `jax.numpy.linalg.eigvalsh` is used to obtain them.

    Parameters
    ----------
    c : array_like
        1-D array of Hermite series coefficients ordered from low to high
        degree.

    Returns
    -------
    mat : ndarray
        Scaled companion matrix of dimensions (deg, deg).

    """
    c = as_series(c)
    if len(c) < 2:
        raise ValueError("Series must have maximum degree of at least 1.")
    if len(c) == 2:
        return jnp.array([[-0.5 * c[0] / c[1]]])

    n = len(c) - 1
    mat = jnp.zeros((n, n), dtype=c.dtype)
    scl = jnp.hstack((1.0, 1.0 / jnp.sqrt(2.0 * jnp.arange(n - 1, 0, -1))))
    scl = jnp.cumprod(scl)[::-1]
    shp = mat.shape
    mat = mat.flatten()
    mat = mat.at[1 :: n + 1].set(jnp.sqrt(0.5 * jnp.arange(1, n)))
    mat = mat.at[n :: n + 1].set(jnp.sqrt(0.5 * jnp.arange(1, n)))
    mat = mat.reshape(shp)
    mat = mat.at[:, -1].add(-scl * c[:-1] / (2.0 * c[-1]))
    return mat

identity(*args, implementation=QarrayImplType.DENSE, **kwargs)

Identity matrix.

Parameters:

Name Type Description Default
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description
Qarray

Identity matrix.

Source code in jaxquantum/core/operators.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def identity(*args, implementation: QarrayImplType = QarrayImplType.DENSE, **kwargs) -> Qarray:
    """Identity matrix.

    Args:
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        Identity matrix.
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        # jnp.eye(*args) is typically eye(N) or eye(N, N); extract N from args.
        n = args[0] if args else kwargs.get("N", kwargs.get("n", None))
        if n is not None and (len(args) <= 1) and not kwargs:
            diags = jnp.ones((1, int(n)), dtype=jnp.float64)
            return _make_sparsedia(offsets=(0,), diags=diags)
    return Qarray.create(jnp.eye(*args, **kwargs), implementation=implementation)

identity_like(A, implementation=QarrayImplType.DENSE)

Identity matrix with the same shape as A.

Parameters:

Name Type Description Default
A

Matrix.

required
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description
Qarray

Identity matrix with the same shape as A.

Source code in jaxquantum/core/operators.py
207
208
209
210
211
212
213
214
215
216
217
218
219
def identity_like(A, implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """Identity matrix with the same shape as A.

    Args:
        A: Matrix.
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        Identity matrix with the same shape as A.
    """
    space_dims = A.space_dims
    total_dim = prod(space_dims)
    return Qarray.create(jnp.eye(total_dim, total_dim), dims=[space_dims, space_dims], implementation=implementation)

inductance_to_inductive_energy(L)

Convert inductance to inductive energy E_L.

Parameters:

Name Type Description Default
L float

Inductance in nH.

required

Returns:

Name Type Description
float

Inductive energy in GHz.

Source code in jaxquantum/utils/units.py
57
58
59
60
61
62
63
64
65
66
67
68
69
def inductance_to_inductive_energy(L):
    """Convert inductance to inductive energy E_L.

    Args:
        L (float): Inductance in nH.

    Returns:
        float: Inductive energy in GHz.
    """

    inv_L = 1e9 / L
    El_joules = inv_L * (FLUX_QUANTUM**2) / (2 * np.pi) ** 2
    return joule_to_GHz(El_joules)

inductive_energy_to_inductance(El)

Convert inductive energy E_L to inductance.

Parameters:

Name Type Description Default
El float

inductive energy in GHz.

required

Returns:

Name Type Description
float

Inductance in nH.

Source code in jaxquantum/utils/units.py
44
45
46
47
48
49
50
51
52
53
54
55
def inductive_energy_to_inductance(El):
    """Convert inductive energy E_L to inductance.

    Args:
        El (float): inductive energy in GHz.

    Returns:
        float: Inductance in nH.
    """

    inv_L = GHz_to_joule(El) * (2 * np.pi) ** 2 / (FLUX_QUANTUM**2)
    return 1e9 / inv_L

inv_pF_to_Ec(inv_pfarad)

1/picoFarad -> GHz

Source code in jaxquantum/utils/units.py
72
73
74
75
76
77
78
def inv_pF_to_Ec(inv_pfarad):
    """
    1/picoFarad -> GHz
    """
    inv_nFarad = inv_pfarad * 1e3
    Gjoule = (constants.e) ** 2 / (2) * inv_nFarad
    return joule_to_GHz(Gjoule * 1e9)

is_dm_data(data)

Check whether data has the shape of a density matrix (square matrix).

Parameters:

Name Type Description Default
data Array

Array to check.

required

Returns:

Type Description
bool

True if the last two dimensions are equal.

Source code in jaxquantum/core/qarray.py
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
def is_dm_data(data: Array) -> bool:
    """Check whether *data* has the shape of a density matrix (square matrix).

    Args:
        data: Array to check.

    Returns:
        True if the last two dimensions are equal.
    """
    return data.shape[-2] == data.shape[-1]

jnp2jqt(arr, dims=None)

JAX array -> QuTiP state.

Parameters:

Name Type Description Default
jnp_obj

JAX array.

required
dims Optional[Union[DIMS_TYPE, List[int]]]

Qarray dims.

None

Returns:

Type Description

QuTiP state.

Source code in jaxquantum/core/conversions.py
79
80
81
82
83
84
85
86
87
88
89
90
def jnp2jqt(arr: Array, dims: Optional[Union[DIMS_TYPE, List[int]]] = None):
    """JAX array -> QuTiP state.

    Args:
        jnp_obj: JAX array.
        dims: Qarray dims.

    Returns:
        QuTiP state.
    """
    dims = extract_dims(arr, dims) if dims is not None else None
    return Qarray.create(arr, dims=dims)

jqt2qt(jqt_obj)

Qarray -> QuTiP state.

Parameters:

Name Type Description Default
jqt_obj

Qarray.

required
dims

QuTiP dims.

required

Returns:

Type Description

QuTiP state.

Source code in jaxquantum/core/conversions.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def jqt2qt(jqt_obj):
    """Qarray -> QuTiP state.

    Args:
        jqt_obj: Qarray.
        dims: QuTiP dims.

    Returns:
        QuTiP state.
    """
    if isinstance(jqt_obj, Qobj) or jqt_obj is None:
        return jqt_obj

    if jqt_obj.is_batched:
        res = []
        for i in range(len(jqt_obj)):
            res.append(jqt2qt(jqt_obj[i]))
        return res

    dims = [list(jqt_obj.dims[0]), list(jqt_obj.dims[1])]
    return Qobj(np.array(jqt_obj.data), dims=dims)

keep_only_diag_elements(qarr)

Zero out all off-diagonal elements of qarr.

For sparse Qarray objects the off-diagonal stored values are zeroed in-place on the BCOO structure — no densification.

Parameters:

Name Type Description Default
qarr Qarray

Non-batched input quantum array.

required

Returns:

Type Description
Qarray

A Qarray with only diagonal entries non-zero.

Raises:

Type Description
ValueError

If qarr has batch dimensions.

Source code in jaxquantum/core/qarray.py
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
def keep_only_diag_elements(qarr: Qarray) -> Qarray:
    """Zero out all off-diagonal elements of *qarr*.

    For sparse ``Qarray`` objects the off-diagonal stored values are zeroed
    in-place on the BCOO structure — no densification.

    Args:
        qarr: Non-batched input quantum array.

    Returns:
        A ``Qarray`` with only diagonal entries non-zero.

    Raises:
        ValueError: If *qarr* has batch dimensions.
    """
    if len(qarr.bdims) > 0:
        raise ValueError("Cannot keep only diagonal elements of a batched Qarray.")

    dims = qarr.dims
    if qarr.is_sparse_bcoo:
        new_impl = qarr._impl.keep_only_diag()
        return Qarray.create(new_impl.data, dims=dims, implementation=QarrayImplType.SPARSE_BCOO)
    if qarr.is_sparse_dia:
        from jaxquantum.core.sparse_dia import SparseDiaImpl
        impl = qarr._impl
        n = impl._diags.shape[-1]
        if 0 in impl._offsets:
            i = impl._offsets.index(0)
            main_diag = impl._diags[..., i:i + 1, :]
        else:
            main_diag = jnp.zeros((*impl._diags.shape[:-2], 1, n), dtype=impl._diags.dtype)
        new_impl = SparseDiaImpl(_offsets=(0,), _diags=main_diag)
        return Qarray.create(new_impl.get_data(), dims=dims, implementation=QarrayImplType.SPARSE_DIA)
    data = jnp.diag(jnp.diag(qarr.data))
    return Qarray.create(data, dims=dims)

ket2dm(qarr)

Convert a ket to a density matrix via outer product.

Parameters:

Name Type Description Default
qarr Qarray

Ket, bra, or operator. Operators are returned unchanged.

required

Returns:

Type Description
Qarray

Density matrix |ψ⟩⟨ψ|.

Source code in jaxquantum/core/qarray.py
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
def ket2dm(qarr: Qarray) -> Qarray:
    """Convert a ket to a density matrix via outer product.

    Args:
        qarr: Ket, bra, or operator.  Operators are returned unchanged.

    Returns:
        Density matrix ``|ψ⟩⟨ψ|``.
    """
    if qarr.qtype == Qtypes.oper:
        return qarr

    if qarr.qtype == Qtypes.bra:
        qarr = qarr.dag()

    return qarr @ qarr.dag()

mesolve(H, rho0, tlist, saveat_tlist=None, c_ops=None, solver_options=None)

Quantum Master Equation solver.

Parameters:

Name Type Description Default
H Union[Qarray, Callable[[float], Qarray]]

time dependent Hamiltonian function or time-independent Qarray.

required
rho0 Qarray

initial state, must be a density matrix. For statevector evolution, please use sesolve.

required
tlist Array

time list

required
saveat_tlist Optional[Array]

list of times at which to save the state. If -1 or [-1], save only at final time. If None, save at all times in tlist. Default: None.

None
c_ops Optional[Qarray]

qarray list of collapse operators

None
solver_options Optional[SolverOptions]

SolverOptions with solver options

None

Returns:

Type Description
Qarray

list of states

Source code in jaxquantum/core/solvers.py
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
def mesolve(
    H: Union[Qarray, Callable[[float], Qarray]],
    rho0: Qarray,
    tlist: Array,
    saveat_tlist: Optional[Array] = None,
    c_ops: Optional[Qarray] = None,
    solver_options: Optional[SolverOptions] = None,
) -> Qarray:
    """Quantum Master Equation solver.

    Args:
        H: time dependent Hamiltonian function or time-independent Qarray.
        rho0: initial state, must be a density matrix. For statevector evolution, please use sesolve.
        tlist: time list
        saveat_tlist: list of times at which to save the state.
            If -1 or [-1], save only at final time.
            If None, save at all times in tlist. Default: None.
        c_ops: qarray list of collapse operators
        solver_options: SolverOptions with solver options

    Returns:
        list of states
    """

    saveat_tlist = saveat_tlist if saveat_tlist is not None else tlist

    saveat_tlist = jnp.atleast_1d(saveat_tlist)

    c_ops = c_ops if c_ops is not None else Qarray.from_list([])

    # if isinstance(H, Qarray):

    if len(c_ops) == 0 and rho0.qtype != Qtypes.oper:
        logging.warning(
            "Consider using `jqt.sesolve()` instead, as `c_ops` is an empty list and the initial state is not a density matrix."
        )

    ρ0 = rho0.to_dm().to_dense()

    if robust_isscalar(H):
        H = H * identity_like(ρ0)  # treat scalar H as a multiple of the identity

    dims = ρ0.dims
    ρ0 = ρ0.data

    c_ops = c_ops.data

    if isinstance(H, Qarray):
        Ht_data = lambda t: H.data
    else:
        Ht_data = lambda t: H(t).data

    ys = _mesolve_data(Ht_data, ρ0, tlist, saveat_tlist, c_ops,
                       solver_options=solver_options)

    return jnp2jqt(ys, dims=dims)

multi_mode_basis_set(Ns)

Creates a multi-mode basis set.

Parameters:

Name Type Description Default
Ns List[int]

List of Hilbert space dimensions for each mode.

required

Returns:

Type Description
Qarray

Multi-mode basis set.

Source code in jaxquantum/core/operators.py
274
275
276
277
278
279
280
281
282
283
284
285
def multi_mode_basis_set(Ns: List[int]) -> Qarray:
    """Creates a multi-mode basis set.

    Args:
        Ns: List of Hilbert space dimensions for each mode.

    Returns:
        Multi-mode basis set.
    """
    data = jnp.eye(prod(Ns))
    dims = (tuple(Ns), tuple([1 for _ in Ns]))
    return Qarray.create(data, dims=dims, bdims=(prod(Ns),))

n_thermal(frequency, temperature)

Calculate the average thermal photon number for a given frequency and temperature.

Parameters:

Name Type Description Default
frequency float

Frequency in GHz.

required
temperature float

Temperature in Kelvin.

required

Returns:

Name Type Description
float float

Average thermal photon number.

Source code in jaxquantum/utils/units.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def n_thermal(frequency: float, temperature: float) -> float:
    """Calculate the average thermal photon number for a given frequency and temperature.

    Args:
        frequency (float): Frequency in GHz.
        temperature (float): Temperature in Kelvin.

    Returns:
        float: Average thermal photon number.
    """
    k_B = constants.k  # Boltzmann constant in J/K
    h = constants.h  # Planck constant in J·s

    exponent = h * (frequency * 1e9) / (k_B * temperature)
    n_avg = 1 / (np.exp(exponent) - 1)
    return n_avg

norm(qarr)

Compute the norm of a quantum array.

Sparse paths (no densification):

  • ket / bra — L2 norm via :meth:SparseBCOOImpl.l2_norm_batched (handles batch dimensions).
  • operator — trace norm assuming PSD (nuclear norm = tr(rho) for density matrices). This is exact for density matrices; for general non-PSD operators convert to dense first.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required

Returns:

Type Description
float

The norm as a scalar (or batched array of scalars).

Source code in jaxquantum/core/qarray.py
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
def norm(qarr: Qarray) -> float:
    """Compute the norm of a quantum array.

    Sparse paths (no densification):

    * ket / bra — L2 norm via :meth:`SparseBCOOImpl.l2_norm_batched` (handles
      batch dimensions).
    * operator — trace norm assuming PSD (nuclear norm = tr(rho) for density
      matrices).  This is exact for density matrices; for general non-PSD
      operators convert to dense first.

    Args:
        qarr: Input quantum array.

    Returns:
        The norm as a scalar (or batched array of scalars).
    """
    if qarr.qtype in [Qtypes.ket, Qtypes.bra] and qarr.is_sparse_bcoo:
        return qarr._impl.l2_norm_batched(qarr.bdims)

    if qarr.qtype == Qtypes.oper and qarr.is_sparse_bcoo:
        # Nuclear norm = trace for positive-semidefinite (density matrix) operators.
        # jnp.real strips any floating-point imaginary artefact.
        return jnp.real(qarr._impl.trace())

    if qarr.qtype == Qtypes.oper and qarr.is_sparse_dia:
        return jnp.real(qarr._impl.trace())

    qarr = qarr.to_dense()

    qdata = qarr.data
    bdims = qarr.bdims

    if qarr.qtype == Qtypes.oper:
        qdata_dag = qarr.dag().data

        if len(bdims) > 0:
            qdata = qdata.reshape(-1, qdata.shape[-2], qdata.shape[-1])
            qdata_dag = qdata_dag.reshape(-1, qdata_dag.shape[-2], qdata_dag.shape[-1])

            evals, _ = vmap(jnp.linalg.eigh)(qdata @ qdata_dag)
            rho_norm = jnp.sum(jnp.sqrt(jnp.abs(evals)), axis=-1)
            rho_norm = rho_norm.reshape(*bdims)
            return rho_norm
        else:
            evals, _ = jnp.linalg.eigh(qdata @ qdata_dag)
            rho_norm = jnp.sum(jnp.sqrt(jnp.abs(evals)))
            return rho_norm

    elif qarr.qtype in [Qtypes.ket, Qtypes.bra]:
        if len(bdims) > 0:
            qdata = qdata.reshape(-1, qdata.shape[-2], qdata.shape[-1])
            return vmap(jnp.linalg.norm)(qdata).reshape(*bdims)
        else:
            return jnp.linalg.norm(qdata)

num(N, implementation=QarrayImplType.DENSE)

Number operator

Parameters:

Name Type Description Default
N

Hilbert Space size

required
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description
Qarray

number operator in Hilber Space of size N

Source code in jaxquantum/core/operators.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def num(N, implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """Number operator

    Args:
        N: Hilbert Space size
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        number operator in Hilber Space of size N
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        # Main diagonal only; no leading/trailing zeros needed (offset 0).
        diags = jnp.arange(N, dtype=jnp.float64).reshape(1, N)
        return _make_sparsedia(offsets=(0,), diags=diags)
    return Qarray.create(jnp.diag(jnp.arange(N)), implementation=implementation)

overlap(rho, sigma)

Overlap between two states or operators.

Parameters:

Name Type Description Default
rho Qarray

state/operator.

required
sigma Qarray

state/operator.

required

Returns:

Type Description
Array

Overlap between rho and sigma.

Source code in jaxquantum/core/measurements.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def overlap(rho: Qarray, sigma: Qarray) -> Array:
    """Overlap between two states or operators.

    Args:
        rho: state/operator.
        sigma: state/operator.

    Returns:
        Overlap between rho and sigma.
    """

    if rho.is_vec() and sigma.is_vec():
        return jnp.abs(((rho.to_ket().dag() @ sigma.to_ket()).trace())) ** 2
    elif rho.is_vec():
        rho = rho.to_ket()
        res = (rho.dag() @ sigma @ rho).data
        return res.squeeze(-1).squeeze(-1)
    elif sigma.is_vec():
        sigma = sigma.to_ket()
        res = (sigma.dag() @ rho @ sigma).data
        return res.squeeze(-1).squeeze(-1)
    else:
        return (rho.dag() @ sigma).trace()

plot_cf(state, pts_x, pts_y=None, axs=None, contour=True, qp_type=WIGNER, cbar_label='', axis_scale_factor=1, plot_cbar=True, plot_grid=True, x_ticks=None, y_ticks=None, z_ticks=None, subtitles=None, figtitle=None)

Plot characteristic function.

Parameters:

Name Type Description Default
state

state with arbitrary number of batch dimensions, result will

required
pts_x

x points to evaluate quasi-probability distribution at

required
pts_y

y points to evaluate quasi-probability distribution at

None
axs

matplotlib axes to plot on

None
contour

make the plot use contouring

True
qp_type

type of quasi probability distribution ("wigner")

WIGNER
cbar_label

labels for the real and imaginary cbar

''
axis_scale_factor

scale of the axes labels relative

1
plot_cbar

whether to plot cbar

True
x_ticks

tick position for the x-axis

None
y_ticks

tick position for the y-axis

None
z_ticks

tick position for the z-axis

None
subtitles

subtitles for the subplots

None
figtitle

figure title

None

Returns:

Type Description

axis on which the plot was plotted.

Source code in jaxquantum/core/visualization.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def plot_cf(
        state,
        pts_x,
        pts_y=None,
        axs=None,
        contour=True,
        qp_type=WIGNER,
        cbar_label="",
        axis_scale_factor=1,
        plot_cbar=True,
        plot_grid=True,
        x_ticks=None,
        y_ticks=None,
        z_ticks=None,
        subtitles=None,
        figtitle=None,
):
    """Plot characteristic function.


    Args:
        state: state with arbitrary number of batch dimensions, result will
        be flattened to a 2d grid to allow for plotting
        pts_x: x points to evaluate quasi-probability distribution at
        pts_y: y points to evaluate quasi-probability distribution at
        axs: matplotlib axes to plot on
        contour: make the plot use contouring
        qp_type: type of quasi probability distribution ("wigner")
        cbar_label: labels for the real and imaginary cbar
        axis_scale_factor: scale of the axes labels relative
        plot_cbar: whether to plot cbar
        x_ticks: tick position for the x-axis
        y_ticks: tick position for the y-axis
        z_ticks: tick position for the z-axis
        subtitles: subtitles for the subplots
        figtitle: figure title

    Returns:
        axis on which the plot was plotted.
    """
    if pts_y is None:
        pts_y = pts_x
    pts_x = jnp.array(pts_x)
    pts_y = jnp.array(pts_y)

    bdims = state.bdims
    added_baxes = 0

    if subtitles is not None:
        if subtitles.shape != bdims:
            raise ValueError(
                f"labels must have same shape as bdims, "
                f"got shapes {subtitles.shape} and {bdims}"
            )

    if len(bdims) == 0:
        bdims = (1,)
        added_baxes += 1
    if len(bdims) == 1:
        bdims = (1, bdims[0])
        added_baxes += 1

    extra_dims = bdims[2:]
    if extra_dims != ():
        state = state.reshape_bdims(
            bdims[0] * int(jnp.prod(jnp.array(extra_dims))), bdims[1]
        )
        if subtitles is not None:
            subtitles = subtitles.reshape(
                bdims[0] * int(jnp.prod(jnp.array(extra_dims))), bdims[1]
            )
        bdims = state.bdims

    if axs is None:
        _, axs = plt.subplots(
            bdims[0],
            bdims[1]*2,
            figsize=(4 * bdims[1]*2, 3 * bdims[0]),
            dpi=200,
        )


    if qp_type == WIGNER:
        vmin = -1
        vmax = 1
        scale = 1
        cmap = "seismic"
        cbar_label = [r"$\mathcal{Re}(\chi_W(\alpha))$", r"$\mathcal{"
                                                         r"Im}(\chi_W("
                                                         r"\alpha))$"]
        QP = scale * cf_wigner(state, pts_x, pts_y)

    for _ in range(added_baxes):
        QP = jnp.array([QP])
        axs = np.array([axs])
        if subtitles is not None:
            subtitles = np.array([subtitles])

    if added_baxes==2:
        axs = axs[0] # When the input state is zero-dimensional, remove an
                     # axis that is automatically added due to the subcolumns


    pts_x = pts_x * axis_scale_factor
    pts_y = pts_y * axis_scale_factor

    x_ticks = (
        jnp.linspace(jnp.min(pts_x), jnp.max(pts_x),
                     5) if x_ticks is None else x_ticks
    )
    y_ticks = (
        jnp.linspace(jnp.min(pts_y), jnp.max(pts_y),
                     5) if y_ticks is None else y_ticks
    )
    z_ticks = jnp.linspace(vmin, vmax, 11) if z_ticks is None else z_ticks
    print(axs.shape)
    for row in range(bdims[0]):
        for col in range(bdims[1]):
            for subcol in range(2):
                ax = axs[row, 2 * col + subcol]
                if contour:
                    im = ax.contourf(
                        pts_x,
                        pts_y,
                        jnp.real(QP[row, col]) if subcol==0 else jnp.imag(QP[
                                                                           row, col]),
                        cmap=cmap,
                        vmin=vmin,
                        vmax=vmax,
                        levels=np.linspace(vmin, vmax, 101),
                    )
                else:
                    im = ax.pcolormesh(
                        pts_x,
                        pts_y,
                        jnp.real(QP[row, col]) if subcol == 0 else jnp.imag(QP[
                                                                                row, col]),
                        cmap=cmap,
                        vmin=vmin,
                        vmax=vmax,
                    )
                ax.set_xticks(x_ticks)
                ax.set_yticks(y_ticks)
                # ax.axhline(0, linestyle="-", color="black", alpha=0.7)
                # ax.axvline(0, linestyle="-", color="black", alpha=0.7)

                if plot_grid:
                    ax.grid()

                ax.set_aspect("equal", adjustable="box")

                if plot_cbar:
                    cbar = plt.colorbar(
                        im, ax=ax, orientation="vertical",
                        ticks=np.linspace(-1, 1, 11)
                    )
                    cbar.ax.set_title(cbar_label[subcol])
                    cbar.set_ticks(z_ticks)

                ax.set_xlabel(r"Re[$\alpha$]")
                ax.set_ylabel(r"Im[$\alpha$]")
                if subtitles is not None:
                    ax.set_title(subtitles[row, col])

    fig = ax.get_figure()
    fig.tight_layout()
    if figtitle is not None:
        fig.suptitle(figtitle, y=1.04)
    return axs, im

plot_cf_wigner(state, pts_x, pts_y=None, axs=None, contour=True, cbar_label='', axis_scale_factor=1, plot_cbar=True, plot_grid=True, x_ticks=None, y_ticks=None, z_ticks=None, subtitles=None, figtitle=None)

Plot the Wigner characteristic function of the state.

Parameters:

Name Type Description Default
state

state with arbitrary number of batch dimensions, result will

required
pts_x

x points to evaluate quasi-probability distribution at

required
pts_y

y points to evaluate quasi-probability distribution at

None
axs

matplotlib axes to plot on

None
contour

make the plot use contouring

True
cbar_label

label for the cbar

''
axis_scale_factor

scale of the axes labels relative

1
plot_cbar

whether to plot cbar

True
x_ticks

tick position for the x-axis

None
y_ticks

tick position for the y-axis

None
z_ticks

tick position for the z-axis

None
subtitles

subtitles for the subplots

None
figtitle

figure title

None

Returns:

Type Description

axis on which the plot was plotted.

Source code in jaxquantum/core/visualization.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
def plot_cf_wigner(
    state,
    pts_x,
    pts_y=None,
    axs=None,
    contour=True,
    cbar_label="",
    axis_scale_factor=1,
    plot_cbar=True,
    plot_grid=True,
    x_ticks=None,
    y_ticks=None,
    z_ticks=None,
    subtitles=None,
    figtitle=None,
):
    """Plot the Wigner characteristic function of the state.


    Args:
        state: state with arbitrary number of batch dimensions, result will
        be flattened to a 2d grid to allow for plotting
        pts_x: x points to evaluate quasi-probability distribution at
        pts_y: y points to evaluate quasi-probability distribution at
        axs: matplotlib axes to plot on
        contour: make the plot use contouring
        cbar_label: label for the cbar
        axis_scale_factor: scale of the axes labels relative
        plot_cbar: whether to plot cbar
        x_ticks: tick position for the x-axis
        y_ticks: tick position for the y-axis
        z_ticks: tick position for the z-axis
        subtitles: subtitles for the subplots
        figtitle: figure title

    Returns:
        axis on which the plot was plotted.
    """
    return plot_cf(
        state=state,
        pts_x=pts_x,
        pts_y=pts_y,
        axs=axs,
        contour=contour,
        qp_type=WIGNER,
        cbar_label=cbar_label,
        axis_scale_factor=axis_scale_factor,
        plot_cbar=plot_cbar,
        plot_grid=plot_grid,
        x_ticks=x_ticks,
        y_ticks=y_ticks,
        z_ticks=z_ticks,
        subtitles=subtitles,
        figtitle=figtitle,
    )

plot_qfunc(state, pts_x, pts_y=None, g=2, axs=None, contour=True, cbar_label='', axis_scale_factor=1, plot_cbar=True, x_ticks=None, y_ticks=None, z_ticks=None, subtitles=None, figtitle=None)

Plot the husimi function of the state.

Parameters:

Name Type Description Default
state

state with arbitrary number of batch dimensions, result will

required
pts_x

x points to evaluate quasi-probability distribution at

required
pts_y

y points to evaluate quasi-probability distribution at

None
g

float, default: 2

required
related to the value of

math:\hbar in the commutation relation

required

math:[x,\,y] = i\hbar via :math:\hbar=2/g^2.

required
axs

matplotlib axes to plot on

None
contour

make the plot use contouring

True
cbar_label

label for the cbar

''
axis_scale_factor

scale of the axes labels relative

1
plot_cbar

whether to plot cbar

True
x_ticks

tick position for the x-axis

None
y_ticks

tick position for the y-axis

None
z_ticks

tick position for the z-axis

None
subtitles

subtitles for the subplots

None
figtitle

figure title

None

Returns:

Type Description

axis on which the plot was plotted.

Source code in jaxquantum/core/visualization.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def plot_qfunc(
    state,
    pts_x,
    pts_y=None,
    g=2,
    axs=None,
    contour=True,
    cbar_label="",
    axis_scale_factor=1,
    plot_cbar=True,
    x_ticks=None,
    y_ticks=None,
    z_ticks=None,
    subtitles=None,
    figtitle=None,
):
    """Plot the husimi function of the state.


    Args:
        state: state with arbitrary number of batch dimensions, result will
        be flattened to a 2d grid to allow for plotting
        pts_x: x points to evaluate quasi-probability distribution at
        pts_y: y points to evaluate quasi-probability distribution at
        g : float, default: 2
        Scaling factor for ``a = 0.5 * g * (x + iy)``.  The value of `g` is
        related to the value of :math:`\\hbar` in the commutation relation
        :math:`[x,\,y] = i\\hbar` via :math:`\\hbar=2/g^2`.
        axs: matplotlib axes to plot on
        contour: make the plot use contouring
        cbar_label: label for the cbar
        axis_scale_factor: scale of the axes labels relative
        plot_cbar: whether to plot cbar
        x_ticks: tick position for the x-axis
        y_ticks: tick position for the y-axis
        z_ticks: tick position for the z-axis
        subtitles: subtitles for the subplots
        figtitle: figure title

    Returns:
        axis on which the plot was plotted.
    """
    return plot_qp(
        state=state,
        pts_x=pts_x,
        pts_y=pts_y,
        g=g,
        axs=axs,
        contour=contour,
        qp_type=HUSIMI,
        cbar_label=cbar_label,
        axis_scale_factor=axis_scale_factor,
        plot_cbar=plot_cbar,
        x_ticks=x_ticks,
        y_ticks=y_ticks,
        z_ticks=z_ticks,
        subtitles=subtitles,
        figtitle=figtitle,
    )

plot_qp(state, pts_x, pts_y=None, g=2, axs=None, contour=True, qp_type=WIGNER, cbar_label='', axis_scale_factor=1, plot_cbar=True, x_ticks=None, y_ticks=None, z_ticks=None, subtitles=None, figtitle=None)

Plot quasi-probability distribution.

Parameters:

Name Type Description Default
state

state with arbitrary number of batch dimensions, result will

required
pts_x

x points to evaluate quasi-probability distribution at

required
pts_y

y points to evaluate quasi-probability distribution at

None
g

float, default: 2

required
related to the value of

math:\hbar in the commutation relation

required

math:[x,\,y] = i\hbar via :math:\hbar=2/g^2.

required
axs

matplotlib axes to plot on

None
contour

make the plot use contouring

True
qp_type

type of quasi probability distribution ("wigner", "qfunc")

WIGNER
cbar_label

label for the cbar

''
axis_scale_factor

scale of the axes labels relative

1
plot_cbar

whether to plot cbar

True
x_ticks

tick position for the x-axis

None
y_ticks

tick position for the y-axis

None
z_ticks

tick position for the z-axis

None
subtitles

subtitles for the subplots

None
figtitle

figure title

None

Returns:

Type Description

axis on which the plot was plotted.

Source code in jaxquantum/core/visualization.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
def plot_qp(
    state,
    pts_x,
    pts_y=None,
    g=2,
    axs=None,
    contour=True,
    qp_type=WIGNER,
    cbar_label="",
    axis_scale_factor=1,
    plot_cbar=True,
    x_ticks=None,
    y_ticks=None,
    z_ticks=None,
    subtitles=None,
    figtitle=None,
):
    """Plot quasi-probability distribution.


    Args:
        state: state with arbitrary number of batch dimensions, result will
        be flattened to a 2d grid to allow for plotting
        pts_x: x points to evaluate quasi-probability distribution at
        pts_y: y points to evaluate quasi-probability distribution at
        g : float, default: 2
        Scaling factor for ``a = 0.5 * g * (x + iy)``.  The value of `g` is
        related to the value of :math:`\\hbar` in the commutation relation
        :math:`[x,\,y] = i\\hbar` via :math:`\\hbar=2/g^2`.
        axs: matplotlib axes to plot on
        contour: make the plot use contouring
        qp_type: type of quasi probability distribution ("wigner", "qfunc")
        cbar_label: label for the cbar
        axis_scale_factor: scale of the axes labels relative
        plot_cbar: whether to plot cbar
        x_ticks: tick position for the x-axis
        y_ticks: tick position for the y-axis
        z_ticks: tick position for the z-axis
        subtitles: subtitles for the subplots
        figtitle: figure title

    Returns:
        axis on which the plot was plotted.
    """
    if pts_y is None:
        pts_y = pts_x
    pts_x = jnp.array(pts_x)
    pts_y = jnp.array(pts_y)

    if len(state.bdims)==1 and state.bdims[0]==1:
        state = state[0]


    bdims = state.bdims
    added_baxes = 0

    if subtitles is not None:
        if subtitles.shape != bdims:
            raise ValueError(
                f"labels must have same shape as bdims, "
                f"got shapes {subtitles.shape} and {bdims}"
            )

    if len(bdims) == 0:
        bdims = (1,)
        added_baxes += 1
    if len(bdims) == 1:
        bdims = (1, bdims[0])
        added_baxes += 1

    extra_dims = bdims[2:]
    if extra_dims != ():
        state = state.reshape_bdims(
            bdims[0] * int(jnp.prod(jnp.array(extra_dims))), bdims[1]
        )
        if subtitles is not None:
            subtitles = subtitles.reshape(
                bdims[0] * int(jnp.prod(jnp.array(extra_dims))), bdims[1]
            )
        bdims = state.bdims

    if axs is None:
        _, axs = plt.subplots(
            bdims[0],
            bdims[1],
            figsize=(4 * bdims[1], 3 * bdims[0]),
            dpi=200,
        )

    if qp_type == WIGNER:
        vmin = -1
        vmax = 1
        scale = np.pi / 2
        cmap = "seismic"
        cbar_label = r"$\mathcal{W}(\alpha)$"
        QP = scale * wigner(state, pts_x, pts_y, g=g)

    elif qp_type == HUSIMI:
        vmin = 0
        vmax = 1
        scale = np.pi
        cmap = "jet"
        cbar_label = r"$\mathcal{Q}(\alpha)$"
        QP = scale * qfunc(state, pts_x, pts_y, g=g)



    for _ in range(added_baxes):
        QP = jnp.array([QP])
        axs = np.array([axs])
        if subtitles is not None:
            subtitles = np.array([subtitles])




    pts_x = pts_x * axis_scale_factor
    pts_y = pts_y * axis_scale_factor

    x_ticks = (
        jnp.linspace(jnp.min(pts_x), jnp.max(pts_x), 5) if x_ticks is None else x_ticks
    )
    y_ticks = (
        jnp.linspace(jnp.min(pts_y), jnp.max(pts_y), 5) if y_ticks is None else y_ticks
    )
    z_ticks = jnp.linspace(vmin, vmax, 3) if z_ticks is None else z_ticks

    for row in range(bdims[0]):
        for col in range(bdims[1]):
            ax = axs[row, col]
            if contour:
                im = ax.contourf(
                    pts_x,
                    pts_y,
                    QP[row, col],
                    cmap=cmap,
                    vmin=vmin,
                    vmax=vmax,
                    levels=np.linspace(vmin, vmax, 101),
                )
            else:
                im = ax.pcolormesh(
                    pts_x,
                    pts_y,
                    QP[row, col],
                    cmap=cmap,
                    vmin=vmin,
                    vmax=vmax,
                )
            ax.set_xticks(x_ticks)
            ax.set_yticks(y_ticks)
            ax.axhline(0, linestyle="-", color="black", alpha=0.7)
            ax.axvline(0, linestyle="-", color="black", alpha=0.7)
            ax.grid()
            ax.set_aspect("equal", adjustable="box")

            if plot_cbar:
                cbar = plt.colorbar(
                    im, ax=ax, orientation="vertical", ticks=np.linspace(-1, 1, 11)
                )
                cbar.ax.set_title(cbar_label)
                cbar.set_ticks(z_ticks)

            ax.set_xlabel(r"Re[$\alpha$]")
            ax.set_ylabel(r"Im[$\alpha$]")
            if subtitles is not None:
                ax.set_title(subtitles[row, col])

    fig = ax.get_figure()
    fig.tight_layout()
    if figtitle is not None:
        fig.suptitle(figtitle, y=1.04)
    return axs, im

plot_wigner(state, pts_x, pts_y=None, g=2, axs=None, contour=True, cbar_label='', axis_scale_factor=1, plot_cbar=True, x_ticks=None, y_ticks=None, z_ticks=None, subtitles=None, figtitle=None)

Plot the wigner function of the state.

Parameters:

Name Type Description Default
state

state with arbitrary number of batch dimensions, result will

required
pts_x

x points to evaluate quasi-probability distribution at

required
pts_y

y points to evaluate quasi-probability distribution at

None
g

float, default: 2

required
related to the value of

math:\hbar in the commutation relation

required

math:[x,\,y] = i\hbar via :math:\hbar=2/g^2.

required
axs

matplotlib axes to plot on

None
contour

make the plot use contouring

True
cbar_label

label for the cbar

''
axis_scale_factor

scale of the axes labels relative

1
plot_cbar

whether to plot cbar

True
x_ticks

tick position for the x-axis

None
y_ticks

tick position for the y-axis

None
z_ticks

tick position for the z-axis

None
subtitles

subtitles for the subplots

None
figtitle

figure title

None

Returns:

Type Description

axis on which the plot was plotted.

Source code in jaxquantum/core/visualization.py
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
def plot_wigner(
    state,
    pts_x,
    pts_y=None,
    g=2,
    axs=None,
    contour=True,
    cbar_label="",
    axis_scale_factor=1,
    plot_cbar=True,
    x_ticks=None,
    y_ticks=None,
    z_ticks=None,
    subtitles=None,
    figtitle=None,
):
    """Plot the wigner function of the state.


    Args:
        state: state with arbitrary number of batch dimensions, result will
        be flattened to a 2d grid to allow for plotting
        pts_x: x points to evaluate quasi-probability distribution at
        pts_y: y points to evaluate quasi-probability distribution at
        g : float, default: 2
        Scaling factor for ``a = 0.5 * g * (x + iy)``.  The value of `g` is
        related to the value of :math:`\\hbar` in the commutation relation
        :math:`[x,\,y] = i\\hbar` via :math:`\\hbar=2/g^2`.
        axs: matplotlib axes to plot on
        contour: make the plot use contouring
        cbar_label: label for the cbar
        axis_scale_factor: scale of the axes labels relative
        plot_cbar: whether to plot cbar
        x_ticks: tick position for the x-axis
        y_ticks: tick position for the y-axis
        z_ticks: tick position for the z-axis
        subtitles: subtitles for the subplots
        figtitle: figure title

    Returns:
        axis on which the plot was plotted.
    """
    return plot_qp(
        state=state,
        pts_x=pts_x,
        pts_y=pts_y,
        g=g,
        axs=axs,
        contour=contour,
        qp_type=WIGNER,
        cbar_label=cbar_label,
        axis_scale_factor=axis_scale_factor,
        plot_cbar=plot_cbar,
        x_ticks=x_ticks,
        y_ticks=y_ticks,
        z_ticks=z_ticks,
        subtitles=subtitles,
        figtitle=figtitle,
    )

powm(qarr, n, clip_eigvals=False)

Matrix power of a Qarray.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required
n Union[int, float]

Exponent. Integer powers use jnp.linalg.matrix_power; float powers diagonalise the matrix.

required
clip_eigvals

When True, clip negative eigenvalues to zero before applying the float power (useful for nearly-PSD matrices).

False

Returns:

Type Description
Qarray

The n-th matrix power as a Qarray (stays SparseDIA for integer

Qarray

non-negative exponents when the input is SparseDIA).

Raises:

Type Description
ValueError

If n is a float and the matrix has negative eigenvalues (and clip_eigvals is False).

Source code in jaxquantum/core/qarray.py
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
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
def powm(qarr: Qarray, n: Union[int, float], clip_eigvals=False) -> Qarray:
    """Matrix power of a ``Qarray``.

    Args:
        qarr: Input quantum array.
        n: Exponent.  Integer powers use ``jnp.linalg.matrix_power``; float
            powers diagonalise the matrix.
        clip_eigvals: When ``True``, clip negative eigenvalues to zero before
            applying the float power (useful for nearly-PSD matrices).

    Returns:
        The *n*-th matrix power as a ``Qarray`` (stays SparseDIA for integer
        non-negative exponents when the input is SparseDIA).

    Raises:
        ValueError: If *n* is a float and the matrix has negative eigenvalues
            (and *clip_eigvals* is ``False``).
    """
    # SparseDIA fast path: binary exponentiation stays in SparseDIA format.
    if qarr.is_sparse_dia and isinstance(n, int) and n >= 0:
        new_impl = qarr._impl.powm(n)
        return Qarray.create(new_impl.data, dims=qarr.dims, implementation=new_impl.impl_type)

    # Convert to dense for powm
    dense_qarr = qarr.to_dense()

    if isinstance(n, int):
        data_res = jnp.linalg.matrix_power(dense_qarr.data, n)
    else:
        evalues, evectors = jnp.linalg.eig(dense_qarr.data)
        if clip_eigvals:
            evalues = jnp.maximum(evalues, 0)
        else:
            if not (evalues >= 0).all():
                raise ValueError(
                    "Non-integer power of a matrix can only be "
                    "computed if the matrix is positive semi-definite."
                    "Got a matrix with a negative eigenvalue."
                )
        data_res = evectors * jnp.pow(evalues, n) @ jnp.linalg.inv(evectors)

    return Qarray.create(data_res, dims=qarr.dims)

powm_data(data, n)

Integer matrix power of a raw array.

Parameters:

Name Type Description Default
data Array

Dense square matrix array.

required
n int

Integer exponent.

required

Returns:

Type Description
Array

The n-th matrix power.

Source code in jaxquantum/core/qarray.py
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
def powm_data(data: Array, n: int) -> Array:
    """Integer matrix power of a raw array.

    Args:
        data: Dense square matrix array.
        n: Integer exponent.

    Returns:
        The *n*-th matrix power.
    """
    return jnp.linalg.matrix_power(data, n)

propagator(H, ts, saveat_tlist=None, solver_options=None)

Generate the propagator for a time dependent Hamiltonian.

Parameters:

Name Type Description Default
H Qarray or callable

A Qarray static Hamiltonian OR a function that takes a time argument and returns a Hamiltonian.

required
ts float or Array

A single time point or an Array of time points.

required
saveat_tlist Optional[Array]

list of times at which to save the state. If -1 or [-1], save only at final time. If None, save at all times in tlist. Default: None.

None

Returns:

Type Description

Qarray or List[Qarray]: The propagator for the Hamiltonian at time t. OR a list of propagators for the Hamiltonian at each time in t.

Source code in jaxquantum/core/solvers.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def propagator(
    H: Union[Qarray, Callable[[float], Qarray]],
    ts: Union[float, Array],
    saveat_tlist: Optional[Array] = None,
    solver_options=None
):
    """ Generate the propagator for a time dependent Hamiltonian.

    Args:
        H (Qarray or callable):
            A Qarray static Hamiltonian OR
            a function that takes a time argument and returns a Hamiltonian.
        ts (float or Array):
            A single time point or
            an Array of time points.
        saveat_tlist: list of times at which to save the state.
            If -1 or [-1], save only at final time.
            If None, save at all times in tlist. Default: None.

    Returns:
        Qarray or List[Qarray]:
            The propagator for the Hamiltonian at time t.
            OR a list of propagators for the Hamiltonian at each time in t.

    """


    ts_is_scalar = robust_isscalar(ts)
    H_is_qarray = isinstance(H, Qarray)

    if H_is_qarray:
        return (-1j * H * ts).expm()
    else:

        if ts_is_scalar:
            H_first = H(0.0)
            if ts == 0:
                return identity_like(H_first)
            ts = jnp.array([0.0, ts])
        else:
            H_first = H(ts[0])

        basis_states = multi_mode_basis_set(H_first.space_dims)
        results = sesolve(H, basis_states, ts, saveat_tlist=saveat_tlist)
        propagators_data = results.data.squeeze(-1).mT
        propagators = Qarray.create(propagators_data, dims=H_first.space_dims)

        return propagators

ptrace(qarr, indx)

Partial trace over subsystem indx.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array (converted to dense internally).

required
indx

Index of the subsystem to trace out.

required

Returns:

Type Description
Qarray

Reduced density matrix as a Qarray.

Source code in jaxquantum/core/qarray.py
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
def ptrace(qarr: Qarray, indx) -> Qarray:
    """Partial trace over subsystem *indx*.

    Args:
        qarr: Input quantum array (converted to dense internally).
        indx: Index of the subsystem to trace out.

    Returns:
        Reduced density matrix as a ``Qarray``.
    """
    # Convert to dense for ptrace
    dense_qarr = qarr.to_dense()
    dense_qarr = ket2dm(dense_qarr)
    rho = dense_qarr.shaped_data
    dims = dense_qarr.dims

    Nq = len(dims[0])

    indxs = [indx, indx + Nq]
    for j in range(Nq):
        if j == indx:
            continue
        indxs.append(j)
        indxs.append(j + Nq)

    bdims = dense_qarr.bdims
    len_bdims = len(bdims)
    bdims_indxs = list(range(len_bdims))
    indxs = bdims_indxs + [j + len_bdims for j in indxs]
    rho = rho.transpose(indxs)

    for j in range(Nq - 1):
        rho = jnp.trace(rho, axis1=2 + len_bdims, axis2=3 + len_bdims)

    return Qarray.create(rho)

qfunc(psi, xvec, yvec, g=2)

Husimi-Q function of a given state vector or density matrix at phase-space points 0.5 * g * (xvec + i*yvec).

Parameters

state : Qarray A state vector or density matrix. This cannot have tensor-product structure.

xvec, yvec : array_like x- and y-coordinates at which to calculate the Husimi-Q function.

float, default: 2

Scaling factor for a = 0.5 * g * (x + iy). The value of g is related to the value of :math:\hbar in the commutation relation :math:[x,\,y] = i\hbar via :math:\hbar=2/g^2.

Returns

jnp.ndarray Values representing the Husimi-Q function calculated over the specified range [xvec, yvec].

Source code in jaxquantum/core/qp_distributions.py
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
def qfunc(psi, xvec, yvec, g=2):
    r"""
    Husimi-Q function of a given state vector or density matrix at phase-space
    points ``0.5 * g * (xvec + i*yvec)``.

    Parameters
    ----------
    state : Qarray
        A state vector or density matrix. This cannot have tensor-product
        structure.

    xvec, yvec : array_like
        x- and y-coordinates at which to calculate the Husimi-Q function.

    g : float, default: 2
        Scaling factor for ``a = 0.5 * g * (x + iy)``.  The value of `g` is
        related to the value of :math:`\hbar` in the commutation relation
        :math:`[x,\,y] = i\hbar` via :math:`\hbar=2/g^2`.

    Returns
    -------
    jnp.ndarray
        Values representing the Husimi-Q function calculated over the specified
        range ``[xvec, yvec]``.

    """

    alpha_grid, prefactor = _qfunc_coherent_grid(xvec, yvec, g)

    if psi.is_vec():
        psi = psi.to_ket()

        def _compute_qfunc(psi, alpha_grid, prefactor, g):
            out = _qfunc_iterative_single(psi, alpha_grid, prefactor, g)
            out /= jnp.pi
            return out
    else:

        def _compute_qfunc(psi, alpha_grid, prefactor, g):
            values, vectors = jnp.linalg.eigh(psi)
            vectors = vectors.T
            out = values[0] * _qfunc_iterative_single(
                vectors[0], alpha_grid, prefactor, g
            )
            for value, vector in zip(values[1:], vectors[1:]):
                out += value * _qfunc_iterative_single(vector, alpha_grid, prefactor, g)
            out /= jnp.pi

            return out

    psi = psi.data

    vmapped_compute_qfunc = [_compute_qfunc]

    for _ in psi.shape[:-2]:
        vmapped_compute_qfunc.append(
            vmap(
                vmapped_compute_qfunc[-1],
                in_axes=(0, None, None, None),
                out_axes=0,
            )
        )
    return vmapped_compute_qfunc[-1](psi, alpha_grid, prefactor, g)

qt2jqt(qt_obj, dtype=jnp.complex128)

QuTiP state -> Qarray.

Parameters:

Name Type Description Default
qt_obj

QuTiP state.

required
dtype

JAX dtype.

complex128

Returns:

Type Description

Qarray.

Source code in jaxquantum/core/conversions.py
22
23
24
25
26
27
28
29
30
31
32
33
34
def qt2jqt(qt_obj, dtype=jnp.complex128):
    """QuTiP state -> Qarray.

    Args:
        qt_obj: QuTiP state.
        dtype: JAX dtype.

    Returns:
        Qarray.
    """
    if isinstance(qt_obj, Qarray) or qt_obj is None:
        return qt_obj
    return Qarray.create(jnp.array(qt_obj.full(), dtype=dtype), dims=qt_obj.dims)

qubit_rotation(theta, nx, ny, nz)

Single qubit rotation.

Parameters:

Name Type Description Default
theta float

rotation angle.

required
nx

rotation axis x component.

required
ny

rotation axis y component.

required
nz

rotation axis z component.

required

Returns:

Type Description
Qarray

Single qubit rotation operator.

Source code in jaxquantum/core/operators.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def qubit_rotation(theta: float, nx, ny, nz) -> Qarray:
    """Single qubit rotation.

    Args:
        theta: rotation angle.
        nx: rotation axis x component.
        ny: rotation axis y component.
        nz: rotation axis z component.

    Returns:
        Single qubit rotation operator.
    """
    return jnp.cos(theta / 2) * identity(2) - 1j * jnp.sin(theta / 2) * (
        nx * sigmax() + ny * sigmay() + nz * sigmaz()
    )

robust_asarray(data)

Convert data to a JAX array, leaving sparse BCOO and SparseDiaData untouched.

Parameters:

Name Type Description Default
data

Input data — any array-like, sparse.BCOO, or SparseDiaData.

required

Returns:

Type Description
Union[Array, BCOO]

A jax.Array, sparse.BCOO, or SparseDiaData.

Source code in jaxquantum/core/qarray.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def robust_asarray(data) -> Union[Array, sparse.BCOO]:
    """Convert *data* to a JAX array, leaving sparse BCOO and SparseDiaData untouched.

    Args:
        data: Input data — any array-like, ``sparse.BCOO``, or ``SparseDiaData``.

    Returns:
        A ``jax.Array``, ``sparse.BCOO``, or ``SparseDiaData``.
    """
    if isinstance(data, sparse.BCOO):
        return data
    # SparseDiaData has a ``_is_sparse_dia`` marker; pass it through unchanged
    if getattr(data, "_is_sparse_dia", False):
        return data
    return jnp.asarray(data)

sesolve(H, rho0, tlist, saveat_tlist=None, solver_options=None)

Schrödinger Equation solver.

Parameters:

Name Type Description Default
H Union[Qarray, Callable[[float], Qarray]]

time dependent Hamiltonian function or time-independent Qarray.

required
rho0 Qarray

initial state, must be a density matrix. For statevector evolution, please use sesolve.

required
tlist Array

time list

required
saveat_tlist Optional[Array]

list of times at which to save the state. If -1 or [-1], save only at final time. If None, save at all times in tlist. Default: None.

None
solver_options Optional[SolverOptions]

SolverOptions with solver options

None

Returns:

Type Description
Qarray

list of states

Source code in jaxquantum/core/solvers.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
def sesolve(
    H: Union[Qarray, Callable[[float], Qarray]],
    rho0: Qarray,
    tlist: Array,
    saveat_tlist: Optional[Array] = None,
    solver_options: Optional[SolverOptions] = None,
) -> Qarray:
    """Schrödinger Equation solver.

    Args:
        H: time dependent Hamiltonian function or time-independent Qarray.
        rho0: initial state, must be a density matrix. For statevector evolution, please use sesolve.
        tlist: time list
        saveat_tlist: list of times at which to save the state.
            If -1 or [-1], save only at final time.
            If None, save at all times in tlist. Default: None.
        solver_options: SolverOptions with solver options

    Returns:
        list of states
    """

    saveat_tlist = saveat_tlist if saveat_tlist is not None else tlist

    saveat_tlist = jnp.atleast_1d(saveat_tlist)

    ψ = rho0

    if ψ.qtype == Qtypes.oper:
        raise ValueError(
            "Please use `jqt.mesolve` for initial state inputs in density matrix form."
        )

    ψ = ψ.to_ket().to_dense()

    if robust_isscalar(H):
        H = H * identity_like(ψ)  # treat scalar H as a multiple of the identity

    dims = ψ.dims
    ψ = ψ.data

    if isinstance(H, Qarray):
        Ht_data = lambda t: H.data
    else:
        Ht_data = lambda t: H(t).data

    ys = _sesolve_data(Ht_data, ψ, tlist, saveat_tlist,
                       solver_options=solver_options)

    return jnp2jqt(ys, dims=dims)

set_precision(precision)

Set the precision of JAX operations.

Parameters:

Name Type Description Default
precision Literal['single', 'double']

'single' or 'double'

required

Raises:

Type Description
ValueError

if precision is not 'single' or 'double'

Source code in jaxquantum/utils/utils.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def set_precision(precision: Literal["single", "double"]):
    """
    Set the precision of JAX operations.

    Args:
        precision: 'single' or 'double'

    Raises:
        ValueError: if precision is not 'single' or 'double'
    """
    if precision == "single":
        config.update("jax_enable_x64", False)
    elif precision == "double":
        config.update("jax_enable_x64", True)
    else:
        raise ValueError("precision must be 'single' or 'double'")

sigmam(implementation=QarrayImplType.DENSE)

σ-

Returns:

Type Description
Qarray

σ- Pauli Operator

Source code in jaxquantum/core/operators.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
def sigmam(implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """σ-

    Returns:
        σ- Pauli Operator
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        diags = jnp.array([[1.0, 0.0]])
        return _make_sparsedia(offsets=(-1,), diags=diags)
    return Qarray.create(jnp.array([[0.0, 0.0], [1.0, 0.0]]), implementation=implementation)

sigmap(implementation=QarrayImplType.DENSE)

σ+

Returns:

Type Description
Qarray

σ+ Pauli Operator

Source code in jaxquantum/core/operators.py
105
106
107
108
109
110
111
112
113
114
def sigmap(implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """σ+

    Returns:
        σ+ Pauli Operator
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        diags = jnp.array([[0.0, 1.0]])
        return _make_sparsedia(offsets=(1,), diags=diags)
    return Qarray.create(jnp.array([[0.0, 1.0], [0.0, 0.0]]), implementation=implementation)

sigmax(implementation=QarrayImplType.DENSE)

σx

Parameters:

Name Type Description Default
implementation QarrayImplType

Qarray implementation type, e.g. "sparse" or "dense".

DENSE

Returns:

Type Description
Qarray

σx Pauli Operator

Source code in jaxquantum/core/operators.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def sigmax(implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """σx

    Args:
        implementation: Qarray implementation type, e.g. "sparse" or "dense".

    Returns:
        σx Pauli Operator
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        # Offset -1: valid at [0:1] → diag[0] = A[1,0] = 1.0, diag[1] = 0 (trailing zero)
        # Offset +1: valid at [1:]  → diag[0] = 0 (leading zero), diag[1] = A[0,1] = 1.0
        diags = jnp.array([[1.0, 0.0], [0.0, 1.0]])
        return _make_sparsedia(offsets=(-1, 1), diags=diags)
    return Qarray.create(jnp.array([[0.0, 1.0], [1.0, 0.0]]), implementation=implementation)

sigmay(implementation=QarrayImplType.DENSE)

σy

Returns:

Type Description
Qarray

σy Pauli Operator

Source code in jaxquantum/core/operators.py
53
54
55
56
57
58
59
60
61
62
def sigmay(implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """σy

    Returns:
        σy Pauli Operator
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        diags = jnp.array([[1.0j, 0.0], [0.0, -1.0j]])
        return _make_sparsedia(offsets=(-1, 1), diags=diags)
    return Qarray.create(jnp.array([[0.0, -1.0j], [1.0j, 0.0]]), implementation=implementation)

sigmaz(implementation=QarrayImplType.DENSE)

σz

Returns:

Type Description
Qarray

σz Pauli Operator

Source code in jaxquantum/core/operators.py
65
66
67
68
69
70
71
72
73
74
def sigmaz(implementation: QarrayImplType = QarrayImplType.DENSE) -> Qarray:
    """σz

    Returns:
        σz Pauli Operator
    """
    if QarrayImplType(implementation) == QarrayImplType.SPARSE_DIA:
        diags = jnp.array([[1.0, -1.0]])
        return _make_sparsedia(offsets=(0,), diags=diags)
    return Qarray.create(jnp.array([[1.0, 0.0], [0.0, -1.0]]), implementation=implementation)

sinm(qarr)

Matrix sine of a Qarray.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array (converted to dense internally).

required

Returns:

Type Description
Qarray

A dense Qarray containing the matrix sine.

Source code in jaxquantum/core/qarray.py
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
def sinm(qarr: Qarray) -> Qarray:
    """Matrix sine of a ``Qarray``.

    Args:
        qarr: Input quantum array (converted to dense internally).

    Returns:
        A dense ``Qarray`` containing the matrix sine.
    """
    dims = qarr.dims
    # Convert to dense for sinm
    dense_data = qarr.to_dense().data
    data = sinm_data(dense_data)
    return Qarray.create(data, dims=dims)

sinm_data(data, **kwargs)

Matrix sine of a raw array.

Parameters:

Name Type Description Default
data Array

Dense matrix array.

required
**kwargs

Unused; kept for API consistency.

{}

Returns:

Type Description
Array

The matrix sine computed as (expm(i*A) - expm(-i*A)) / (2i).

Source code in jaxquantum/core/qarray.py
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
def sinm_data(data: Array, **kwargs) -> Array:
    """Matrix sine of a raw array.

    Args:
        data: Dense matrix array.
        **kwargs: Unused; kept for API consistency.

    Returns:
        The matrix sine computed as ``(expm(i*A) - expm(-i*A)) / (2i)``.
    """
    return (expm_data(1j * data) - expm_data(-1j * data)) / (2j)

solve(f, ρ0, tlist, saveat_tlist, args, solver_options=None)

Gets teh desired solver from diffrax.

Parameters:

Name Type Description Default
f

function defining the ODE

required
ρ0

initial state

required
tlist

time list

required
saveat_tlist

list of times at which to save the state pass in [-1] to save only at final time

required
args

additional arguments to f

required
solver_options Optional[SolverOptions]

dictionary with solver options

None

Returns:

Type Description

solution

Source code in jaxquantum/core/solvers.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def solve(f, ρ0, tlist, saveat_tlist, args, solver_options: Optional[
    SolverOptions] = None):
    """Gets teh desired solver from diffrax.

    Args:
        f: function defining the ODE
        ρ0: initial state
        tlist: time list
        saveat_tlist: list of times at which to save the state
            pass in [-1] to save only at final time
        args: additional arguments to f
        solver_options: dictionary with solver options

    Returns:
        solution
    """

    # f and ts
    term = ODETerm(f)

    if saveat_tlist.shape[0] == 1 and saveat_tlist == -1:
        saveat = SaveAt(t1=True)
    else:
        saveat = SaveAt(ts=saveat_tlist)

    # solver
    solver_options = solver_options or SolverOptions.create()

    solver_name = solver_options.solver
    solver = getattr(diffrax, solver_name)()
    stepsize_controller = PIDController(rtol=solver_options.rtol, atol=solver_options.atol)

    # solve!
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                message="Complex dtype support in Diffrax",
                                category=UserWarning)  # NOTE: suppresses complex dtype warning in diffrax
        sol = diffeqsolve(
            term,
            solver,
            t0=tlist[0],
            t1=tlist[-1],
            dt0=tlist[1] - tlist[0],
            y0=ρ0,
            saveat=saveat,
            stepsize_controller=stepsize_controller,
            args=args,
            max_steps=solver_options.max_steps,
            progress_meter=CustomProgressMeter()
            if solver_options.progress_meter
            else NoProgressMeter(),
        )

    return sol

squeeze(N, z)

Single-mode Squeezing operator.

Parameters:

Name Type Description Default
N

Hilbert Space Size

required
z

squeezing parameter

required

Returns:

Type Description

Sqeezing operator

Source code in jaxquantum/core/operators.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def squeeze(N, z):
    """Single-mode Squeezing operator.


    Args:
        N: Hilbert Space Size
        z: squeezing parameter

    Returns:
        Sqeezing operator
    """

    a = destroy(N)
    op = (1 / 2.0) * jnp.conj(z) * (a @ a) - (1 / 2.0) * z * (a.dag() @ a.dag())
    return op.expm()

tensor(*args, **kwargs)

Tensor (Kronecker) product of two or more Qarray objects.

Parameters:

Name Type Description Default
*args

Qarray objects to tensor together (left to right).

()
**kwargs

Optional keyword arguments. Pass parallel=True to use an einsum-based batched outer product instead of jnp.kron.

{}

Returns:

Type Description
Qarray

The tensor product as a Qarray. The output implementation is

Qarray

determined by the highest PROMOTION_ORDER among the inputs: all-sparse

Qarray

inputs → sparse output; any dense input → dense output. This holds for

Qarray

both parallel=True and parallel=False.

Note

parallel=True uses an einsum-based batched outer product. The einsum is always computed on dense data for efficiency, but the result is then wrapped in the appropriate backend (sparse when all inputs are sparse, dense otherwise). For the default (parallel=False) path each backend's kron method is used directly.

Source code in jaxquantum/core/qarray.py
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
def tensor(*args, **kwargs) -> Qarray:
    """Tensor (Kronecker) product of two or more ``Qarray`` objects.

    Args:
        *args: ``Qarray`` objects to tensor together (left to right).
        **kwargs: Optional keyword arguments.  Pass ``parallel=True`` to use
            an einsum-based batched outer product instead of ``jnp.kron``.

    Returns:
        The tensor product as a ``Qarray``.  The output implementation is
        determined by the highest ``PROMOTION_ORDER`` among the inputs: all-sparse
        inputs → sparse output; any dense input → dense output.  This holds for
        both ``parallel=True`` and ``parallel=False``.

    Note:
        ``parallel=True`` uses an einsum-based batched outer product.  The
        einsum is always computed on dense data for efficiency, but the result
        is then wrapped in the appropriate backend (sparse when all inputs are
        sparse, dense otherwise).  For the default (``parallel=False``) path
        each backend's ``kron`` method is used directly.
    """
    parallel = kwargs.pop("parallel", False)

    if parallel:
        # Determine target implementation: highest PROMOTION_ORDER wins.
        # All-sparse → sparse; any dense input → dense (same rule as non-parallel).
        target_impl_type = max(
            (arg.impl_type for arg in args),
            key=lambda t: t.get_impl_class().PROMOTION_ORDER,
        )
        # Einsum-based batched outer product (computed on dense data).
        dense_args = [arg.to_dense() for arg in args]
        data = dense_args[0].data
        dims_0 = dense_args[0].dims[0]
        dims_1 = dense_args[0].dims[1]
        for arg in dense_args[1:]:
            a, b = data, arg.data
            if len(a.shape) > len(b.shape):
                batch_dim = a.shape[:-2]
            elif len(a.shape) == len(b.shape):
                batch_dim = a.shape[:-2] if prod(a.shape[:-2]) > prod(b.shape[:-2]) else b.shape[:-2]
            else:
                batch_dim = b.shape[:-2]

            # NOTE: implementation einsum should be used when available
            data = jnp.einsum("...ij,...kl->...ikjl", a, b).reshape(
                *batch_dim, a.shape[-2] * b.shape[-2], -1
            )
            dims_0 = dims_0 + arg.dims[0]
            dims_1 = dims_1 + arg.dims[1]
        return Qarray.create(data, dims=(dims_0, dims_1), implementation=target_impl_type)

    # Non-parallel: delegate to each impl's kron method.
    # All-sparse inputs stay sparse; mixed inputs promote to dense via _coerce.
    current_impl = args[0]._impl
    dims_0 = args[0].dims[0]
    dims_1 = args[0].dims[1]
    for arg in args[1:]:
        current_impl = current_impl.kron(arg._impl)
        dims_0 = dims_0 + arg.dims[0]
        dims_1 = dims_1 + arg.dims[1]
    return Qarray.create(current_impl.data, dims=(dims_0, dims_1),
                         implementation=current_impl.impl_type)

tensor_basis(single_basis, n)

Construct n-fold tensor product basis from a single-system basis.

Parameters:

Name Type Description Default
single_basis Qarray

The single-system operator basis as a Qarray.

required
n int

Number of tensor copies to construct.

required

Returns:

Type Description
Qarray

Qarray containing the n-fold tensor product basis operators.

Qarray

The resulting basis has b^n elements where b is the number

Qarray

of operators in the single-system basis.

Source code in jaxquantum/core/measurements.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def tensor_basis(single_basis: Qarray, n: int) -> Qarray:
    """Construct n-fold tensor product basis from a single-system basis.

    Args:
        single_basis: The single-system operator basis as a Qarray.
        n: Number of tensor copies to construct.

    Returns:
        Qarray containing the n-fold tensor product basis operators.
        The resulting basis has b^n elements where b is the number
        of operators in the single-system basis.
    """

    dims = single_basis.dims

    single_basis = single_basis.data
    b, d, _ = single_basis.shape
    indices = jnp.stack(jnp.meshgrid(*[jnp.arange(b)] * n, indexing="ij"),
                        axis=-1).reshape(-1, n)  # shape (b^n, n)

    # Select the operators based on indices: shape (b^n, n, d, d)
    selected = single_basis[indices]  # shape: (b^n, n, d, d)

    # Vectorized Kronecker products
    full_basis = vmap(lambda ops: reduce(jnp.kron, ops))(selected)

    new_dims = tuple(tuple(x**n for x in row) for row in dims)

    return Qarray.create(full_basis, dims=new_dims, bdims=(b**n,))

thermal_dm(N, n)

Thermal state.

Parameters:

Name Type Description Default
N int

Hilbert Space Size.

required
n float

average photon number.

required
Return

Thermal state.

Source code in jaxquantum/core/operators.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def thermal_dm(N: int, n: float) -> Qarray:
    """Thermal state.

    Args:
        N: Hilbert Space Size.
        n: average photon number.

    Return:
        Thermal state.
    """

    beta = jnp.log(1 + 1 / n)

    return Qarray.create(
        jnp.where(
            jnp.isposinf(beta),
            basis(N, 0).to_dm().data,
            jnp.diag(jnp.exp(-beta * jnp.linspace(0, N - 1, N))),
        )
    ).unit()

to_ket(qarr)

Convert qarr to a ket.

Parameters:

Name Type Description Default
qarr Qarray

A ket (returned as-is) or bra (conjugate-transposed).

required

Returns:

Type Description
Qarray

The ket form of qarr.

Raises:

Type Description
ValueError

If qarr is an operator.

Source code in jaxquantum/core/qarray.py
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
def to_ket(qarr: Qarray) -> Qarray:
    """Convert *qarr* to a ket.

    Args:
        qarr: A ket (returned as-is) or bra (conjugate-transposed).

    Returns:
        The ket form of *qarr*.

    Raises:
        ValueError: If *qarr* is an operator.
    """
    if qarr.qtype == Qtypes.ket:
        return qarr
    elif qarr.qtype == Qtypes.bra:
        return qarr.dag()
    else:
        raise ValueError("Can only get ket from a ket or bra.")

tr(qarr, **kwargs)

Full trace of qarr.

For sparse Qarray objects the trace is computed natively on the BCOO data using a masked scatter — no densification. Custom axis arguments are ignored for sparse (the last two dimensions are always the matrix dimensions in jaxquantum's convention).

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required
**kwargs

Forwarded to jnp.trace for dense arrays (e.g. axis1, axis2).

{}

Returns:

Type Description
Array

The trace as a scalar (or batched array of scalars).

Source code in jaxquantum/core/qarray.py
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
def tr(qarr: Qarray, **kwargs) -> Array:
    """Full trace of *qarr*.

    For sparse ``Qarray`` objects the trace is computed natively on the BCOO
    data using a masked scatter — no densification.  Custom axis arguments
    are ignored for sparse (the last two dimensions are always the matrix
    dimensions in jaxquantum's convention).

    Args:
        qarr: Input quantum array.
        **kwargs: Forwarded to ``jnp.trace`` for dense arrays (e.g.
            ``axis1``, ``axis2``).

    Returns:
        The trace as a scalar (or batched array of scalars).
    """
    if qarr.is_sparse_bcoo:
        return qarr._impl.trace()
    if qarr.is_sparse_dia:
        return qarr._impl.trace()
    axis1 = kwargs.get("axis1", -2)
    axis2 = kwargs.get("axis2", -1)
    return jnp.trace(qarr.data, axis1=axis1, axis2=axis2, **kwargs)

trace(qarr, **kwargs)

Full trace (alias for :func:tr).

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required
**kwargs

Forwarded to :func:tr.

{}

Returns:

Type Description
Array

The trace as a scalar (or batched array of scalars).

Source code in jaxquantum/core/qarray.py
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
def trace(qarr: Qarray, **kwargs) -> Array:
    """Full trace (alias for :func:`tr`).

    Args:
        qarr: Input quantum array.
        **kwargs: Forwarded to :func:`tr`.

    Returns:
        The trace as a scalar (or batched array of scalars).
    """
    return tr(qarr, **kwargs)

transpose(qarr, indices)

Transpose subsystem indices of the quantum array.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required
indices List[int]

New ordering of subsystem indices.

required

Returns:

Type Description
Qarray

Transposed Qarray (converted to dense first).

Source code in jaxquantum/core/qarray.py
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
def transpose(qarr: Qarray, indices: List[int]) -> Qarray:
    """Transpose subsystem indices of the quantum array.

    Args:
        qarr: Input quantum array.
        indices: New ordering of subsystem indices.

    Returns:
        Transposed ``Qarray`` (converted to dense first).
    """

    qarr = qarr.to_dense()

    indices = list(indices)

    shaped_data = qarr.shaped_data
    dims = qarr.dims
    bdims_indxs = list(range(len(qarr.bdims)))

    reshape_indices = indices + [j + len(dims[0]) for j in indices]
    reshape_indices = bdims_indxs + [j + len(bdims_indxs) for j in reshape_indices]

    shaped_data = shaped_data.transpose(reshape_indices)
    new_dims = (
        tuple([dims[0][j] for j in indices]),
        tuple([dims[1][j] for j in indices]),
    )

    full_dims = prod(dims[0])
    full_data = shaped_data.reshape(*qarr.bdims, full_dims, -1)

    # Preserve implementation type
    implementation = qarr.impl_type
    return Qarray.create(full_data, dims=new_dims, implementation=implementation)

unit(qarr)

Normalize qarr to unit norm.

Parameters:

Name Type Description Default
qarr Qarray

Input quantum array.

required

Returns:

Type Description
Qarray

Normalized quantum array.

Source code in jaxquantum/core/qarray.py
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
def unit(qarr: Qarray) -> Qarray:
    """Normalize *qarr* to unit norm.

    Args:
        qarr: Input quantum array.

    Returns:
        Normalized quantum array.
    """
    return qarr / qarr.norm()

wigner(psi, xvec, yvec, method='clenshaw', g=2)

Wigner function for a state vector or density matrix at points xvec + i * yvec.

Parameters

Qarray

A state vector or density matrix.

array_like

x-coordinates at which to calculate the Wigner function.

array_like

y-coordinates at which to calculate the Wigner function.

float, default: 2

Scaling factor for a = 0.5 * g * (x + iy), default g = 2. The value of g is related to the value of hbar in the commutation relation [x, y] = i * hbar via hbar=2/g^2.

string {'clenshaw', 'iterative', 'laguerre', 'fft'}, default: 'clenshaw'

Only 'clenshaw' is currently supported. Select method 'clenshaw' 'iterative', 'laguerre', or 'fft', where 'clenshaw' and 'iterative' use an iterative method to evaluate the Wigner functions for density matrices :math:|m><n|, while 'laguerre' uses the Laguerre polynomials in scipy for the same task. The 'fft' method evaluates the Fourier transform of the density matrix. The 'iterative' method is default, and in general recommended, but the 'laguerre' method is more efficient for very sparse density matrices (e.g., superpositions of Fock states in a large Hilbert space). The 'clenshaw' method is the preferred method for dealing with density matrices that have a large number of excitations (>~50). 'clenshaw' is a fast and numerically stable method.

Returns

array

Values representing the Wigner function calculated over the specified range [xvec,yvec].

References

Ulf Leonhardt, Measuring the Quantum State of Light, (Cambridge University Press, 1997)

Source code in jaxquantum/core/qp_distributions.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def wigner(psi, xvec, yvec, method="clenshaw", g=2):
    """Wigner function for a state vector or density matrix at points
    `xvec + i * yvec`.

    Parameters
    ----------

    state : Qarray
        A state vector or density matrix.

    xvec : array_like
        x-coordinates at which to calculate the Wigner function.

    yvec : array_like
        y-coordinates at which to calculate the Wigner function.

    g : float, default: 2
        Scaling factor for `a = 0.5 * g * (x + iy)`, default `g = 2`.
        The value of `g` is related to the value of `hbar` in the commutation
        relation `[x, y] = i * hbar` via `hbar=2/g^2`.

    method : string {'clenshaw', 'iterative', 'laguerre', 'fft'}, default: 'clenshaw'
        Only 'clenshaw' is currently supported.
        Select method 'clenshaw' 'iterative', 'laguerre', or 'fft', where 'clenshaw'
        and 'iterative' use an iterative method to evaluate the Wigner functions for density
        matrices :math:`|m><n|`, while 'laguerre' uses the Laguerre polynomials
        in scipy for the same task. The 'fft' method evaluates the Fourier
        transform of the density matrix. The 'iterative' method is default, and
        in general recommended, but the 'laguerre' method is more efficient for
        very sparse density matrices (e.g., superpositions of Fock states in a
        large Hilbert space). The 'clenshaw' method is the preferred method for
        dealing with density matrices that have a large number of excitations
        (>~50). 'clenshaw' is a fast and numerically stable method.

    Returns
    -------

    W : array
        Values representing the Wigner function calculated over the specified
        range [xvec,yvec].


    References
    ----------

    Ulf Leonhardt,
    Measuring the Quantum State of Light, (Cambridge University Press, 1997)

    """

    if not (psi.is_vec() or psi.is_dm()):
        raise TypeError("Input state is not a valid operator.")

    if method == "fft":
        raise NotImplementedError("Only the 'clenshaw' method is implemented.")

    if method == "iterative":
        raise NotImplementedError("Only the 'clenshaw' method is implemented.")

    elif method == "laguerre":
        raise NotImplementedError("Only the 'clenshaw' method is implemented.")

    elif method == "clenshaw":
        rho = psi.to_dm()
        rho = rho.data

        vmapped_wigner_clenshaw = [_wigner_clenshaw]

        for _ in rho.shape[:-2]:
            vmapped_wigner_clenshaw.append(
                vmap(
                    vmapped_wigner_clenshaw[-1],
                    in_axes=(0, None, None, None),
                    out_axes=0,
                )
            )
        return vmapped_wigner_clenshaw[-1](rho, xvec, yvec, g)

    else:
        raise TypeError("method must be either 'iterative', 'laguerre', or 'fft'.")