Skip to content

API Reference

This page contains the auto-generated API reference for quantum-emotion. All public classes listed below are also re-exported at the top-level quantum_emotion namespace (from quantum_emotion import KetState, Hadamard, CNOT).

Core Registers & Gate Abstractions

quantum_emotion.core

Core quantum state registers and gate abstractions.

Defines the user-facing KetState and BraState quantum registers as well as the CircuitOp, BaseGate, Measure, ClassicallyControlledGate, and CompositeGate operator abstractions. Concrete quantum gates live in quantum_emotion.gates, while internal tensor-network contraction mechanics live in quantum_emotion._register.

KetState

Bases: CoreRegister

Ket state register \(|\psi\rangle\).

A KetState is acted upon by gates and mid-circuit measurements from the left-hand side (op @ ket or composite_gate @ ket) and forms inner products with a BraState on the left (bra @ ket).

Source code in src/quantum_emotion/core.py
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 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
 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
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 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
class KetState(CoreRegister):
    r"""
    Ket state register $|\psi\rangle$.

    A `KetState` is acted upon by gates and mid-circuit measurements
    from the left-hand side (`op @ ket` or `composite_gate @ ket`) and
    forms inner products with a `BraState` on the left (`bra @ ket`).
    """

    def _resolve_outcomes(
        self,
        outcomes: Mapping[int | str, int] | Sequence[int] | int,
    ) -> tuple[int, ...]:
        """
        Validate and convert `outcomes` into a chronological tuple of
        length `len(self._measurements)`.
        """
        num_meas = len(self._measurements)
        if num_meas == 0:
            if isinstance(outcomes, (tuple, list, Mapping)) and (
                len(outcomes) == 0
            ):
                return ()
            raise ValueError(
                "".join(
                    (
                        "Cannot post-select outcomes on a register with ",
                        "no mid-circuit measurements.",
                    )
                ),
            )

        if isinstance(outcomes, Mapping):
            keys_in_order = [entry[1] for entry in self._measurements]
            if len(set(keys_in_order)) != len(keys_in_order):
                raise ValueError(
                    "".join(
                        (
                            "Register has duplicate classical keys ",
                            f"{tuple(keys_in_order)}; pass 'outcomes' as ",
                            "a chronological sequence instead of a mapping.",
                        )
                    ),
                )
            expected_keys = set(keys_in_order)
            provided_keys = set(outcomes.keys())
            if provided_keys != expected_keys:
                raise ValueError(
                    "".join(
                        (
                            "Outcome mapping keys do not match measured ",
                            f"keys: expected {expected_keys}, got ",
                            f"{provided_keys}.",
                        )
                    ),
                )
            raw_seq = [outcomes[k] for k in keys_in_order]
        elif isinstance(outcomes, int) and not isinstance(outcomes, bool):
            if num_meas != 1:
                raise ValueError(
                    "".join(
                        (
                            f"Expected {num_meas} measurement outcomes, ",
                            f"got scalar {outcomes}.",
                        )
                    ),
                )
            raw_seq = [outcomes]
        elif isinstance(outcomes, (tuple, list)):
            if len(outcomes) != num_meas:
                raise ValueError(
                    "".join(
                        (
                            f"Expected {num_meas} measurement outcomes, ",
                            f"got {len(outcomes)}.",
                        )
                    ),
                )
            raw_seq = list(outcomes)
        else:
            raise TypeError(
                "".join(
                    (
                        "outcomes must be a sequence of integers, ",
                        "a key-to-integer mapping, or a single integer.",
                    )
                ),
            )

        resolved: list[int] = []
        for val in raw_seq:
            if isinstance(val, bool) or not isinstance(val, int):
                raise TypeError("Each measurement outcome must be an integer.")
            if not (0 <= val < self.d):
                raise ValueError(
                    "".join(
                        (
                            f"Measurement outcome {val} is out of range ",
                            f"for local dimension d={self.d} ",
                            f"(expected 0 <= outcome < {self.d}).",
                        )
                    ),
                )
            resolved.append(val)
        return tuple(resolved)

    def eval(
        self,
        flat: bool = True,
        *,
        outcomes: Mapping[int | str, int] | Sequence[int] | int | None = None,
        normalize: bool = True,
        **kwargs: object,
    ) -> np.ndarray:
        r"""
        Contract the ket tensor network and return $|\psi\rangle$.

        When mid-circuit measurements are present, `outcomes` can be
        used to select a trajectory to contract by specifying the
        desired measurement outcomes.

        Args:
            flat: If `True`, return a 1D complex vector of shape
                `(d**N,)`. If `False`, return shape `(d,) * N`.
            outcomes: Optional classical outcomes to post-select, given
                as a chronological sequence `(m_0, ..., m_{K-1})`, an
                unambiguous `{key: outcome}` mapping, or a single `int`
                when $K = 1$.
            normalize: If `True` (default), normalize the post-selected
                branch and raise `ValueError` if its probability is
                zero. If `False`, return the raw unnormalized Kraus
                vector $|\tilde{\psi}_{\mathbf{m}}\rangle$.
            **kwargs: Additional keyword arguments forwarded to
                `cotengra.array_contract`.

        Returns:
            Contracted state array of shape `(d**N,)` or `(d,) * N`.

        Raises:
            TypeError: If `outcomes` or `normalize` has an invalid type.
            ValueError: If unpinned measurements exist, `outcomes` do
                not match the measurement records, or `normalize=True`
                on a zero-probability branch.
        """
        if not isinstance(flat, bool):
            raise TypeError("flat must be a boolean.")
        if not isinstance(normalize, bool):
            raise TypeError("normalize must be a boolean.")

        if outcomes is None:
            return super().eval(flat=flat, **kwargs)

        outcome_tuple = self._resolve_outcomes(outcomes)
        if len(outcome_tuple) == 0:
            return super().eval(flat=flat, **kwargs)

        _check_dense_tensor_limits(self.N, self.d, "eval()")
        pinned_G = self.G.copy()
        next_node = self._next_node_id
        for entry, m_val in zip(self._measurements, outcome_tuple):
            uid = entry[0]
            c_leg = self.classical_frontier[uid]
            basis_vec = np.zeros(self.d, dtype=np.complex128)
            basis_vec[m_val] = 1.0
            basis_vec.flags.writeable = False

            pinned_G.add_node(next_node, tensor=basis_vec, kind="postselect")
            pinned_G.add_edge(
                c_leg[0],
                next_node,
                out_axis=c_leg[1],
                in_axis=0,
                classical_uid=uid,
            )
            next_node += 1

        output_legs = [self.frontier[w] for w in range(self.N)]
        state = self._contract_graph(
            pinned_G,
            output_legs=output_legs,
            **kwargs,
        )
        if normalize:
            norm = float(np.linalg.norm(state))
            if np.isclose(norm, 0.0, atol=1e-15):
                raise ValueError(
                    "".join(
                        (
                            f"Post-selected outcome {outcome_tuple} ",
                            "has zero probability.",
                        )
                    ),
                )
            state = state / norm

        if flat:
            return state.reshape(self.d**self.N)
        return state.reshape((self.d,) * self.N)

    def eval_branches(
        self,
        flat: bool = True,
        *,
        tol: float = 1e-12,
        **kwargs: object,
    ) -> dict[tuple[int, ...], tuple[float, np.ndarray]]:
        r"""
        Evaluate all non-zero classical measurement trajectories.

        Args:
            flat: If `True`, format each branch state as shape
                `(d**N,)`. If `False`, format as `(d,) * N`.
            tol: Minimum Born probability threshold for including a
                trajectory in the returned dictionary.
            **kwargs: Additional keyword arguments forwarded to
                `cotengra.array_contract`.

        Returns:
            branches:
                Dictionary `{outcomes_tuple: (probability, state)}`
                mapping each non-zero classical outcome tuple to its
                Born probability $p(\mathbf{m})$ and normalized state
                $|\psi_{\mathbf{m}}\rangle$.
        """
        if not isinstance(flat, bool):
            raise TypeError("flat must be a boolean.")
        if (
            isinstance(tol, bool)
            or not isinstance(tol, (int, float, np.number))
            or isinstance(tol, (complex, np.complexfloating))
        ):
            raise TypeError("tol must be a real number.")
        tol_val = float(tol)
        if (not np.isfinite(tol_val)) or tol_val < 0.0:
            raise ValueError("tol must be a finite non-negative number.")

        classical_legs = [
            self.classical_frontier[entry[0]] for entry in self._measurements
        ]
        quantum_legs = [self.frontier[w] for w in range(self.N)]
        num_meas = len(classical_legs)
        _check_dense_tensor_limits(
            num_meas + self.N,
            self.d,
            "eval_branches()",
        )

        full_tensor = self._contract_graph(
            self.G,
            output_legs=classical_legs + quantum_legs,
            **kwargs,
        )
        reshaped = full_tensor.reshape(self.d**num_meas, self.d**self.N)

        branches: dict[tuple[int, ...], tuple[float, np.ndarray]] = {}
        outcomes_iter = itertools.product(range(self.d), repeat=num_meas)
        for idx, outcome in enumerate(outcomes_iter):
            branch_vec = reshaped[idx]
            prob = float(np.real(np.vdot(branch_vec, branch_vec)))
            if prob > tol_val:
                normed = branch_vec / np.sqrt(prob)
                if not flat:
                    normed = normed.reshape((self.d,) * self.N)
                branches[outcome] = (prob, normed)
        return branches

    def eval_density_matrix(
        self,
        wires: Sequence[int] | int | None = None,
        **kwargs: object,
    ) -> np.ndarray:
        r"""
        Calculate the full or reduced density matrix $\rho$ via
        `cotengra`.

        The `wires` argument allows to specify manually a subspace of
        wires that should be kept; if `wires` is specified, this
        method thus calculates a reduced density matrix. By default,
        the density matrix of all wires is calculated.

        If $A$ is the set of wires that are retained and $\bar{A}$ its
        complement, and $C$ is the set of measurement outcomes, then
        `eval_density_matrix` calculates
        $\rho = \sum_{C} \mathrm{Tr}_{\bar{A}} |\psi_C\rangle \langle
        \psi_C |$. This is done using `cotengra`, i.e. without forming
        dense statevectors.

        Args:
            wires: Optional wire index or sequence of wire indices to
                retain. Defaults to `0 .. N - 1` (full quantum density
                matrix).
            **kwargs: Additional keyword arguments forwarded to
                `cotengra.array_contract`.

        Returns:
            rho:
                Complex density matrix of shape `(d**M, d**M)`, where
                `M = len(wires)`.

        Raises:
            TypeError: If `wires` has an invalid type.
            ValueError: If `wires` is empty, contains duplicates, or
                has indices outside `0 <= wire < N`.
        """
        if wires is None:
            kept_wires = tuple(range(self.N))
        elif isinstance(wires, int) and not isinstance(wires, bool):
            kept_wires = (wires,)
        elif isinstance(wires, (tuple, list)):
            kept_wires = tuple(wires)
        else:
            raise TypeError(
                "wires must be None, an integer, or a sequence of integers."
            )

        if len(kept_wires) == 0:
            raise ValueError("wires must contain at least one wire.")
        for w in kept_wires:
            if (not isinstance(w, int)) or isinstance(w, bool):
                raise TypeError("All wire indices must be integers.")
            if not (0 <= w < self.N):
                raise ValueError(
                    "".join(
                        (
                            f"Wire {w} is out of bounds for register of ",
                            f"size N={self.N} (expected 0 <= wire < N).",
                        )
                    ),
                )
        if len(set(kept_wires)) != len(kept_wires):
            raise ValueError(
                f"wires must be unique, got duplicate in {kept_wires}."
            )
        _check_dense_tensor_limits(
            2 * len(kept_wires),
            self.d,
            "eval_density_matrix()",
        )

        bra = self.conj
        combined_G = self.G.copy()
        offset = self._next_node_id

        for u, data in bra.G.nodes(data=True):
            combined_G.add_node(u + offset, **data)
        for u, v, data in bra.G.edges(data=True):
            combined_G.add_edge(u + offset, v + offset, **data)

        for entry in self._measurements:
            uid = entry[0]
            ket_c = self.classical_frontier[uid]
            bra_c = bra.classical_frontier[uid]
            combined_G.add_edge(
                ket_c[0],
                bra_c[0] + offset,
                out_axis=ket_c[1],
                in_axis=bra_c[1],
                classical_uid=uid,
            )

        kept_set = set(kept_wires)
        for w in range(self.N):
            if w not in kept_set:
                ket_q = self.frontier[w]
                bra_q = bra.frontier[w]
                combined_G.add_edge(
                    ket_q[0],
                    bra_q[0] + offset,
                    out_axis=ket_q[1],
                    in_axis=bra_q[1],
                    wire=w,
                )

        row_legs = [self.frontier[w] for w in kept_wires]
        col_legs = [
            (bra.frontier[w][0] + offset, bra.frontier[w][1])
            for w in kept_wires
        ]
        rho = self._contract_graph(
            combined_G,
            output_legs=row_legs + col_legs,
            **kwargs,
        )
        dim = self.d ** len(kept_wires)
        return rho.reshape(dim, dim)

    def sample(
        self,
        shots: int = 1,
        *,
        rng: np.random.Generator | int | None = None,
        **kwargs: object,
    ) -> np.ndarray:
        r"""
        Sample mid-circuit measurement outcomes from the Born
        distribution.

        Contracts all quantum wires between `self` and `self.conj` via
        `cotengra` to extract the joint classical outcome probabilities
        $p(m_0, \dots, m_{K-1})$ without materializing $d^N$ state
        vectors.

        Args:
            shots: Number of independent classical trajectory samples
                (`>= 1`).
            rng: Optional `numpy.random.Generator` or integer seed for
                reproducible sampling.
            **kwargs: Additional keyword arguments forwarded to
                `cotengra.array_contract`.

        Returns:
            Integer NumPy array of shape `(shots, K)` where `K` is the
            number of mid-circuit measurements in chronological order.

        Raises:
            TypeError: If `shots` is not an integer.
            ValueError: If `shots < 1` or the register has no
                measurements.
        """
        if isinstance(shots, bool) or not isinstance(shots, int):
            raise TypeError("shots must be a positive integer.")
        if shots < 1:
            raise ValueError("shots must be >= 1.")

        num_meas = len(self._measurements)
        if num_meas == 0:
            raise ValueError(
                "".join(
                    (
                        "Register has no mid-circuit measurements to ",
                        "sample. Apply Measure(...) first.",
                    )
                ),
            )

        gen = np.random.default_rng(rng)
        if (
            num_meas > _MAX_JOINT_SAMPLE_MEAS
            or (self.d**num_meas) > _MAX_JOINT_SAMPLE_BRANCHES
        ):
            return self._sample_autoregressive(
                shots=shots,
                gen=gen,
                **kwargs,
            )

        bra = self.conj
        combined_G = self.G.copy()
        offset = self._next_node_id

        for u, data in bra.G.nodes(data=True):
            combined_G.add_node(u + offset, **data)
        for u, v, data in bra.G.edges(data=True):
            combined_G.add_edge(u + offset, v + offset, **data)

        for w in range(self.N):
            ket_q = self.frontier[w]
            bra_q = bra.frontier[w]
            combined_G.add_edge(
                ket_q[0],
                bra_q[0] + offset,
                out_axis=ket_q[1],
                in_axis=bra_q[1],
                wire=w,
            )

        delta_3 = np.zeros((self.d, self.d, self.d), dtype=np.complex128)
        for idx in range(self.d):
            delta_3[idx, idx, idx] = 1.0
        delta_3.flags.writeable = False

        next_node = self._next_node_id + bra._next_node_id
        prob_legs: list[tuple[int, int]] = []
        for entry in self._measurements:
            uid = entry[0]
            ket_c = self.classical_frontier[uid]
            bra_c = bra.classical_frontier[uid]
            combined_G.add_node(next_node, tensor=delta_3, kind="prob_diag")
            combined_G.add_edge(
                ket_c[0],
                next_node,
                out_axis=ket_c[1],
                in_axis=0,
            )
            combined_G.add_edge(
                bra_c[0] + offset,
                next_node,
                out_axis=bra_c[1],
                in_axis=1,
            )
            prob_legs.append((next_node, 2))
            next_node += 1

        prob_tensor = self._contract_graph(
            combined_G,
            output_legs=prob_legs,
            **kwargs,
        )
        probs = np.maximum(np.real(prob_tensor.reshape(-1)), 0.0)
        total_prob = float(np.sum(probs))
        if total_prob <= 0.0:
            raise ValueError("Total probability across branches is zero.")
        probs = probs / total_prob

        flat_choices = gen.choice(self.d**num_meas, size=shots, p=probs)
        unraveled = np.unravel_index(flat_choices, (self.d,) * num_meas)
        return np.column_stack(unraveled)

    def _sample_autoregressive(
        self,
        shots: int,
        gen: np.random.Generator,
        **kwargs: object,
    ) -> np.ndarray:
        """
        Sample mid-circuit measurements sequentially via the chain rule
        when `d**K` exceeds joint-tensor limits.
        """
        num_meas = len(self._measurements)
        bra = self.conj
        base_G = self.G.copy()
        offset = self._next_node_id

        for u, data in bra.G.nodes(data=True):
            base_G.add_node(u + offset, **data)
        for u, v, data in bra.G.edges(data=True):
            base_G.add_edge(u + offset, v + offset, **data)

        for w in range(self.N):
            ket_q = self.frontier[w]
            bra_q = bra.frontier[w]
            base_G.add_edge(
                ket_q[0],
                bra_q[0] + offset,
                out_axis=ket_q[1],
                in_axis=bra_q[1],
                wire=w,
            )

        delta_3 = np.zeros((self.d, self.d, self.d), dtype=np.complex128)
        for idx in range(self.d):
            delta_3[idx, idx, idx] = 1.0
        delta_3.flags.writeable = False

        basis_vecs: list[np.ndarray] = []
        for idx in range(self.d):
            vec = np.zeros(self.d, dtype=np.complex128)
            vec[idx] = 1.0
            vec.flags.writeable = False
            basis_vecs.append(vec)

        base_next_node = self._next_node_id + bra._next_node_id
        results = np.zeros((shots, num_meas), dtype=np.int64)
        prefix_groups: dict[tuple[int, ...], list[int]] = {
            (): list(range(shots)),
        }

        for step_idx in range(num_meas):
            next_groups: dict[tuple[int, ...], list[int]] = {}
            for prefix, shot_indices in prefix_groups.items():
                step_G = base_G.copy()
                cur_node = base_next_node
                prob_legs: list[tuple[int, int]] = []

                for r in range(num_meas):
                    uid = self._measurements[r][0]
                    ket_c = self.classical_frontier[uid]
                    bra_c = bra.classical_frontier[uid]

                    if r < step_idx:
                        pin_vec = basis_vecs[prefix[r]]
                        step_G.add_node(
                            cur_node,
                            tensor=pin_vec,
                            kind="postselect",
                        )
                        step_G.add_edge(
                            ket_c[0],
                            cur_node,
                            out_axis=ket_c[1],
                            in_axis=0,
                        )
                        step_G.add_node(
                            cur_node + 1,
                            tensor=pin_vec,
                            kind="postselect",
                        )
                        step_G.add_edge(
                            bra_c[0] + offset,
                            cur_node + 1,
                            out_axis=bra_c[1],
                            in_axis=0,
                        )
                        cur_node += 2
                    elif r == step_idx:
                        step_G.add_node(
                            cur_node,
                            tensor=delta_3,
                            kind="prob_diag",
                        )
                        step_G.add_edge(
                            ket_c[0],
                            cur_node,
                            out_axis=ket_c[1],
                            in_axis=0,
                        )
                        step_G.add_edge(
                            bra_c[0] + offset,
                            cur_node,
                            out_axis=bra_c[1],
                            in_axis=1,
                        )
                        prob_legs.append((cur_node, 2))
                        cur_node += 1
                    else:
                        step_G.add_edge(
                            ket_c[0],
                            bra_c[0] + offset,
                            out_axis=ket_c[1],
                            in_axis=bra_c[1],
                            classical_uid=uid,
                        )

                prob_vec = self._contract_graph(
                    step_G,
                    output_legs=prob_legs,
                    **kwargs,
                )
                probs = np.maximum(np.real(prob_vec.reshape(-1)), 0.0)
                total_prob = float(np.sum(probs))
                if total_prob <= 0.0:
                    raise ValueError(
                        "Total probability across branches is zero."
                    )
                probs = probs / total_prob

                sampled = gen.choice(
                    self.d,
                    size=len(shot_indices),
                    p=probs,
                )
                for s_pos, m_val in zip(shot_indices, sampled):
                    m_int = int(m_val)
                    results[s_pos, step_idx] = m_int
                    new_prefix = (*prefix, m_int)
                    next_groups.setdefault(new_prefix, []).append(s_pos)

            prefix_groups = next_groups

        return results

    def _apply(self, gates: CompositeGate) -> KetState:
        """
        Apply all circuit operations in `gates` to a cloned `KetState`.

        Because Python evaluates `U_n @ ... @ U_2 @ U_1 @ ket` by
        accumulating `[U_n, ..., U_2, U_1]` left-to-right into a
        `CompositeGate`, `U_1` is closest to `ket` and must be applied
        first. This method therefore iterates over `reversed(gates)`.
        """
        new_state = self.copy()
        for op in reversed(gates):
            for wire in op.wires:
                if not (0 <= wire < new_state.N):
                    raise ValueError(
                        "".join(
                            (
                                f"Gate wire {wire} is out of bounds for ",
                                f"register of size N={new_state.N} ",
                                "(expected 0 <= wire < N) in ",
                                f"{op.__class__.__name__}(wires={op.wires}).",
                            )
                        ),
                    )

            if isinstance(op, ModularGate):
                if op.d != new_state.d:
                    raise ValueError(
                        "".join(
                            (
                                f"Gate local dimension d={op.d} does not ",
                                f"match register dimension d={new_state.d} ",
                                f"in {op.__class__.__name__}",
                                f"(wires={op.wires}).",
                            )
                        ),
                    )
                mod_id = _next_meas_uid()
                for child in reversed(op.ops):
                    if isinstance(child, ModularGate):
                        sub_id: int | None = _next_meas_uid()
                        sub_label: str | None = child.nickname
                        sub_wires: tuple[int, ...] | None = child.wires
                        child_leaves = tuple(_iter_atomic_gates(child.ops))
                    else:
                        sub_id = None
                        sub_label = None
                        sub_wires = None
                        child_leaves = tuple(_iter_atomic_gates((child,)))
                    for leaf in reversed(child_leaves):
                        gate_node = new_state._alloc_node_id()
                        new_state.G.add_node(
                            gate_node,
                            tensor=leaf.tensor,
                            kind="gate",
                            wires=leaf.wires,
                            label=leaf.nickname,
                            module_id=mod_id,
                            module_label=op.nickname,
                            module_wires=op.wires,
                            submodule_id=sub_id,
                            submodule_label=sub_label,
                            submodule_wires=sub_wires,
                        )
                        for idx, wire in enumerate(leaf.wires):
                            prev_leg = new_state.frontier[wire]
                            new_state.G.add_edge(
                                prev_leg[0],
                                gate_node,
                                out_axis=prev_leg[1],
                                in_axis=leaf.L + idx,
                                wire=wire,
                            )
                            new_state.frontier[wire] = (gate_node, idx)

            elif isinstance(op, BaseGate):
                if op.d != new_state.d:
                    raise ValueError(
                        "".join(
                            (
                                f"Gate local dimension d={op.d} does not ",
                                f"match register dimension d={new_state.d} ",
                                f"in {op.__class__.__name__}",
                                f"(wires={op.wires}).",
                            )
                        ),
                    )

                gate_node = new_state._alloc_node_id()
                new_state.G.add_node(
                    gate_node,
                    tensor=op.tensor,
                    kind="gate",
                    wires=op.wires,
                    label=op.nickname,
                )
                for idx, wire in enumerate(op.wires):
                    prev_leg = new_state.frontier[wire]
                    in_axis = op.L + idx
                    out_axis = idx
                    new_state.G.add_edge(
                        prev_leg[0],
                        gate_node,
                        out_axis=prev_leg[1],
                        in_axis=in_axis,
                        wire=wire,
                    )
                    new_state.frontier[wire] = (gate_node, out_axis)

            elif isinstance(op, Measure):
                d = new_state.d
                new_meas = list(new_state._measurements)
                for wire, key in zip(op.wires, op.keys):
                    uid = _next_meas_uid()
                    meas_node = new_state._alloc_node_id()
                    prev_leg = new_state.frontier[wire]

                    if op.reset:
                        ket_zero = np.zeros(d, dtype=np.complex128)
                        ket_zero[0] = 1.0
                        ket_zero.flags.writeable = False

                        new_state.G.add_node(
                            meas_node,
                            tensor=ket_zero,
                            kind="measure",
                            wires=(wire,),
                            key=key,
                            reset=True,
                            label=f"M({key})->|0>",
                        )
                        new_state.classical_frontier[uid] = prev_leg
                        new_state.frontier[wire] = (meas_node, 0)
                    else:
                        delta_3 = np.zeros((d, d, d), dtype=np.complex128)
                        for idx in range(d):
                            delta_3[idx, idx, idx] = 1.0
                        delta_3.flags.writeable = False

                        new_state.G.add_node(
                            meas_node,
                            tensor=delta_3,
                            kind="measure",
                            wires=(wire,),
                            key=key,
                            reset=False,
                            label=f"M({key})",
                        )
                        new_state.G.add_edge(
                            prev_leg[0],
                            meas_node,
                            out_axis=prev_leg[1],
                            in_axis=2,
                            wire=wire,
                        )
                        new_state.frontier[wire] = (meas_node, 0)
                        new_state.classical_frontier[uid] = (meas_node, 1)

                    new_state.classical_keys[key] = uid
                    new_meas.append((uid, key))
                new_state._measurements = tuple(new_meas)

            elif isinstance(op, ClassicallyControlledGate):
                if op.d != new_state.d:
                    raise ValueError(
                        "".join(
                            (
                                f"Gate local dimension d={op.d} does not ",
                                f"match register dimension d={new_state.d} ",
                                f"in {op.__class__.__name__}",
                                f"(wires={op.wires}).",
                            )
                        ),
                    )
                for key in op.keys:
                    if key not in new_state.classical_keys:
                        raise ValueError(
                            "".join(
                                (
                                    f"Classical key {key!r} has not been ",
                                    "measured prior to classical control.",
                                )
                            ),
                        )

                k = len(op.keys)
                d = new_state.d
                ctrl_node = new_state._alloc_node_id()
                new_state.G.add_node(
                    ctrl_node,
                    tensor=op.tensor,
                    kind="classical_control",
                    wires=op.wires,
                    keys=op.keys,
                    label=op.label,
                )

                delta_3 = np.zeros((d, d, d), dtype=np.complex128)
                for idx in range(d):
                    delta_3[idx, idx, idx] = 1.0
                delta_3.flags.writeable = False

                for c_idx, key in enumerate(op.keys):
                    uid = new_state.classical_keys[key]
                    prev_c = new_state.classical_frontier[uid]
                    copy_node = new_state._alloc_node_id()
                    new_state.G.add_node(
                        copy_node,
                        tensor=delta_3,
                        kind="classical_copy",
                    )
                    new_state.G.add_edge(
                        prev_c[0],
                        copy_node,
                        out_axis=prev_c[1],
                        in_axis=0,
                        classical_uid=uid,
                    )
                    new_state.G.add_edge(
                        copy_node,
                        ctrl_node,
                        out_axis=1,
                        in_axis=c_idx,
                        classical_uid=uid,
                    )
                    new_state.classical_frontier[uid] = (copy_node, 2)

                for q_idx, wire in enumerate(op.wires):
                    prev_q = new_state.frontier[wire]
                    in_q_ax = k + op.L + q_idx
                    out_q_ax = k + q_idx
                    new_state.G.add_edge(
                        prev_q[0],
                        ctrl_node,
                        out_axis=prev_q[1],
                        in_axis=in_q_ax,
                        wire=wire,
                    )
                    new_state.frontier[wire] = (ctrl_node, out_q_ax)

            else:
                raise TypeError(
                    f"Unsupported circuit operation: {type(op).__name__}."
                )

        new_state._circuit = gates.ops + new_state._circuit
        return new_state

    def _braket(
        self,
        lhs: BraState,
        **kwargs: object,
    ) -> complex:
        r"""
        Contract $\langle\text{lhs}|\text{self}\rangle$ and return the
        scalar inner product (or $\mathrm{Tr}(\rho O)$ when matching
        classical-record legs are present).
        """
        if (lhs.N != self.N) or (lhs.d != self.d):
            raise ValueError(
                "".join(
                    (
                        "Cannot form braket between registers with ",
                        f"different dimensions: (N={lhs.N}, d={lhs.d}) ",
                        f"vs (N={self.N}, d={self.d}).",
                    )
                ),
            )

        lhs_uids = tuple(entry[0] for entry in lhs._measurements)
        rhs_uids = tuple(entry[0] for entry in self._measurements)
        if lhs_uids != rhs_uids:
            raise ValueError(
                "".join(
                    (
                        "Cannot form braket between registers with ",
                        "mismatched mid-circuit measurement histories.",
                    )
                ),
            )

        combined_G = lhs.G.copy()
        offset = lhs._next_node_id

        for u, data in self.G.nodes(data=True):
            combined_G.add_node(u + offset, **data)
        for u, v, data in self.G.edges(data=True):
            combined_G.add_edge(u + offset, v + offset, **data)

        for wire in range(self.N):
            bra_leg = lhs.frontier[wire]
            ket_leg = self.frontier[wire]
            combined_G.add_edge(
                bra_leg[0],
                ket_leg[0] + offset,
                out_axis=bra_leg[1],
                in_axis=ket_leg[1],
                wire=wire,
            )

        for uid in rhs_uids:
            bra_c = lhs.classical_frontier[uid]
            ket_c = self.classical_frontier[uid]
            combined_G.add_edge(
                bra_c[0],
                ket_c[0] + offset,
                out_axis=bra_c[1],
                in_axis=ket_c[1],
                classical_uid=uid,
            )

        scalar_arr = self._contract_graph(
            combined_G,
            output_legs=(),
            **kwargs,
        )
        return complex(scalar_arr.item())

    def _outer(self, rhs: BraState) -> BaseGate | CompositeGate:
        """
        Calculate the outer product `self @ rhs` (|self><rhs|).

        Args:
            rhs: Bra state to form the outer product with.

        Returns:
            A BaseGate if neither state carries a quantum circuit,
            or a CompositeGate if either or both states carry a circuit.

        Raises:
            ValueError: If registers have different N or d, or if
                either register contains mid-circuit measurements.
        """
        if (rhs.N != self.N) or (rhs.d != self.d):
            raise ValueError(
                "".join(
                    (
                        "Cannot form outer product between registers with ",
                        f"different dimensions: (N={self.N}, d={self.d}) ",
                        f"vs (N={rhs.N}, d={rhs.d}).",
                    )
                ),
            )
        if len(self._measurements) > 0 or len(rhs._measurements) > 0:
            raise ValueError(
                "".join(
                    (
                        "Cannot form outer product |ket><bra| when ",
                        "mid-circuit measurements are present.",
                    )
                ),
            )

        _check_dense_tensor_limits(2 * self.N, self.d, "outer product")

        v0 = self._init_state.eval()
        w0 = rhs._init_state.eval()
        mat0 = np.outer(v0, w0)
        g0 = BaseGate(
            wires=tuple(range(self.N)),
            mat=mat0,
            is_unitary=False,
            _validate_unitary=False,
        )

        if len(self._circuit) == 0 and len(rhs._circuit) == 0:
            return g0

        return CompositeGate(*self._circuit, g0, *rhs._circuit)

    @overload
    def __matmul__(self, rhs: BraState) -> BaseGate | CompositeGate: ...

    @overload
    def __matmul__(self, rhs: object) -> BaseGate | CompositeGate: ...

    def __matmul__(self, rhs: object) -> BaseGate | CompositeGate:
        r"""
        Compute outer product with `BraState`, returning an operator.

        Raises:
            RuntimeError: A `RuntimeError` is raised if an object of
                non-`BraState` type is passed, since operations of the
                form $|\psi\rangle U$ are not mathematically defined for
                operators $U$.
        """
        if isinstance(rhs, BraState):
            return self._outer(rhs)

        raise RuntimeError(
            "".join(
                (
                    "KetState.__matmul__ received an object of type",
                    f"{type(rhs)}. A ket state cannot be acted upon from the",
                    "right-hand side by anything that is not a bra-state.",
                )
            )
        )

    @overload
    def __rmatmul__(self, lhs: CompositeGate) -> KetState: ...

    @overload
    def __rmatmul__(self, lhs: CircuitOp) -> KetState: ...

    @overload
    def __rmatmul__(self, lhs: BraState) -> complex: ...

    def __rmatmul__(self, lhs: object) -> KetState | complex:
        """
        Handle `CompositeGate @ KetState`, `CircuitOp @ KetState`, and
        `BraState @ KetState`.
        """
        if isinstance(lhs, ModularGate):
            return self._apply(CompositeGate(lhs))
        if isinstance(lhs, CompositeGate):
            return self._apply(lhs)
        if isinstance(lhs, CircuitOp):
            return self._apply(CompositeGate(lhs))
        if isinstance(lhs, BraState):
            return self._braket(lhs)

        return NotImplemented

    def __init__(
        self,
        N: int,
        d: int = 2,
        psi0: np.ndarray | None = None,
        normalize: bool = False,
    ) -> None:
        super().__init__(N=N, d=d, psi0=psi0, normalize=normalize)

eval

eval(
    flat: bool = True,
    *,
    outcomes: Mapping[int | str, int]
    | Sequence[int]
    | int
    | None = None,
    normalize: bool = True,
    **kwargs: object,
) -> np.ndarray

Contract the ket tensor network and return \(|\psi\rangle\).

When mid-circuit measurements are present, outcomes can be used to select a trajectory to contract by specifying the desired measurement outcomes.

Parameters:

Name Type Description Default
flat bool

If True, return a 1D complex vector of shape (d**N,). If False, return shape (d,) * N.

True
outcomes Mapping[int | str, int] | Sequence[int] | int | None

Optional classical outcomes to post-select, given as a chronological sequence (m_0, ..., m_{K-1}), an unambiguous {key: outcome} mapping, or a single int when \(K = 1\).

None
normalize bool

If True (default), normalize the post-selected branch and raise ValueError if its probability is zero. If False, return the raw unnormalized Kraus vector \(|\tilde{\psi}_{\mathbf{m}}\rangle\).

True
**kwargs object

Additional keyword arguments forwarded to cotengra.array_contract.

{}

Returns:

Type Description
ndarray

Contracted state array of shape (d**N,) or (d,) * N.

Raises:

Type Description
TypeError

If outcomes or normalize has an invalid type.

ValueError

If unpinned measurements exist, outcomes do not match the measurement records, or normalize=True on a zero-probability branch.

Source code in src/quantum_emotion/core.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
def eval(
    self,
    flat: bool = True,
    *,
    outcomes: Mapping[int | str, int] | Sequence[int] | int | None = None,
    normalize: bool = True,
    **kwargs: object,
) -> np.ndarray:
    r"""
    Contract the ket tensor network and return $|\psi\rangle$.

    When mid-circuit measurements are present, `outcomes` can be
    used to select a trajectory to contract by specifying the
    desired measurement outcomes.

    Args:
        flat: If `True`, return a 1D complex vector of shape
            `(d**N,)`. If `False`, return shape `(d,) * N`.
        outcomes: Optional classical outcomes to post-select, given
            as a chronological sequence `(m_0, ..., m_{K-1})`, an
            unambiguous `{key: outcome}` mapping, or a single `int`
            when $K = 1$.
        normalize: If `True` (default), normalize the post-selected
            branch and raise `ValueError` if its probability is
            zero. If `False`, return the raw unnormalized Kraus
            vector $|\tilde{\psi}_{\mathbf{m}}\rangle$.
        **kwargs: Additional keyword arguments forwarded to
            `cotengra.array_contract`.

    Returns:
        Contracted state array of shape `(d**N,)` or `(d,) * N`.

    Raises:
        TypeError: If `outcomes` or `normalize` has an invalid type.
        ValueError: If unpinned measurements exist, `outcomes` do
            not match the measurement records, or `normalize=True`
            on a zero-probability branch.
    """
    if not isinstance(flat, bool):
        raise TypeError("flat must be a boolean.")
    if not isinstance(normalize, bool):
        raise TypeError("normalize must be a boolean.")

    if outcomes is None:
        return super().eval(flat=flat, **kwargs)

    outcome_tuple = self._resolve_outcomes(outcomes)
    if len(outcome_tuple) == 0:
        return super().eval(flat=flat, **kwargs)

    _check_dense_tensor_limits(self.N, self.d, "eval()")
    pinned_G = self.G.copy()
    next_node = self._next_node_id
    for entry, m_val in zip(self._measurements, outcome_tuple):
        uid = entry[0]
        c_leg = self.classical_frontier[uid]
        basis_vec = np.zeros(self.d, dtype=np.complex128)
        basis_vec[m_val] = 1.0
        basis_vec.flags.writeable = False

        pinned_G.add_node(next_node, tensor=basis_vec, kind="postselect")
        pinned_G.add_edge(
            c_leg[0],
            next_node,
            out_axis=c_leg[1],
            in_axis=0,
            classical_uid=uid,
        )
        next_node += 1

    output_legs = [self.frontier[w] for w in range(self.N)]
    state = self._contract_graph(
        pinned_G,
        output_legs=output_legs,
        **kwargs,
    )
    if normalize:
        norm = float(np.linalg.norm(state))
        if np.isclose(norm, 0.0, atol=1e-15):
            raise ValueError(
                "".join(
                    (
                        f"Post-selected outcome {outcome_tuple} ",
                        "has zero probability.",
                    )
                ),
            )
        state = state / norm

    if flat:
        return state.reshape(self.d**self.N)
    return state.reshape((self.d,) * self.N)

eval_branches

eval_branches(
    flat: bool = True,
    *,
    tol: float = 1e-12,
    **kwargs: object,
) -> dict[tuple[int, ...], tuple[float, np.ndarray]]

Evaluate all non-zero classical measurement trajectories.

Parameters:

Name Type Description Default
flat bool

If True, format each branch state as shape (d**N,). If False, format as (d,) * N.

True
tol float

Minimum Born probability threshold for including a trajectory in the returned dictionary.

1e-12
**kwargs object

Additional keyword arguments forwarded to cotengra.array_contract.

{}

Returns:

Name Type Description
branches dict[tuple[int, ...], tuple[float, ndarray]]

Dictionary {outcomes_tuple: (probability, state)} mapping each non-zero classical outcome tuple to its Born probability \(p(\mathbf{m})\) and normalized state \(|\psi_{\mathbf{m}}\rangle\).

Source code in src/quantum_emotion/core.py
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
def eval_branches(
    self,
    flat: bool = True,
    *,
    tol: float = 1e-12,
    **kwargs: object,
) -> dict[tuple[int, ...], tuple[float, np.ndarray]]:
    r"""
    Evaluate all non-zero classical measurement trajectories.

    Args:
        flat: If `True`, format each branch state as shape
            `(d**N,)`. If `False`, format as `(d,) * N`.
        tol: Minimum Born probability threshold for including a
            trajectory in the returned dictionary.
        **kwargs: Additional keyword arguments forwarded to
            `cotengra.array_contract`.

    Returns:
        branches:
            Dictionary `{outcomes_tuple: (probability, state)}`
            mapping each non-zero classical outcome tuple to its
            Born probability $p(\mathbf{m})$ and normalized state
            $|\psi_{\mathbf{m}}\rangle$.
    """
    if not isinstance(flat, bool):
        raise TypeError("flat must be a boolean.")
    if (
        isinstance(tol, bool)
        or not isinstance(tol, (int, float, np.number))
        or isinstance(tol, (complex, np.complexfloating))
    ):
        raise TypeError("tol must be a real number.")
    tol_val = float(tol)
    if (not np.isfinite(tol_val)) or tol_val < 0.0:
        raise ValueError("tol must be a finite non-negative number.")

    classical_legs = [
        self.classical_frontier[entry[0]] for entry in self._measurements
    ]
    quantum_legs = [self.frontier[w] for w in range(self.N)]
    num_meas = len(classical_legs)
    _check_dense_tensor_limits(
        num_meas + self.N,
        self.d,
        "eval_branches()",
    )

    full_tensor = self._contract_graph(
        self.G,
        output_legs=classical_legs + quantum_legs,
        **kwargs,
    )
    reshaped = full_tensor.reshape(self.d**num_meas, self.d**self.N)

    branches: dict[tuple[int, ...], tuple[float, np.ndarray]] = {}
    outcomes_iter = itertools.product(range(self.d), repeat=num_meas)
    for idx, outcome in enumerate(outcomes_iter):
        branch_vec = reshaped[idx]
        prob = float(np.real(np.vdot(branch_vec, branch_vec)))
        if prob > tol_val:
            normed = branch_vec / np.sqrt(prob)
            if not flat:
                normed = normed.reshape((self.d,) * self.N)
            branches[outcome] = (prob, normed)
    return branches

eval_density_matrix

eval_density_matrix(
    wires: Sequence[int] | int | None = None,
    **kwargs: object,
) -> np.ndarray

Calculate the full or reduced density matrix \(\rho\) via cotengra.

The wires argument allows to specify manually a subspace of wires that should be kept; if wires is specified, this method thus calculates a reduced density matrix. By default, the density matrix of all wires is calculated.

If \(A\) is the set of wires that are retained and \(\bar{A}\) its complement, and \(C\) is the set of measurement outcomes, then eval_density_matrix calculates \(\rho = \sum_{C} \mathrm{Tr}_{\bar{A}} |\psi_C\rangle \langle \psi_C |\). This is done using cotengra, i.e. without forming dense statevectors.

Parameters:

Name Type Description Default
wires Sequence[int] | int | None

Optional wire index or sequence of wire indices to retain. Defaults to 0 .. N - 1 (full quantum density matrix).

None
**kwargs object

Additional keyword arguments forwarded to cotengra.array_contract.

{}

Returns:

Name Type Description
rho ndarray

Complex density matrix of shape (d**M, d**M), where M = len(wires).

Raises:

Type Description
TypeError

If wires has an invalid type.

ValueError

If wires is empty, contains duplicates, or has indices outside 0 <= wire < N.

Source code in src/quantum_emotion/core.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
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
def eval_density_matrix(
    self,
    wires: Sequence[int] | int | None = None,
    **kwargs: object,
) -> np.ndarray:
    r"""
    Calculate the full or reduced density matrix $\rho$ via
    `cotengra`.

    The `wires` argument allows to specify manually a subspace of
    wires that should be kept; if `wires` is specified, this
    method thus calculates a reduced density matrix. By default,
    the density matrix of all wires is calculated.

    If $A$ is the set of wires that are retained and $\bar{A}$ its
    complement, and $C$ is the set of measurement outcomes, then
    `eval_density_matrix` calculates
    $\rho = \sum_{C} \mathrm{Tr}_{\bar{A}} |\psi_C\rangle \langle
    \psi_C |$. This is done using `cotengra`, i.e. without forming
    dense statevectors.

    Args:
        wires: Optional wire index or sequence of wire indices to
            retain. Defaults to `0 .. N - 1` (full quantum density
            matrix).
        **kwargs: Additional keyword arguments forwarded to
            `cotengra.array_contract`.

    Returns:
        rho:
            Complex density matrix of shape `(d**M, d**M)`, where
            `M = len(wires)`.

    Raises:
        TypeError: If `wires` has an invalid type.
        ValueError: If `wires` is empty, contains duplicates, or
            has indices outside `0 <= wire < N`.
    """
    if wires is None:
        kept_wires = tuple(range(self.N))
    elif isinstance(wires, int) and not isinstance(wires, bool):
        kept_wires = (wires,)
    elif isinstance(wires, (tuple, list)):
        kept_wires = tuple(wires)
    else:
        raise TypeError(
            "wires must be None, an integer, or a sequence of integers."
        )

    if len(kept_wires) == 0:
        raise ValueError("wires must contain at least one wire.")
    for w in kept_wires:
        if (not isinstance(w, int)) or isinstance(w, bool):
            raise TypeError("All wire indices must be integers.")
        if not (0 <= w < self.N):
            raise ValueError(
                "".join(
                    (
                        f"Wire {w} is out of bounds for register of ",
                        f"size N={self.N} (expected 0 <= wire < N).",
                    )
                ),
            )
    if len(set(kept_wires)) != len(kept_wires):
        raise ValueError(
            f"wires must be unique, got duplicate in {kept_wires}."
        )
    _check_dense_tensor_limits(
        2 * len(kept_wires),
        self.d,
        "eval_density_matrix()",
    )

    bra = self.conj
    combined_G = self.G.copy()
    offset = self._next_node_id

    for u, data in bra.G.nodes(data=True):
        combined_G.add_node(u + offset, **data)
    for u, v, data in bra.G.edges(data=True):
        combined_G.add_edge(u + offset, v + offset, **data)

    for entry in self._measurements:
        uid = entry[0]
        ket_c = self.classical_frontier[uid]
        bra_c = bra.classical_frontier[uid]
        combined_G.add_edge(
            ket_c[0],
            bra_c[0] + offset,
            out_axis=ket_c[1],
            in_axis=bra_c[1],
            classical_uid=uid,
        )

    kept_set = set(kept_wires)
    for w in range(self.N):
        if w not in kept_set:
            ket_q = self.frontier[w]
            bra_q = bra.frontier[w]
            combined_G.add_edge(
                ket_q[0],
                bra_q[0] + offset,
                out_axis=ket_q[1],
                in_axis=bra_q[1],
                wire=w,
            )

    row_legs = [self.frontier[w] for w in kept_wires]
    col_legs = [
        (bra.frontier[w][0] + offset, bra.frontier[w][1])
        for w in kept_wires
    ]
    rho = self._contract_graph(
        combined_G,
        output_legs=row_legs + col_legs,
        **kwargs,
    )
    dim = self.d ** len(kept_wires)
    return rho.reshape(dim, dim)

sample

sample(
    shots: int = 1,
    *,
    rng: Generator | int | None = None,
    **kwargs: object,
) -> np.ndarray

Sample mid-circuit measurement outcomes from the Born distribution.

Contracts all quantum wires between self and self.conj via cotengra to extract the joint classical outcome probabilities \(p(m_0, \dots, m_{K-1})\) without materializing \(d^N\) state vectors.

Parameters:

Name Type Description Default
shots int

Number of independent classical trajectory samples (>= 1).

1
rng Generator | int | None

Optional numpy.random.Generator or integer seed for reproducible sampling.

None
**kwargs object

Additional keyword arguments forwarded to cotengra.array_contract.

{}

Returns:

Type Description
ndarray

Integer NumPy array of shape (shots, K) where K is the

ndarray

number of mid-circuit measurements in chronological order.

Raises:

Type Description
TypeError

If shots is not an integer.

ValueError

If shots < 1 or the register has no measurements.

Source code in src/quantum_emotion/core.py
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
def sample(
    self,
    shots: int = 1,
    *,
    rng: np.random.Generator | int | None = None,
    **kwargs: object,
) -> np.ndarray:
    r"""
    Sample mid-circuit measurement outcomes from the Born
    distribution.

    Contracts all quantum wires between `self` and `self.conj` via
    `cotengra` to extract the joint classical outcome probabilities
    $p(m_0, \dots, m_{K-1})$ without materializing $d^N$ state
    vectors.

    Args:
        shots: Number of independent classical trajectory samples
            (`>= 1`).
        rng: Optional `numpy.random.Generator` or integer seed for
            reproducible sampling.
        **kwargs: Additional keyword arguments forwarded to
            `cotengra.array_contract`.

    Returns:
        Integer NumPy array of shape `(shots, K)` where `K` is the
        number of mid-circuit measurements in chronological order.

    Raises:
        TypeError: If `shots` is not an integer.
        ValueError: If `shots < 1` or the register has no
            measurements.
    """
    if isinstance(shots, bool) or not isinstance(shots, int):
        raise TypeError("shots must be a positive integer.")
    if shots < 1:
        raise ValueError("shots must be >= 1.")

    num_meas = len(self._measurements)
    if num_meas == 0:
        raise ValueError(
            "".join(
                (
                    "Register has no mid-circuit measurements to ",
                    "sample. Apply Measure(...) first.",
                )
            ),
        )

    gen = np.random.default_rng(rng)
    if (
        num_meas > _MAX_JOINT_SAMPLE_MEAS
        or (self.d**num_meas) > _MAX_JOINT_SAMPLE_BRANCHES
    ):
        return self._sample_autoregressive(
            shots=shots,
            gen=gen,
            **kwargs,
        )

    bra = self.conj
    combined_G = self.G.copy()
    offset = self._next_node_id

    for u, data in bra.G.nodes(data=True):
        combined_G.add_node(u + offset, **data)
    for u, v, data in bra.G.edges(data=True):
        combined_G.add_edge(u + offset, v + offset, **data)

    for w in range(self.N):
        ket_q = self.frontier[w]
        bra_q = bra.frontier[w]
        combined_G.add_edge(
            ket_q[0],
            bra_q[0] + offset,
            out_axis=ket_q[1],
            in_axis=bra_q[1],
            wire=w,
        )

    delta_3 = np.zeros((self.d, self.d, self.d), dtype=np.complex128)
    for idx in range(self.d):
        delta_3[idx, idx, idx] = 1.0
    delta_3.flags.writeable = False

    next_node = self._next_node_id + bra._next_node_id
    prob_legs: list[tuple[int, int]] = []
    for entry in self._measurements:
        uid = entry[0]
        ket_c = self.classical_frontier[uid]
        bra_c = bra.classical_frontier[uid]
        combined_G.add_node(next_node, tensor=delta_3, kind="prob_diag")
        combined_G.add_edge(
            ket_c[0],
            next_node,
            out_axis=ket_c[1],
            in_axis=0,
        )
        combined_G.add_edge(
            bra_c[0] + offset,
            next_node,
            out_axis=bra_c[1],
            in_axis=1,
        )
        prob_legs.append((next_node, 2))
        next_node += 1

    prob_tensor = self._contract_graph(
        combined_G,
        output_legs=prob_legs,
        **kwargs,
    )
    probs = np.maximum(np.real(prob_tensor.reshape(-1)), 0.0)
    total_prob = float(np.sum(probs))
    if total_prob <= 0.0:
        raise ValueError("Total probability across branches is zero.")
    probs = probs / total_prob

    flat_choices = gen.choice(self.d**num_meas, size=shots, p=probs)
    unraveled = np.unravel_index(flat_choices, (self.d,) * num_meas)
    return np.column_stack(unraveled)

__matmul__

__matmul__(rhs: BraState) -> BaseGate | CompositeGate
__matmul__(rhs: object) -> BaseGate | CompositeGate
__matmul__(rhs: object) -> BaseGate | CompositeGate

Compute outer product with BraState, returning an operator.

Raises:

Type Description
RuntimeError

A RuntimeError is raised if an object of non-BraState type is passed, since operations of the form \(|\psi\rangle U\) are not mathematically defined for operators \(U\).

Source code in src/quantum_emotion/core.py
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
def __matmul__(self, rhs: object) -> BaseGate | CompositeGate:
    r"""
    Compute outer product with `BraState`, returning an operator.

    Raises:
        RuntimeError: A `RuntimeError` is raised if an object of
            non-`BraState` type is passed, since operations of the
            form $|\psi\rangle U$ are not mathematically defined for
            operators $U$.
    """
    if isinstance(rhs, BraState):
        return self._outer(rhs)

    raise RuntimeError(
        "".join(
            (
                "KetState.__matmul__ received an object of type",
                f"{type(rhs)}. A ket state cannot be acted upon from the",
                "right-hand side by anything that is not a bra-state.",
            )
        )
    )

__rmatmul__

__rmatmul__(lhs: CompositeGate) -> KetState
__rmatmul__(lhs: CircuitOp) -> KetState
__rmatmul__(lhs: BraState) -> complex
__rmatmul__(lhs: object) -> KetState | complex

Handle CompositeGate @ KetState, CircuitOp @ KetState, and BraState @ KetState.

Source code in src/quantum_emotion/core.py
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
def __rmatmul__(self, lhs: object) -> KetState | complex:
    """
    Handle `CompositeGate @ KetState`, `CircuitOp @ KetState`, and
    `BraState @ KetState`.
    """
    if isinstance(lhs, ModularGate):
        return self._apply(CompositeGate(lhs))
    if isinstance(lhs, CompositeGate):
        return self._apply(lhs)
    if isinstance(lhs, CircuitOp):
        return self._apply(CompositeGate(lhs))
    if isinstance(lhs, BraState):
        return self._braket(lhs)

    return NotImplemented

BraState

Bases: CoreRegister

Bra state register \(\langle\psi|\).

A BraState stores complex-conjugated initial/adjoint tensors in self.G and is acted upon by BaseGate operators from the right-hand side (bra @ gate or bra @ composite_gate).

Source code in src/quantum_emotion/core.py
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
class BraState(CoreRegister):
    r"""
    Bra state register $\langle\psi|$.

    A `BraState` stores complex-conjugated initial/adjoint tensors in
    `self.G` and is acted upon by `BaseGate` operators from the
    right-hand side (`bra @ gate` or `bra @ composite_gate`).
    """

    _conjugate_init: ClassVar[bool] = True

    def eval(
        self,
        flat: bool = True,
        **kwargs: object,
    ) -> np.ndarray:
        r"""
        Contract the bra tensor network and return $\langle\psi|$.
        """
        return super().eval(flat=flat, **kwargs)

    def _apply(self, gates: CompositeGate) -> BraState:
        r"""
        Apply all `BaseGate` operations in `gates` from the right to a
        cloned bra.

        In `bra @ U_1 @ U_2 @ ... @ U_n`, `U_1` acts first on `bra`.
        This method iterates over `gates` in forward order and connects
        each gate's output (row) axes `0 .. L - 1` to
        `new_state.frontier` without complex-conjugating `U_k`, leaving
        its input (column) axes `L .. 2L - 1` as the new open frontier.
        Consequently, `(bra @ U) @ ket` directly evaluates
        $\langle\text{bra}|U|\text{ket}\rangle$.
        """
        for op in gates:
            if not isinstance(op, (BaseGate, ModularGate)):
                raise TypeError(
                    "".join(
                        (
                            "Mid-circuit measurements and classical ",
                            "controls cannot act on a BraState from the ",
                            "right.",
                        )
                    ),
                )

        new_state = self.copy()
        for gate in gates:
            assert isinstance(gate, (BaseGate, ModularGate))
            for wire in gate.wires:
                if not (0 <= wire < new_state.N):
                    raise ValueError(
                        "".join(
                            (
                                f"Gate wire {wire} is out of bounds for ",
                                f"register of size N={new_state.N} ",
                                "(expected 0 <= wire < N) in ",
                                f"{gate.__class__.__name__}",
                                f"(wires={gate.wires}).",
                            )
                        ),
                    )
            if gate.d != new_state.d:
                raise ValueError(
                    "".join(
                        (
                            f"Gate local dimension d={gate.d} does not ",
                            f"match register dimension d={new_state.d} ",
                            f"in {gate.__class__.__name__}",
                            f"(wires={gate.wires}).",
                        )
                    ),
                )

            if isinstance(gate, ModularGate):
                mod_id = _next_meas_uid()
                for child in gate.ops:
                    if isinstance(child, ModularGate):
                        sub_id: int | None = _next_meas_uid()
                        sub_label: str | None = child.nickname
                        sub_wires: tuple[int, ...] | None = child.wires
                        child_leaves = tuple(_iter_atomic_gates(child.ops))
                    else:
                        sub_id = None
                        sub_label = None
                        sub_wires = None
                        child_leaves = tuple(_iter_atomic_gates((child,)))
                    for leaf in child_leaves:
                        gate_node = new_state._alloc_node_id()
                        new_state.G.add_node(
                            gate_node,
                            tensor=leaf.tensor,
                            kind="gate",
                            wires=leaf.wires,
                            label=leaf.nickname,
                            module_id=mod_id,
                            module_label=gate.nickname,
                            module_wires=gate.wires,
                            submodule_id=sub_id,
                            submodule_label=sub_label,
                            submodule_wires=sub_wires,
                        )
                        for idx, wire in enumerate(leaf.wires):
                            prev_leg = new_state.frontier[wire]
                            new_state.G.add_edge(
                                prev_leg[0],
                                gate_node,
                                out_axis=prev_leg[1],
                                in_axis=idx,
                                wire=wire,
                            )
                            new_state.frontier[wire] = (
                                gate_node,
                                leaf.L + idx,
                            )
                continue

            gate_node = new_state._alloc_node_id()
            new_state.G.add_node(
                gate_node,
                tensor=gate.tensor,
                kind="gate",
                wires=gate.wires,
                label=gate.nickname,
            )
            for idx, wire in enumerate(gate.wires):
                prev_leg = new_state.frontier[wire]
                row_axis = idx
                col_axis = gate.L + idx
                new_state.G.add_edge(
                    prev_leg[0],
                    gate_node,
                    out_axis=prev_leg[1],
                    in_axis=row_axis,
                    wire=wire,
                )
                new_state.frontier[wire] = (gate_node, col_axis)

        if len(self._measurements) == 0:
            new_state._circuit = self._circuit + gates.ops
        return new_state

    @overload
    def __matmul__(self, rhs: CompositeGate) -> BraState: ...

    @overload
    def __matmul__(self, rhs: BaseGate) -> BraState: ...

    @overload
    def __matmul__(self, rhs: KetState) -> complex: ...

    def __matmul__(self, rhs: object) -> BraState | complex:
        """
        Handle `BraState @ BaseGate` and `BraState @ CompositeGate`.

        When `rhs` is a `KetState` (`bra @ ket`), returns
        `NotImplemented` so Python dispatches to
        `KetState.__rmatmul__` -> `ket._braket(bra)`.
        """
        if isinstance(rhs, CompositeGate):
            return self._apply(rhs)
        if isinstance(rhs, CircuitOp):
            return self._apply(CompositeGate(rhs))

        return NotImplemented

    def __rmatmul__(self, lhs: object) -> BaseGate | CompositeGate:
        """
        Handle `ket @ bra` if dispatched via `KetState.__matmul__`.
        """
        if isinstance(lhs, KetState):
            return lhs._outer(self)

        raise RuntimeError(
            "A bra state cannot be acted upon from the left-hand side!",
        )

    def __init__(
        self,
        N: int,
        d: int = 2,
        psi0: np.ndarray | None = None,
        normalize: bool = False,
    ) -> None:
        super().__init__(N=N, d=d, psi0=psi0, normalize=normalize)

eval

eval(flat: bool = True, **kwargs: object) -> np.ndarray

Contract the bra tensor network and return \(\langle\psi|\).

Source code in src/quantum_emotion/core.py
1203
1204
1205
1206
1207
1208
1209
1210
1211
def eval(
    self,
    flat: bool = True,
    **kwargs: object,
) -> np.ndarray:
    r"""
    Contract the bra tensor network and return $\langle\psi|$.
    """
    return super().eval(flat=flat, **kwargs)

__matmul__

__matmul__(rhs: CompositeGate) -> BraState
__matmul__(rhs: BaseGate) -> BraState
__matmul__(rhs: KetState) -> complex
__matmul__(rhs: object) -> BraState | complex

Handle BraState @ BaseGate and BraState @ CompositeGate.

When rhs is a KetState (bra @ ket), returns NotImplemented so Python dispatches to KetState.__rmatmul__ -> ket._braket(bra).

Source code in src/quantum_emotion/core.py
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
def __matmul__(self, rhs: object) -> BraState | complex:
    """
    Handle `BraState @ BaseGate` and `BraState @ CompositeGate`.

    When `rhs` is a `KetState` (`bra @ ket`), returns
    `NotImplemented` so Python dispatches to
    `KetState.__rmatmul__` -> `ket._braket(bra)`.
    """
    if isinstance(rhs, CompositeGate):
        return self._apply(rhs)
    if isinstance(rhs, CircuitOp):
        return self._apply(CompositeGate(rhs))

    return NotImplemented

__rmatmul__

__rmatmul__(lhs: object) -> BaseGate | CompositeGate

Handle ket @ bra if dispatched via KetState.__matmul__.

Source code in src/quantum_emotion/core.py
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
def __rmatmul__(self, lhs: object) -> BaseGate | CompositeGate:
    """
    Handle `ket @ bra` if dispatched via `KetState.__matmul__`.
    """
    if isinstance(lhs, KetState):
        return lhs._outer(self)

    raise RuntimeError(
        "A bra state cannot be acted upon from the left-hand side!",
    )

CircuitOp

Bases: ABC

Abstract base class for @-composable quantum circuit operations.

Subclassed by BaseGate (pure matrix operators on qudit wires), Measure (computational-basis mid-circuit measurements), and ClassicallyControlledGate (gates conditioned on classical measurement records).

Source code in src/quantum_emotion/core.py
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
class CircuitOp(ABC):
    """
    Abstract base class for `@`-composable quantum circuit operations.

    Subclassed by `BaseGate` (pure matrix operators on qudit wires),
    `Measure` (computational-basis mid-circuit measurements), and
    `ClassicallyControlledGate` (gates conditioned on classical
    measurement records).
    """

    wires: tuple[int, ...]
    """
    Zero-based quantum wire indices acted upon by this operation.
    """
    L: int
    """
    Number of quantum wires acted upon by this operation.
    """
    nickname: str
    """
    Compact display label used in circuit diagrams.
    """

    @overload
    def __matmul__(self, rhs: CircuitOp) -> CompositeGate: ...

    @overload
    def __matmul__(self, rhs: CompositeGate) -> CompositeGate: ...

    def __matmul__(self, rhs: object) -> CompositeGate:
        """
        Compose operations via `@`. An operation with the types
        `CircuitOp @ KetState` is delegated to `KetState.__rmatmul__`
        by returning `NotImplemented`.
        """
        if isinstance(rhs, ModularGate):
            return CompositeGate._from_validated_ops((self, rhs))
        if isinstance(rhs, CompositeGate):
            return CompositeGate._from_validated_ops((self, *rhs.ops))
        if isinstance(rhs, CircuitOp):
            return CompositeGate._from_validated_ops((self, rhs))

        return NotImplemented

wires instance-attribute

wires: tuple[int, ...]

Zero-based quantum wire indices acted upon by this operation.

L instance-attribute

L: int

Number of quantum wires acted upon by this operation.

nickname instance-attribute

nickname: str

Compact display label used in circuit diagrams.

__matmul__

__matmul__(rhs: CircuitOp) -> CompositeGate
__matmul__(rhs: CompositeGate) -> CompositeGate
__matmul__(rhs: object) -> CompositeGate

Compose operations via @. An operation with the types CircuitOp @ KetState is delegated to KetState.__rmatmul__ by returning NotImplemented.

Source code in src/quantum_emotion/core.py
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
def __matmul__(self, rhs: object) -> CompositeGate:
    """
    Compose operations via `@`. An operation with the types
    `CircuitOp @ KetState` is delegated to `KetState.__rmatmul__`
    by returning `NotImplemented`.
    """
    if isinstance(rhs, ModularGate):
        return CompositeGate._from_validated_ops((self, rhs))
    if isinstance(rhs, CompositeGate):
        return CompositeGate._from_validated_ops((self, *rhs.ops))
    if isinstance(rhs, CircuitOp):
        return CompositeGate._from_validated_ops((self, rhs))

    return NotImplemented

BaseGate

Bases: CircuitOp

Base class for quantum gates.

Holds the computational basis matrix representation self.mat of size (d**L, d**L), its reshaped rank-2L tensor self.tensor of shape (d,) * (2 * L), and the 0-based self.wires tuple of length L.

Source code in src/quantum_emotion/core.py
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
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
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
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
class BaseGate(CircuitOp):
    """
    Base class for quantum gates.

    Holds the computational basis matrix representation `self.mat` of
    size `(d**L, d**L)`, its reshaped rank-`2L` tensor `self.tensor` of
    shape `(d,) * (2 * L)`, and the 0-based `self.wires` tuple of length
    `L`.
    """

    L: int
    """
    Number of qudits that this gate acts on.
    """
    d: int
    """
    Local dimensionality of each wire inferred from `mat`.
    """
    wires: tuple[int, ...]
    """
    Zero-based wire indices `(w_0, ..., w_{L-1})` this gate acts on.
    """
    mat: np.ndarray | None = None
    """
    Matrix representation of the gate in the canonical basis.
    """
    tensor: np.ndarray
    """
    Rank-`2L` tensor representation with shape `(d,) * (2 * L)` where
    axes `0 .. L - 1` are output (row) legs and `L .. 2L - 1` are input
    (column) legs.
    """
    is_unitary: bool
    """
    Whether the gate matrix is unitary.
    """

    def c_if(
        self,
        keys: int | str | Sequence[int | str],
        val: int | Sequence[int] | None = None,
        *,
        condition: Callable[..., bool] | None = None,
    ) -> ClassicallyControlledGate:
        """
        Return a classically controlled version of this gate.

        Args:
            keys: Single classical key (`int` or `str`) or sequence of
                keys recorded by prior `Measure` operations.
            val: Target classical outcome value(s) in `{0, ..., d - 1}`
                (defaults to `1` when a single key is given and
                `condition` is `None`).
            condition: Optional boolean predicate `condition(*outcomes)`
                taking `len(keys)` integer outcomes and returning `True`
                when this gate should be applied.

        Returns:
            A `ClassicallyControlledGate` wrapping `self`.
        """
        return ClassicallyControlledGate(
            gate=self,
            keys=keys,
            val=val,
            condition=condition,
        )

    @overload
    def __add__(self, rhs: BaseGate) -> BaseGate: ...

    def __add__(self, rhs: object) -> BaseGate:
        """
        Add matrix representations of two gates on identical wires.

        Computes the elementwise sum of the matrix representations of
        `self` and `rhs`, and infers whether the resulting matrix is
        unitary.

        Args:
            rhs: Gate to add to this gate. Must be an instance of
                `BaseGate` acting on the same wires.

        Returns:
            A new `BaseGate` instance acting on `self.wires` with the
            summed matrix.

        Raises:
            TypeError: If `rhs` is a `CompositeGate` or not an instance
                of `BaseGate`.
            ValueError: If `rhs.wires` does not match `self.wires`, or
                if local dimension `d` differs.
        """
        if isinstance(rhs, CompositeGate):
            raise TypeError(
                "".join(
                    (
                        "Matrix addition is not supported ",
                        "for CompositeGate.",
                    )
                ),
            )
        if not isinstance(rhs, BaseGate):
            return NotImplemented

        if self.wires != rhs.wires:
            raise ValueError(
                "".join(
                    (
                        "Cannot add gates with different wires: ",
                        f"{self.wires} vs {rhs.wires}.",
                    )
                ),
            )
        if self.d != rhs.d:
            raise ValueError(
                "".join(
                    (
                        "Cannot add gates with different ",
                        f"local dimensions: d={self.d} vs d={rhs.d}.",
                    )
                ),
            )

        assert self.mat is not None
        assert rhs.mat is not None
        new_mat = self.mat + rhs.mat
        dim = new_mat.shape[0]
        ident = np.eye(dim, dtype=np.complex128)
        is_unitary = bool(np.allclose(new_mat @ new_mat.conj().T, ident))
        return BaseGate(
            wires=self.wires,
            mat=new_mat,
            is_unitary=is_unitary,
            _validate_unitary=False,
        )

    @overload
    def __radd__(self, lhs: BaseGate) -> BaseGate: ...

    @overload
    def __radd__(self, lhs: object) -> BaseGate: ...

    def __radd__(self, lhs: object) -> BaseGate:
        """
        Reflected matrix addition for `BaseGate` instances.

        Args:
            lhs: Left-hand operand to add. Must be an instance of
                `BaseGate` acting on the same wires.

        Returns:
            A new `BaseGate` instance acting on `self.wires` with the
            summed matrix.

        Raises:
            TypeError: If `lhs` is a `CompositeGate` or not an instance
                of `BaseGate`.
            ValueError: If `lhs.wires` does not match `self.wires`, or
                if local dimension `d` differs.
        """
        if isinstance(lhs, CompositeGate):
            raise TypeError(
                "".join(
                    (
                        "Matrix addition is not supported ",
                        "for CompositeGate.",
                    )
                ),
            )
        if not isinstance(lhs, BaseGate):
            return NotImplemented
        return self.__add__(lhs)

    @property
    def sqrt(self) -> BaseGate:
        r"""
        Return a gate whose matrix is a square root of this gate's
        matrix.

        The returned matrix $\sqrt{S}$ satisfies $\sqrt{S}^2 = S$; the
        unitary metadata is preserved.
        """
        return BaseGate(
            wires=self.wires,
            mat=sqrtm(self.mat),
            is_unitary=self.is_unitary,
            _validate_unitary=False,
        )

    @property
    def dagger(self) -> BaseGate:
        """
        Return the Hermitian adjoint (conjugate transpose) gate.
        """
        assert self.mat is not None
        adj_mat = np.conj(self.mat).T
        return BaseGate(
            wires=self.wires,
            mat=adj_mat,
            is_unitary=self.is_unitary,
            _validate_unitary=False,
        )

    def __repr__(self) -> str:
        return "\n".join(
            (
                f"Gate on {self.L} wires, with matrix representation",
                str(self.mat),
            )
        )

    def __init__(
        self,
        wires: tuple[int, ...] | list[int] | int,
        mat: np.ndarray | None = None,
        is_unitary: bool = True,
        *,
        _validate_unitary: bool = True,
    ) -> None:
        if not isinstance(is_unitary, bool):
            raise TypeError("is_unitary must be a boolean.")
        if isinstance(wires, int) and not isinstance(wires, bool):
            resolved_wires = (wires,)
        elif isinstance(wires, (tuple, list)):
            resolved_wires = tuple(wires)
        else:
            raise TypeError(
                "wires must be a non-negative integer or sequence of integers."
            )

        if len(resolved_wires) == 0:
            raise ValueError("Gate must act on at least one wire.")
        if any(
            (not isinstance(w, int)) or isinstance(w, bool) or (w < 0)
            for w in resolved_wires
        ):
            raise ValueError(
                "All wire indices must be non-negative 0-based integers."
            )
        if len(set(resolved_wires)) != len(resolved_wires):
            raise ValueError(
                "".join(
                    (
                        "Gate wires must be unique, got duplicate in ",
                        f"{resolved_wires}.",
                    )
                ),
            )

        self.wires = resolved_wires
        self.L = len(resolved_wires)

        if mat is None:
            mat = getattr(self, "mat", None)
        if mat is None:
            raise ValueError(
                "".join(
                    (
                        "Gate matrix 'mat' must be provided to __init__ ",
                        "or defined on the gate subclass.",
                    )
                ),
            )

        mat_arr = np.asarray(mat, dtype=np.complex128)
        if mat_arr.ndim != 2:
            raise ValueError("mat argument must be a 2D matrix.")
        if mat_arr.shape[0] != mat_arr.shape[1]:
            raise ValueError("mat argument is not square.")
        if not np.all(np.isfinite(mat_arr)):
            raise ValueError(
                "".join(
                    (
                        "Gate matrix 'mat' must contain only finite ",
                        "numbers (no NaN or Inf).",
                    )
                ),
            )

        dim = mat_arr.shape[0]
        d_inferred = round(dim ** (1.0 / self.L))
        if d_inferred**self.L != dim or d_inferred < 2:
            raise ValueError(
                "".join(
                    (
                        f"Matrix dimension {dim}x{dim} is incompatible ",
                        f"with L={self.L} wires of integer dimension d>=2.",
                    )
                ),
            )
        _check_dense_tensor_limits(
            2 * self.L,
            d_inferred,
            "BaseGate",
            check_ndim=True,
        )
        if is_unitary and _validate_unitary:
            ident = np.eye(dim, dtype=np.complex128)
            if not np.allclose(mat_arr @ mat_arr.conj().T, ident):
                raise ValueError(
                    "Gate matrix is not unitary (mat @ mat.dagger != I)."
                )

        mat_arr = mat_arr.copy()
        mat_arr.flags.writeable = False
        tensor_arr = mat_arr.reshape((d_inferred,) * (2 * self.L))
        tensor_arr.flags.writeable = False

        self.d = d_inferred
        self.mat = mat_arr
        self.tensor = tensor_arr
        self.is_unitary = is_unitary
        self.nickname = getattr(type(self), "nickname", type(self).__name__)

sqrt property

sqrt: BaseGate

Return a gate whose matrix is a square root of this gate's matrix.

The returned matrix \(\sqrt{S}\) satisfies \(\sqrt{S}^2 = S\); the unitary metadata is preserved.

dagger property

dagger: BaseGate

Return the Hermitian adjoint (conjugate transpose) gate.

wires instance-attribute

wires: tuple[int, ...] = resolved_wires

Zero-based wire indices (w_0, ..., w_{L-1}) this gate acts on.

L instance-attribute

L: int = len(resolved_wires)

Number of qudits that this gate acts on.

d instance-attribute

d: int = d_inferred

Local dimensionality of each wire inferred from mat.

mat class-attribute instance-attribute

mat: ndarray | None = mat_arr

Matrix representation of the gate in the canonical basis.

tensor instance-attribute

tensor: ndarray = tensor_arr

Rank-2L tensor representation with shape (d,) * (2 * L) where axes 0 .. L - 1 are output (row) legs and L .. 2L - 1 are input (column) legs.

is_unitary instance-attribute

is_unitary: bool = is_unitary

Whether the gate matrix is unitary.

c_if

c_if(
    keys: int | str | Sequence[int | str],
    val: int | Sequence[int] | None = None,
    *,
    condition: Callable[..., bool] | None = None,
) -> ClassicallyControlledGate

Return a classically controlled version of this gate.

Parameters:

Name Type Description Default
keys int | str | Sequence[int | str]

Single classical key (int or str) or sequence of keys recorded by prior Measure operations.

required
val int | Sequence[int] | None

Target classical outcome value(s) in {0, ..., d - 1} (defaults to 1 when a single key is given and condition is None).

None
condition Callable[..., bool] | None

Optional boolean predicate condition(*outcomes) taking len(keys) integer outcomes and returning True when this gate should be applied.

None

Returns:

Type Description
ClassicallyControlledGate

A ClassicallyControlledGate wrapping self.

Source code in src/quantum_emotion/core.py
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
def c_if(
    self,
    keys: int | str | Sequence[int | str],
    val: int | Sequence[int] | None = None,
    *,
    condition: Callable[..., bool] | None = None,
) -> ClassicallyControlledGate:
    """
    Return a classically controlled version of this gate.

    Args:
        keys: Single classical key (`int` or `str`) or sequence of
            keys recorded by prior `Measure` operations.
        val: Target classical outcome value(s) in `{0, ..., d - 1}`
            (defaults to `1` when a single key is given and
            `condition` is `None`).
        condition: Optional boolean predicate `condition(*outcomes)`
            taking `len(keys)` integer outcomes and returning `True`
            when this gate should be applied.

    Returns:
        A `ClassicallyControlledGate` wrapping `self`.
    """
    return ClassicallyControlledGate(
        gate=self,
        keys=keys,
        val=val,
        condition=condition,
    )

__add__

__add__(rhs: BaseGate) -> BaseGate
__add__(rhs: object) -> BaseGate

Add matrix representations of two gates on identical wires.

Computes the elementwise sum of the matrix representations of self and rhs, and infers whether the resulting matrix is unitary.

Parameters:

Name Type Description Default
rhs object

Gate to add to this gate. Must be an instance of BaseGate acting on the same wires.

required

Returns:

Type Description
BaseGate

A new BaseGate instance acting on self.wires with the

BaseGate

summed matrix.

Raises:

Type Description
TypeError

If rhs is a CompositeGate or not an instance of BaseGate.

ValueError

If rhs.wires does not match self.wires, or if local dimension d differs.

Source code in src/quantum_emotion/core.py
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
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
def __add__(self, rhs: object) -> BaseGate:
    """
    Add matrix representations of two gates on identical wires.

    Computes the elementwise sum of the matrix representations of
    `self` and `rhs`, and infers whether the resulting matrix is
    unitary.

    Args:
        rhs: Gate to add to this gate. Must be an instance of
            `BaseGate` acting on the same wires.

    Returns:
        A new `BaseGate` instance acting on `self.wires` with the
        summed matrix.

    Raises:
        TypeError: If `rhs` is a `CompositeGate` or not an instance
            of `BaseGate`.
        ValueError: If `rhs.wires` does not match `self.wires`, or
            if local dimension `d` differs.
    """
    if isinstance(rhs, CompositeGate):
        raise TypeError(
            "".join(
                (
                    "Matrix addition is not supported ",
                    "for CompositeGate.",
                )
            ),
        )
    if not isinstance(rhs, BaseGate):
        return NotImplemented

    if self.wires != rhs.wires:
        raise ValueError(
            "".join(
                (
                    "Cannot add gates with different wires: ",
                    f"{self.wires} vs {rhs.wires}.",
                )
            ),
        )
    if self.d != rhs.d:
        raise ValueError(
            "".join(
                (
                    "Cannot add gates with different ",
                    f"local dimensions: d={self.d} vs d={rhs.d}.",
                )
            ),
        )

    assert self.mat is not None
    assert rhs.mat is not None
    new_mat = self.mat + rhs.mat
    dim = new_mat.shape[0]
    ident = np.eye(dim, dtype=np.complex128)
    is_unitary = bool(np.allclose(new_mat @ new_mat.conj().T, ident))
    return BaseGate(
        wires=self.wires,
        mat=new_mat,
        is_unitary=is_unitary,
        _validate_unitary=False,
    )

__radd__

__radd__(lhs: BaseGate) -> BaseGate
__radd__(lhs: object) -> BaseGate
__radd__(lhs: object) -> BaseGate

Reflected matrix addition for BaseGate instances.

Parameters:

Name Type Description Default
lhs object

Left-hand operand to add. Must be an instance of BaseGate acting on the same wires.

required

Returns:

Type Description
BaseGate

A new BaseGate instance acting on self.wires with the

BaseGate

summed matrix.

Raises:

Type Description
TypeError

If lhs is a CompositeGate or not an instance of BaseGate.

ValueError

If lhs.wires does not match self.wires, or if local dimension d differs.

Source code in src/quantum_emotion/core.py
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
def __radd__(self, lhs: object) -> BaseGate:
    """
    Reflected matrix addition for `BaseGate` instances.

    Args:
        lhs: Left-hand operand to add. Must be an instance of
            `BaseGate` acting on the same wires.

    Returns:
        A new `BaseGate` instance acting on `self.wires` with the
        summed matrix.

    Raises:
        TypeError: If `lhs` is a `CompositeGate` or not an instance
            of `BaseGate`.
        ValueError: If `lhs.wires` does not match `self.wires`, or
            if local dimension `d` differs.
    """
    if isinstance(lhs, CompositeGate):
        raise TypeError(
            "".join(
                (
                    "Matrix addition is not supported ",
                    "for CompositeGate.",
                )
            ),
        )
    if not isinstance(lhs, BaseGate):
        return NotImplemented
    return self.__add__(lhs)

Measure

Bases: CircuitOp

Mid-circuit computational-basis measurement operation.

The STinespring dilation theorem is used to retain a coherent quantum state; the auxliary Hilbert space is formed by dimensions that record the measurement outcomes (also referred to as "classical record legs"). This enables this code to defer contraction of the internal tensor networks until the end. When reset=True, the measured wire is reset to \(|0\rangle\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | list[int] | int

Target wire index or sequence of unique 0-based wire indices to measure.

required
keys tuple[int | str, ...] | list[int | str] | int | str | None

Optional classical channel key(s) (int or str) matching the length of wires. Defaults to wires.

None
reset bool

If True, reset each measured wire to \(|0\rangle\) immediately after recording its outcome.

False
Source code in src/quantum_emotion/core.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
class Measure(CircuitOp):
    r"""
    Mid-circuit computational-basis measurement operation.

    The STinespring dilation theorem is used to retain a coherent
    quantum state; the auxliary Hilbert space is formed by dimensions
    that record the measurement outcomes (also referred to as
    "classical record legs"). This enables this code to
    defer contraction of the internal tensor networks until the end.
    When `reset=True`, the measured wire is reset to $|0\rangle$.

    Args:
        wires: Target wire index or sequence of unique 0-based wire
            indices to measure.
        keys: Optional classical channel key(s) (`int` or `str`)
            matching the length of `wires`. Defaults to `wires`.
        reset: If `True`, reset each measured wire to $|0\rangle$
            immediately after recording its outcome.
    """

    keys: tuple[int | str, ...]
    """
    Classical channel keys corresponding to each measured wire.
    """
    reset: bool
    """
    Whether measured wires are reset to `|0>` after measurement.
    """

    def __repr__(self) -> str:
        return (
            f"Measure(wires={self.wires}, keys={self.keys}, "
            f"reset={self.reset})"
        )

    def __init__(
        self,
        wires: tuple[int, ...] | list[int] | int,
        keys: tuple[int | str, ...]
        | list[int | str]
        | int
        | str
        | None = None,
        *,
        reset: bool = False,
    ) -> None:
        if isinstance(wires, int) and not isinstance(wires, bool):
            resolved_wires = (wires,)
        elif isinstance(wires, (tuple, list)):
            resolved_wires = tuple(wires)
        else:
            raise TypeError(
                "wires must be a non-negative integer or sequence of integers."
            )

        if len(resolved_wires) == 0:
            raise ValueError("Measure must act on at least one wire.")
        if any(
            (not isinstance(w, int)) or isinstance(w, bool) or (w < 0)
            for w in resolved_wires
        ):
            raise ValueError(
                "All wire indices must be non-negative 0-based integers."
            )
        if len(set(resolved_wires)) != len(resolved_wires):
            raise ValueError(
                f"Measured wires must be unique, got {resolved_wires}."
            )

        if not isinstance(reset, bool):
            raise TypeError("reset must be a boolean.")

        if keys is None:
            resolved_keys: tuple[int | str, ...] = resolved_wires
        elif isinstance(keys, bool):
            raise TypeError("keys cannot be a boolean.")
        elif isinstance(keys, (int, str)):
            resolved_keys = (_parse_classical_key(keys),)
        elif isinstance(keys, (tuple, list)):
            resolved_keys = tuple(_parse_classical_key(k) for k in keys)
        else:
            raise TypeError(
                "keys must be None, an int/str, or a sequence of int/str."
            )

        if len(resolved_keys) != len(resolved_wires):
            raise ValueError(
                "".join(
                    (
                        f"Number of classical keys ({len(resolved_keys)}) ",
                        "must match number of measured wires ",
                        f"({len(resolved_wires)}).",
                    )
                ),
            )
        if len(set(resolved_keys)) != len(resolved_keys):
            raise ValueError(
                "".join(
                    (
                        "Classical keys in Measure must be unique, ",
                        f"got {resolved_keys}.",
                    )
                ),
            )

        self.wires = resolved_wires
        self.L = len(resolved_wires)
        self.keys = resolved_keys
        self.reset = reset

keys instance-attribute

keys: tuple[int | str, ...] = resolved_keys

Classical channel keys corresponding to each measured wire.

reset instance-attribute

reset: bool = reset

Whether measured wires are reset to |0> after measurement.

ClassicallyControlledGate

Bases: CircuitOp

Quantum gate \(U\) conditioned on one or more classical measurement keys.

Constructs a block-diagonal tensor over \(k\) classical-record legs and \(L\) quantum target wires:

\[ \sum_{\mathbf{m} \in \{0, \dots, d-1\}^k} |\mathbf{m}\rangle\langle\mathbf{m}|_C \otimes U_{\mathbf{m}}, \]

where \(U_{\mathbf{m}} = U\) when \(\mathbf{m}\) satisfies the classical condition and \(U_{\mathbf{m}} = I^{\otimes L}\) otherwise.

Parameters:

Name Type Description Default
gate BaseGate

Target BaseGate to apply when the condition holds.

required
keys int | str | Sequence[int | str]

Single classical key (int or str) or sequence of unique keys recorded by prior Measure operations.

required
val int | Sequence[int] | None

Expected outcome value(s) in {0, ..., d - 1}. Defaults to 1 when a single key is given and condition is None.

None
condition Callable[..., bool] | None

Optional boolean callable condition(*outcomes) accepting k integers in {0, ..., d - 1}.

None
Source code in src/quantum_emotion/core.py
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
class ClassicallyControlledGate(CircuitOp):
    r"""
    Quantum gate $U$ conditioned on one or more classical measurement
    keys.

    Constructs a block-diagonal tensor over $k$ classical-record legs
    and $L$ quantum target wires:

    $$
    \sum_{\mathbf{m} \in \{0, \dots, d-1\}^k}
    |\mathbf{m}\rangle\langle\mathbf{m}|_C \otimes U_{\mathbf{m}},
    $$

    where $U_{\mathbf{m}} = U$ when $\mathbf{m}$ satisfies the classical
    condition and $U_{\mathbf{m}} = I^{\otimes L}$ otherwise.

    Args:
        gate: Target `BaseGate` to apply when the condition holds.
        keys: Single classical key (`int` or `str`) or sequence of
            unique keys recorded by prior `Measure` operations.
        val: Expected outcome value(s) in `{0, ..., d - 1}`. Defaults to
            `1` when a single key is given and `condition` is `None`.
        condition: Optional boolean callable `condition(*outcomes)`
            accepting `k` integers in `{0, ..., d - 1}`.
    """

    gate: BaseGate
    r"""
    Target gate $U$.
    """
    d: int
    """
    Local qudit dimension inherited from `gate`.
    """
    keys: tuple[int | str, ...]
    """
    Tuple of classical channel keys controlling `gate`.
    """
    val: tuple[int, ...] | None
    """
    Target classical outcome tuple when value-matching is used.
    """
    condition: Callable[..., bool] | None
    """
    Custom predicate callable when predicate-matching is used.
    """
    tensor: np.ndarray
    """
    Block-diagonal rank-`2(k + L)` tensor over classical and quantum
    legs.
    """
    label: str
    """
    Compact display label used in circuit diagrams.
    """

    def __repr__(self) -> str:
        return (
            f"ClassicallyControlledGate(gate={self.gate.__class__.__name__}"
            f"(wires={self.wires}), keys={self.keys})"
        )

    def __init__(
        self,
        gate: BaseGate,
        keys: int | str | Sequence[int | str],
        val: int | Sequence[int] | None = None,
        *,
        condition: Callable[..., bool] | None = None,
    ) -> None:
        if not isinstance(gate, BaseGate):
            raise TypeError("gate must be an instance of BaseGate.")

        if isinstance(keys, bool):
            raise TypeError("keys cannot be a boolean.")
        if isinstance(keys, (int, str)):
            resolved_keys = (_parse_classical_key(keys),)
        elif isinstance(keys, (tuple, list)):
            resolved_keys = tuple(_parse_classical_key(k) for k in keys)
        else:
            raise TypeError(
                "keys must be an int, str, or sequence of int/str."
            )

        if len(resolved_keys) == 0:
            raise ValueError("Classical control requires at least one key.")
        if len(set(resolved_keys)) != len(resolved_keys):
            raise ValueError(
                f"Classical control keys must be unique, got {resolved_keys}."
            )

        if (val is not None) and (condition is not None):
            raise ValueError("Specify either 'val' or 'condition', not both.")

        k = len(resolved_keys)
        d = gate.d
        L = gate.L

        if condition is not None:
            if not callable(condition):
                raise TypeError("condition must be callable.")
            resolved_val: tuple[int, ...] | None = None
            cond_desc = ",".join(str(key) for key in resolved_keys)
        else:
            if val is None:
                if k != 1:
                    raise ValueError(
                        "".join(
                            (
                                "Multi-key classical control requires an ",
                                "explicit 'val' sequence or 'condition' ",
                                "callable.",
                            )
                        ),
                    )
                resolved_val = (1,)
            elif isinstance(val, bool):
                raise TypeError("val cannot be a boolean.")
            elif isinstance(val, int):
                if k != 1:
                    raise ValueError(
                        "".join(
                            (
                                f"Expected {k} outcome values for {k} ",
                                f"keys, got scalar {val}.",
                            )
                        ),
                    )
                resolved_val = (val,)
            elif isinstance(val, (tuple, list)):
                if len(val) != k:
                    raise ValueError(
                        "".join(
                            (
                                f"Expected {k} outcome values for {k} ",
                                f"keys, got {len(val)}.",
                            )
                        ),
                    )
                parsed_vals: list[int] = []
                for item in val:
                    if isinstance(item, bool) or not isinstance(item, int):
                        raise TypeError(
                            "All classical outcome values must be integers."
                        )
                    parsed_vals.append(item)
                resolved_val = tuple(parsed_vals)
            else:
                raise TypeError(
                    "val must be an integer or sequence of integers."
                )

            for item in resolved_val:
                if not (0 <= item < d):
                    raise ValueError(
                        "".join(
                            (
                                f"Classical outcome value {item} is out ",
                                f"of range for d={d} ",
                                f"(expected 0 <= val < {d}).",
                            )
                        ),
                    )
            if k == 1:
                cond_desc = f"{resolved_keys[0]}=={resolved_val[0]}"
            else:
                cond_desc = f"{resolved_keys}=={resolved_val}"

        assert gate.mat is not None
        _check_dense_tensor_limits(
            k + 2 * L,
            d,
            "ClassicallyControlledGate",
        )
        ident_mat = np.eye(d**L, dtype=np.complex128)
        blocks = np.zeros((d**k, d**L, d**L), dtype=np.complex128)
        outcomes_iter = itertools.product(range(d), repeat=k)
        for idx, outcome in enumerate(outcomes_iter):
            if condition is not None:
                try:
                    matched = bool(condition(*outcome))
                except Exception as exc:
                    raise ValueError(
                        "".join(
                            (
                                "Error evaluating classical condition on ",
                                f"keys {resolved_keys} for outcome ",
                                f"{outcome}: {exc}",
                            )
                        ),
                    ) from exc
            else:
                matched = outcome == resolved_val
            blocks[idx, :, :] = gate.mat if matched else ident_mat

        tensor_arr = blocks.reshape((d,) * (k + 2 * L))
        tensor_arr.flags.writeable = False

        self.gate = gate
        self.wires = gate.wires
        self.L = L
        self.d = d
        self.keys = resolved_keys
        self.val = resolved_val
        self.condition = condition
        self.tensor = tensor_arr
        self.label = f"{gate.nickname}\n[{cond_desc}]"

gate instance-attribute

gate: BaseGate = gate

Target gate \(U\).

d instance-attribute

d: int = d

Local qudit dimension inherited from gate.

keys instance-attribute

keys: tuple[int | str, ...] = resolved_keys

Tuple of classical channel keys controlling gate.

val instance-attribute

val: tuple[int, ...] | None = resolved_val

Target classical outcome tuple when value-matching is used.

condition instance-attribute

condition: Callable[..., bool] | None = condition

Custom predicate callable when predicate-matching is used.

tensor instance-attribute

tensor: ndarray = tensor_arr

Block-diagonal rank-2(k + L) tensor over classical and quantum legs.

label instance-attribute

label: str = f'{gate.nickname}\n[{cond_desc}]'

Compact display label used in circuit diagrams.

CompositeGate

Bases: CircuitOp

Immutable sequence of CircuitOp instances formed by @.

Because Python evaluates CNOT2 @ CZ @ H @ X @ CNOT @ psi from left to right, operator-to-operator multiplications first assemble a CompositeGate before CompositeGate @ KetState dispatches via NotImplemented to KetState.__rmatmul__. Implementing __iter__ supports unpacking (*self) without inheriting mutable list methods.

Source code in src/quantum_emotion/core.py
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
class CompositeGate(CircuitOp):
    """
    Immutable sequence of `CircuitOp` instances formed by `@`.

    Because Python evaluates `CNOT2 @ CZ @ H @ X @ CNOT @ psi` from
    left to right, operator-to-operator multiplications first assemble a
    `CompositeGate` before `CompositeGate @ KetState` dispatches via
    `NotImplemented` to `KetState.__rmatmul__`. Implementing `__iter__`
    supports unpacking (`*self`) without inheriting mutable `list`
    methods.
    """

    ops: tuple[CircuitOp, ...]
    """
    Ordered tuple of circuit operations `(U_n, ..., U_1)` in this
    composition.
    """

    def __init__(self, *args: CircuitOp) -> None:
        if len(args) == 0:
            raise ValueError("CompositeGate requires at least one gate.")
        flattened: list[CircuitOp] = []
        for op in args:
            if not isinstance(op, CircuitOp):
                raise ValueError(
                    "".join(
                        (
                            "CompositeGate received a non-operation ",
                            "argument. Only CircuitOp instances can be ",
                            "composed.",
                        )
                    ),
                )
            if isinstance(op, CompositeGate) and not isinstance(
                op, ModularGate
            ):
                flattened.extend(op.ops)
            else:
                flattened.append(op)
        self.ops = tuple(flattened)

    @classmethod
    def _from_validated_ops(cls, ops: tuple[CircuitOp, ...]) -> CompositeGate:
        """
        Construct a `CompositeGate` from already-validated operations in
        O(N) without redundant type checks.
        """
        inst = cls.__new__(cls)
        inst.ops = ops
        return inst

    @property
    def dagger(self) -> CompositeGate:
        """
        Return the Hermitian adjoint composition in reversed order.
        """
        adjoint_ops: list[CircuitOp] = []
        for op in reversed(self.ops):
            if not hasattr(op, "dagger"):
                raise TypeError(
                    "".join(
                        (
                            "Cannot take dagger of CompositeGate ",
                            "containing non-unitary operation ",
                            f"{op.__class__.__name__}.",
                        )
                    ),
                )
            adjoint_ops.append(op.dagger)  # type: ignore[attr-defined]
        return CompositeGate._from_validated_ops(tuple(adjoint_ops))

    @property
    def wires(self) -> tuple[int, ...]:
        """Return the sorted set of wires used by the operations."""
        return tuple(sorted({wire for op in self.ops for wire in op.wires}))

    @property
    def L(self) -> int:
        """Return the number of distinct wires used by the operations."""
        return len(self.wires)

    def __iter__(self) -> Iterator[CircuitOp]:
        """
        Iterate over composed operations left-to-right (`*self`).
        """
        return iter(self.ops)

    def __reversed__(self) -> Iterator[CircuitOp]:
        """
        Iterate over composed operations right-to-left
        (`KetState._apply`).
        """
        return reversed(self.ops)

    def inverse(self) -> CompositeGate:
        """
        Return the inverse (Hermitian adjoint) of this composite circuit.

        Operations are reversed and each unitary operation is replaced
        by its dagger. Circuit operations without an adjoint raise
        `TypeError`.
        """
        return self.dagger

    def __len__(self) -> int:
        return len(self.ops)

    def __getitem__(self, index: int) -> CircuitOp:
        return self.ops[index]

    def plot(
        self,
        *,
        ax: plt.Axes | None = None,
        decompose_modules: bool = False,
    ) -> plt.Axes:
        """
        Plot the circuit using a placeholder all-zero input state.

        Args:
            ax: Optional existing `matplotlib.axes.Axes` instance.
            decompose_modules: If `True`, render module operations
                instead of collapsed module blocks.

        Returns:
            The `matplotlib.axes.Axes` instance containing the plot.

        Raises:
            ValueError: If the circuit contains no wires.
        """
        if not self.wires:
            raise ValueError("Cannot plot a circuit with no wires.")

        zero_state = KetState(N=max(self.wires) + 1)
        return (self @ zero_state).plot(
            ax=ax,
            decompose_modules=decompose_modules,
        )

    @overload
    def __matmul__(self, rhs: CircuitOp) -> CompositeGate: ...

    @overload
    def __matmul__(self, rhs: CompositeGate) -> CompositeGate: ...

    @overload
    def __matmul__(self, rhs: KetState) -> KetState: ...

    def __matmul__(self, rhs: object) -> CompositeGate:
        """
        Compose with another `CircuitOp` or `CompositeGate`, or return
        `NotImplemented` so `KetState.__rmatmul__` handles states.
        """
        lhs_ops = (self,) if isinstance(self, ModularGate) else self.ops
        if isinstance(rhs, ModularGate):
            return CompositeGate._from_validated_ops((*lhs_ops, rhs))
        if isinstance(rhs, CompositeGate):
            return CompositeGate._from_validated_ops((*lhs_ops, *rhs.ops))
        if isinstance(rhs, CircuitOp):
            return CompositeGate._from_validated_ops((*lhs_ops, rhs))

        return NotImplemented

    def __add__(self, rhs: object) -> None:
        """
        Prevent matrix addition on composite gates.

        Raises:
            TypeError: Always raised because matrix addition is not
                supported for composite gates.
        """
        raise TypeError(
            "".join(
                (
                    "Matrix addition is not supported ",
                    "for CompositeGate.",
                )
            ),
        )

    def __radd__(self, lhs: object) -> None:
        """
        Prevent reflected matrix addition on composite gates.

        Raises:
            TypeError: Always raised because matrix addition is not
                supported for composite gates.
        """
        raise TypeError(
            "".join(
                (
                    "Matrix addition is not supported ",
                    "for CompositeGate.",
                )
            ),
        )

    def eval(
        self,
        wires: Sequence[int] | None = None,
        **kwargs: object,
    ) -> BaseGate:
        """
        Contract composed `BaseGate` instances into a single `BaseGate`.

        Args:
            wires: Optional wire sequence defining the qubit ordering
                and subsystem. Defaults to all active wires sorted in
                ascending order.
            **kwargs: Additional keyword arguments forwarded to
                `CoreRegister._contract_graph`.

        Returns:
            A `BaseGate` instance acting on `wires` with the combined
            matrix and rank-`2L` tensor representation.

        Raises:
            TypeError: If any composed operation is not a `BaseGate`
                (e.g., `Measure` or `ClassicallyControlledGate`).
            ValueError: If gate dimensions mismatch or specified wires
                do not cover all active wires.
        """
        pure_gates = list(_iter_atomic_gates(self.ops))

        d = pure_gates[0].d
        for op in pure_gates:
            if op.d != d:
                raise ValueError(
                    "".join(
                        (
                            "Mismatched qudit dimensions in CompositeGate: ",
                            f"expected d={d}, got d={op.d}.",
                        )
                    ),
                )

        active_wires = {w for op in pure_gates for w in op.wires}
        if wires is None:
            resolved_wires = tuple(sorted(active_wires))
        else:
            if not isinstance(wires, Sequence) or isinstance(
                wires, (str, bytes)
            ):
                raise TypeError(
                    "".join(
                        (
                            "wires must be None or a sequence of ",
                            "non-negative integers.",
                        )
                    ),
                )
            resolved_wires = tuple(wires)
            if any(
                (not isinstance(w, int)) or isinstance(w, bool) or (w < 0)
                for w in resolved_wires
            ):
                raise ValueError(
                    "".join(
                        (
                            "All wire indices must be non-negative 0-based ",
                            "integers.",
                        )
                    ),
                )
            if len(set(resolved_wires)) != len(resolved_wires):
                raise ValueError(
                    "".join(
                        (
                            "Gate wires must be unique, got duplicate in ",
                            f"{resolved_wires}.",
                        )
                    ),
                )
            if not active_wires.issubset(set(resolved_wires)):
                raise ValueError(
                    "".join(
                        (
                            "Specified wires must contain all wires acted on ",
                            "by the composite gate. Missing: ",
                            f"{active_wires - set(resolved_wires)}.",
                        )
                    ),
                )

        _check_dense_tensor_limits(
            2 * len(resolved_wires),
            d,
            "CompositeGate.eval()",
        )

        G = nx.MultiDiGraph()
        in_frontier: dict[int, tuple[int, int]] = {}
        out_frontier: dict[int, tuple[int, int]] = {}

        for node_id, gate in enumerate(reversed(pure_gates)):
            G.add_node(node_id, tensor=gate.tensor)
            for idx, wire in enumerate(gate.wires):
                in_ax = gate.L + idx
                out_ax = idx
                if wire not in in_frontier:
                    in_frontier[wire] = (node_id, in_ax)
                if wire in out_frontier:
                    prev_leg = out_frontier[wire]
                    G.add_edge(
                        prev_leg[0],
                        node_id,
                        out_axis=prev_leg[1],
                        in_axis=in_ax,
                        wire=wire,
                    )
                out_frontier[wire] = (node_id, out_ax)

        node_counter = len(pure_gates)
        for wire in resolved_wires:
            if wire not in active_wires:
                eye_node = node_counter
                node_counter = node_counter + 1
                G.add_node(
                    eye_node,
                    tensor=np.eye(d, dtype=np.complex128),
                )
                out_frontier[wire] = (eye_node, 0)
                in_frontier[wire] = (eye_node, 1)

        output_legs = [out_frontier[w] for w in resolved_wires] + [
            in_frontier[w] for w in resolved_wires
        ]
        contracted = CoreRegister._contract_graph(
            G,
            output_legs=output_legs,
            **kwargs,
        )
        L = len(resolved_wires)
        mat = contracted.reshape(d**L, d**L)
        is_unitary = all(getattr(op, "is_unitary", True) for op in pure_gates)

        return BaseGate(
            wires=resolved_wires,
            mat=mat,
            is_unitary=is_unitary,
            _validate_unitary=False,
        )

ops instance-attribute

ops: tuple[CircuitOp, ...] = tuple(flattened)

Ordered tuple of circuit operations (U_n, ..., U_1) in this composition.

dagger property

dagger: CompositeGate

Return the Hermitian adjoint composition in reversed order.

wires property

wires: tuple[int, ...]

Return the sorted set of wires used by the operations.

L property

L: int

Return the number of distinct wires used by the operations.

__iter__

__iter__() -> Iterator[CircuitOp]

Iterate over composed operations left-to-right (*self).

Source code in src/quantum_emotion/core.py
2150
2151
2152
2153
2154
def __iter__(self) -> Iterator[CircuitOp]:
    """
    Iterate over composed operations left-to-right (`*self`).
    """
    return iter(self.ops)

__reversed__

__reversed__() -> Iterator[CircuitOp]

Iterate over composed operations right-to-left (KetState._apply).

Source code in src/quantum_emotion/core.py
2156
2157
2158
2159
2160
2161
def __reversed__(self) -> Iterator[CircuitOp]:
    """
    Iterate over composed operations right-to-left
    (`KetState._apply`).
    """
    return reversed(self.ops)

inverse

inverse() -> CompositeGate

Return the inverse (Hermitian adjoint) of this composite circuit.

Operations are reversed and each unitary operation is replaced by its dagger. Circuit operations without an adjoint raise TypeError.

Source code in src/quantum_emotion/core.py
2163
2164
2165
2166
2167
2168
2169
2170
2171
def inverse(self) -> CompositeGate:
    """
    Return the inverse (Hermitian adjoint) of this composite circuit.

    Operations are reversed and each unitary operation is replaced
    by its dagger. Circuit operations without an adjoint raise
    `TypeError`.
    """
    return self.dagger

plot

plot(
    *,
    ax: Axes | None = None,
    decompose_modules: bool = False,
) -> plt.Axes

Plot the circuit using a placeholder all-zero input state.

Parameters:

Name Type Description Default
ax Axes | None

Optional existing matplotlib.axes.Axes instance.

None
decompose_modules bool

If True, render module operations instead of collapsed module blocks.

False

Returns:

Type Description
Axes

The matplotlib.axes.Axes instance containing the plot.

Raises:

Type Description
ValueError

If the circuit contains no wires.

Source code in src/quantum_emotion/core.py
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
def plot(
    self,
    *,
    ax: plt.Axes | None = None,
    decompose_modules: bool = False,
) -> plt.Axes:
    """
    Plot the circuit using a placeholder all-zero input state.

    Args:
        ax: Optional existing `matplotlib.axes.Axes` instance.
        decompose_modules: If `True`, render module operations
            instead of collapsed module blocks.

    Returns:
        The `matplotlib.axes.Axes` instance containing the plot.

    Raises:
        ValueError: If the circuit contains no wires.
    """
    if not self.wires:
        raise ValueError("Cannot plot a circuit with no wires.")

    zero_state = KetState(N=max(self.wires) + 1)
    return (self @ zero_state).plot(
        ax=ax,
        decompose_modules=decompose_modules,
    )

__matmul__

__matmul__(rhs: CircuitOp) -> CompositeGate
__matmul__(rhs: CompositeGate) -> CompositeGate
__matmul__(rhs: KetState) -> KetState
__matmul__(rhs: object) -> CompositeGate

Compose with another CircuitOp or CompositeGate, or return NotImplemented so KetState.__rmatmul__ handles states.

Source code in src/quantum_emotion/core.py
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
def __matmul__(self, rhs: object) -> CompositeGate:
    """
    Compose with another `CircuitOp` or `CompositeGate`, or return
    `NotImplemented` so `KetState.__rmatmul__` handles states.
    """
    lhs_ops = (self,) if isinstance(self, ModularGate) else self.ops
    if isinstance(rhs, ModularGate):
        return CompositeGate._from_validated_ops((*lhs_ops, rhs))
    if isinstance(rhs, CompositeGate):
        return CompositeGate._from_validated_ops((*lhs_ops, *rhs.ops))
    if isinstance(rhs, CircuitOp):
        return CompositeGate._from_validated_ops((*lhs_ops, rhs))

    return NotImplemented

__add__

__add__(rhs: object) -> None

Prevent matrix addition on composite gates.

Raises:

Type Description
TypeError

Always raised because matrix addition is not supported for composite gates.

Source code in src/quantum_emotion/core.py
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
def __add__(self, rhs: object) -> None:
    """
    Prevent matrix addition on composite gates.

    Raises:
        TypeError: Always raised because matrix addition is not
            supported for composite gates.
    """
    raise TypeError(
        "".join(
            (
                "Matrix addition is not supported ",
                "for CompositeGate.",
            )
        ),
    )

__radd__

__radd__(lhs: object) -> None

Prevent reflected matrix addition on composite gates.

Raises:

Type Description
TypeError

Always raised because matrix addition is not supported for composite gates.

Source code in src/quantum_emotion/core.py
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
def __radd__(self, lhs: object) -> None:
    """
    Prevent reflected matrix addition on composite gates.

    Raises:
        TypeError: Always raised because matrix addition is not
            supported for composite gates.
    """
    raise TypeError(
        "".join(
            (
                "Matrix addition is not supported ",
                "for CompositeGate.",
            )
        ),
    )

eval

eval(
    wires: Sequence[int] | None = None, **kwargs: object
) -> BaseGate

Contract composed BaseGate instances into a single BaseGate.

Parameters:

Name Type Description Default
wires Sequence[int] | None

Optional wire sequence defining the qubit ordering and subsystem. Defaults to all active wires sorted in ascending order.

None
**kwargs object

Additional keyword arguments forwarded to CoreRegister._contract_graph.

{}

Returns:

Type Description
BaseGate

A BaseGate instance acting on wires with the combined

BaseGate

matrix and rank-2L tensor representation.

Raises:

Type Description
TypeError

If any composed operation is not a BaseGate (e.g., Measure or ClassicallyControlledGate).

ValueError

If gate dimensions mismatch or specified wires do not cover all active wires.

Source code in src/quantum_emotion/core.py
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
def eval(
    self,
    wires: Sequence[int] | None = None,
    **kwargs: object,
) -> BaseGate:
    """
    Contract composed `BaseGate` instances into a single `BaseGate`.

    Args:
        wires: Optional wire sequence defining the qubit ordering
            and subsystem. Defaults to all active wires sorted in
            ascending order.
        **kwargs: Additional keyword arguments forwarded to
            `CoreRegister._contract_graph`.

    Returns:
        A `BaseGate` instance acting on `wires` with the combined
        matrix and rank-`2L` tensor representation.

    Raises:
        TypeError: If any composed operation is not a `BaseGate`
            (e.g., `Measure` or `ClassicallyControlledGate`).
        ValueError: If gate dimensions mismatch or specified wires
            do not cover all active wires.
    """
    pure_gates = list(_iter_atomic_gates(self.ops))

    d = pure_gates[0].d
    for op in pure_gates:
        if op.d != d:
            raise ValueError(
                "".join(
                    (
                        "Mismatched qudit dimensions in CompositeGate: ",
                        f"expected d={d}, got d={op.d}.",
                    )
                ),
            )

    active_wires = {w for op in pure_gates for w in op.wires}
    if wires is None:
        resolved_wires = tuple(sorted(active_wires))
    else:
        if not isinstance(wires, Sequence) or isinstance(
            wires, (str, bytes)
        ):
            raise TypeError(
                "".join(
                    (
                        "wires must be None or a sequence of ",
                        "non-negative integers.",
                    )
                ),
            )
        resolved_wires = tuple(wires)
        if any(
            (not isinstance(w, int)) or isinstance(w, bool) or (w < 0)
            for w in resolved_wires
        ):
            raise ValueError(
                "".join(
                    (
                        "All wire indices must be non-negative 0-based ",
                        "integers.",
                    )
                ),
            )
        if len(set(resolved_wires)) != len(resolved_wires):
            raise ValueError(
                "".join(
                    (
                        "Gate wires must be unique, got duplicate in ",
                        f"{resolved_wires}.",
                    )
                ),
            )
        if not active_wires.issubset(set(resolved_wires)):
            raise ValueError(
                "".join(
                    (
                        "Specified wires must contain all wires acted on ",
                        "by the composite gate. Missing: ",
                        f"{active_wires - set(resolved_wires)}.",
                    )
                ),
            )

    _check_dense_tensor_limits(
        2 * len(resolved_wires),
        d,
        "CompositeGate.eval()",
    )

    G = nx.MultiDiGraph()
    in_frontier: dict[int, tuple[int, int]] = {}
    out_frontier: dict[int, tuple[int, int]] = {}

    for node_id, gate in enumerate(reversed(pure_gates)):
        G.add_node(node_id, tensor=gate.tensor)
        for idx, wire in enumerate(gate.wires):
            in_ax = gate.L + idx
            out_ax = idx
            if wire not in in_frontier:
                in_frontier[wire] = (node_id, in_ax)
            if wire in out_frontier:
                prev_leg = out_frontier[wire]
                G.add_edge(
                    prev_leg[0],
                    node_id,
                    out_axis=prev_leg[1],
                    in_axis=in_ax,
                    wire=wire,
                )
            out_frontier[wire] = (node_id, out_ax)

    node_counter = len(pure_gates)
    for wire in resolved_wires:
        if wire not in active_wires:
            eye_node = node_counter
            node_counter = node_counter + 1
            G.add_node(
                eye_node,
                tensor=np.eye(d, dtype=np.complex128),
            )
            out_frontier[wire] = (eye_node, 0)
            in_frontier[wire] = (eye_node, 1)

    output_legs = [out_frontier[w] for w in resolved_wires] + [
        in_frontier[w] for w in resolved_wires
    ]
    contracted = CoreRegister._contract_graph(
        G,
        output_legs=output_legs,
        **kwargs,
    )
    L = len(resolved_wires)
    mat = contracted.reshape(d**L, d**L)
    is_unitary = all(getattr(op, "is_unitary", True) for op in pure_gates)

    return BaseGate(
        wires=resolved_wires,
        mat=mat,
        is_unitary=is_unitary,
        _validate_unitary=False,
    )

ModularGate

Bases: CompositeGate

A named composite circuit that can be inserted as one operation.

The contracted tensor is computed lazily when .tensor is queried, while _apply inserts the constituent local gates into the register graph tagged with module metadata for plotting and scalable cotengra contraction.

Source code in src/quantum_emotion/core.py
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
class ModularGate(CompositeGate):
    """
    A named composite circuit that can be inserted as one operation.

    The contracted tensor is computed lazily when `.tensor` is queried,
    while `_apply` inserts the constituent local gates into the register
    graph tagged with module metadata for plotting and scalable
    `cotengra` contraction.
    """

    is_module = True

    def __init__(self, *args: CircuitOp, wires: Sequence[int]) -> None:
        super().__init__(*args)
        if not isinstance(wires, Sequence) or isinstance(wires, (str, bytes)):
            raise TypeError(
                "ModularGate wires must be a sequence of integers."
            )
        resolved_wires = tuple(wires)
        if len(resolved_wires) == 0:
            raise ValueError("ModularGate requires at least one wire.")
        if any(
            not isinstance(wire, int) or isinstance(wire, bool) or wire < 0
            for wire in resolved_wires
        ):
            raise TypeError("ModularGate wires must be non-negative integers.")
        if len(set(resolved_wires)) != len(resolved_wires):
            raise ValueError("ModularGate wires must be unique.")
        operation_wires = {wire for op in self.ops for wire in op.wires}
        if operation_wires != set(resolved_wires):
            raise ValueError(
                "".join(
                    (
                        "ModularGate wires must match the wires used by ",
                        "its operations.",
                    )
                ),
            )
        self._module_wires = resolved_wires
        self.nickname = getattr(type(self), "nickname", type(self).__name__)
        self._cached_tensor: np.ndarray | None = None
        _ = self.d

    @property
    def wires(self) -> tuple[int, ...]:
        """Return the module's externally visible wire ordering."""
        return self._module_wires

    @property
    def d(self) -> int:
        """Return the common local dimension of the module operations."""
        try:
            leaf_gates = tuple(_iter_atomic_gates(self.ops))
        except TypeError as exc:
            raise TypeError(
                "ModularGate operations must all be BaseGate instances."
            ) from exc
        dimensions = {op.d for op in leaf_gates}
        if len(dimensions) != 1:
            raise ValueError(
                "".join(
                    (
                        "Mismatched qudit dimensions in ModularGate: ",
                        f"{sorted(dimensions)}.",
                    )
                ),
            )
        return dimensions.pop()

    @property
    def dagger(self) -> ModularGate:
        """
        Return the Hermitian adjoint module in reversed gate order.
        """
        adjoint_ops = tuple(
            op.dagger  # type: ignore[attr-defined]
            for op in reversed(self.ops)
        )
        dag = ModularGate(*adjoint_ops, wires=self.wires)
        dag.nickname = self.nickname
        return dag

    @property
    def tensor(self) -> np.ndarray:
        """Return the module's contracted rank-`2L` tensor."""
        if self._cached_tensor is None:
            self._cached_tensor = self.eval(wires=self.wires).tensor
        return self._cached_tensor

wires property

wires: tuple[int, ...]

Return the module's externally visible wire ordering.

d property

d: int

Return the common local dimension of the module operations.

dagger property

dagger: ModularGate

Return the Hermitian adjoint module in reversed gate order.

tensor property

tensor: ndarray

Return the module's contracted rank-2L tensor.

Quantum Gates

quantum_emotion.gates

Quantum gate definitions.

Provides standard single-qubit and two-qubit unitary gates built by subclassing BaseGate. Contributors adding new gates can define a subclass here with a mat class attribute (for fixed gates) or compute mat in __init__ (for parameterized gates).

PauliX

Bases: BaseGate

Single-qubit Pauli-\(X\) (bit-flip) gate.

Acts on computational basis states as \(X|0\rangle = |1\rangle\) and \(X|1\rangle = |0\rangle\), with matrix representation:

\[ X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \]

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
 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
class PauliX(BaseGate):
    r"""
    Single-qubit Pauli-$X$ (bit-flip) gate.

    Acts on computational basis states as $X|0\rangle = |1\rangle$ and
    $X|1\rangle = |0\rangle$, with matrix representation:

    $$
    X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$X$"

    mat: np.ndarray = np.array(
        [
            [0.0, 1.0],
            [1.0, 0.0],
        ],
        dtype=np.complex128,
    )

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

PauliY

Bases: BaseGate

Single-qubit Pauli-\(Y\) gate.

Acts on computational basis states as \(Y|0\rangle = i|1\rangle\) and \(Y|1\rangle = -i|0\rangle\), with matrix representation:

\[ Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix} \]

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class PauliY(BaseGate):
    r"""
    Single-qubit Pauli-$Y$ gate.

    Acts on computational basis states as $Y|0\rangle = i|1\rangle$ and
    $Y|1\rangle = -i|0\rangle$, with matrix representation:

    $$
    Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$Y$"

    mat: np.ndarray = np.array(
        [
            [0.0, -1.0j],
            [1.0j, 0.0],
        ],
        dtype=np.complex128,
    )

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

PauliZ

Bases: BaseGate

Single-qubit Pauli-\(Z\) (phase-flip) gate.

Acts on computational basis states as \(Z|0\rangle = |0\rangle\) and \(Z|1\rangle = -|1\rangle\), with matrix representation:

\[ Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \]

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class PauliZ(BaseGate):
    r"""
    Single-qubit Pauli-$Z$ (phase-flip) gate.

    Acts on computational basis states as $Z|0\rangle = |0\rangle$ and
    $Z|1\rangle = -|1\rangle$, with matrix representation:

    $$
    Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$Z$"

    mat: np.ndarray = np.array(
        [
            [1.0, 0.0],
            [0.0, -1.0],
        ],
        dtype=np.complex128,
    )

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

PauliXRot

Bases: BaseGate

Single-qubit Pauli-\(X\) rotation gate.

Defined as \(R_X(\phi) = e^{-i \phi X / 2}\), where \(X\) is the Pauli-\(X\) gate, with matrix representation:

\[ R_X(\phi) = \begin{pmatrix} \cos(\phi / 2) & -i \sin(\phi / 2) \\ -i \sin(\phi / 2) & \cos(\phi / 2) \end{pmatrix} \]

Parameters:

Name Type Description Default
wires

Target wire index (0-based integer or 1-tuple).

required
phi float

Rotation angle.

None
**kwargs

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class PauliXRot(BaseGate):
    r"""
    Single-qubit Pauli-$X$ rotation gate.

    Defined as $R_X(\phi) = e^{-i \phi X / 2}$, where $X$ is the
    Pauli-$X$ gate, with matrix representation:

    $$
    R_X(\phi) = \begin{pmatrix}
        \cos(\phi / 2) & -i \sin(\phi / 2) \\
        -i \sin(\phi / 2) & \cos(\phi / 2)
    \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        phi: Rotation angle.
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$R_X(\phi)$"

    def __init__(self, wires, phi: float = None, **kwargs):
        phi_val = _validate_angle(phi, type(self).__name__)
        mat = scialg.expm(-1.0j * phi_val * PauliX.mat / 2)
        super().__init__(wires, mat=mat, **kwargs)

PauliYRot

Bases: BaseGate

Single-qubit Pauli-\(Y\) rotation gate.

Defined as \(R_Y(\phi) = e^{-i \phi Y / 2}\), where \(Y\) is the Pauli-\(Y\) gate, with matrix representation:

\[ R_Y(\phi) = \begin{pmatrix} \cos(\phi / 2) & -\sin(\phi / 2) \\ \sin(\phi / 2) & \cos(\phi / 2) \end{pmatrix} \]

Parameters:

Name Type Description Default
wires

Target wire index (0-based integer or 1-tuple).

required
phi float

Rotation angle.

None
**kwargs

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class PauliYRot(BaseGate):
    r"""
    Single-qubit Pauli-$Y$ rotation gate.

    Defined as $R_Y(\phi) = e^{-i \phi Y / 2}$, where $Y$ is the
    Pauli-$Y$ gate, with matrix representation:

    $$
    R_Y(\phi) = \begin{pmatrix}
        \cos(\phi / 2) & -\sin(\phi / 2) \\
        \sin(\phi / 2) & \cos(\phi / 2)
    \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        phi: Rotation angle.
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$R_Y(\phi)$"

    def __init__(self, wires, phi: float = None, **kwargs):
        phi_val = _validate_angle(phi, type(self).__name__)
        mat = scialg.expm(-1.0j * phi_val * PauliY.mat / 2)
        super().__init__(wires, mat=mat, **kwargs)

PauliZRot

Bases: BaseGate

Single-qubit Pauli-\(Z\) rotation gate.

Defined as \(R_Z(\phi) = e^{-i \phi Z / 2}\), where \(Z\) is the Pauli-\(Z\) gate, with matrix representation:

\[ R_Z(\phi) = \begin{pmatrix} e^{-i \phi / 2} & 0 \\ 0 & e^{i \phi / 2} \end{pmatrix} \]

Parameters:

Name Type Description Default
wires

Target wire index (0-based integer or 1-tuple).

required
phi float

Rotation angle.

None
**kwargs

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class PauliZRot(BaseGate):
    r"""
    Single-qubit Pauli-$Z$ rotation gate.

    Defined as $R_Z(\phi) = e^{-i \phi Z / 2}$, where $Z$ is the
    Pauli-$Z$ gate, with matrix representation:

    $$
    R_Z(\phi) = \begin{pmatrix}
        e^{-i \phi / 2} & 0 \\
        0 & e^{i \phi / 2}
    \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        phi: Rotation angle.
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$R_Z(\phi)$"

    def __init__(self, wires, phi: float = None, **kwargs):
        phi_val = _validate_angle(phi, type(self).__name__)
        mat = scialg.expm(-1.0j * phi_val * PauliZ.mat / 2)
        super().__init__(wires, mat=mat, **kwargs)

Hadamard

Bases: BaseGate

Single-qubit Hadamard (\(H\)) gate.

Maps \(z\)-basis states to the \(x\)-basis: \(H|0\rangle = (|0\rangle + |1\rangle)/\sqrt{2}\) and \(H|1\rangle = (|0\rangle - |1\rangle)/\sqrt{2}\), with matrix representation:

\[ H = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} \]

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class Hadamard(BaseGate):
    r"""
    Single-qubit Hadamard ($H$) gate.

    Maps $z$-basis states to the $x$-basis:
    $H|0\rangle = (|0\rangle + |1\rangle)/\sqrt{2}$ and
    $H|1\rangle = (|0\rangle - |1\rangle)/\sqrt{2}$, with matrix
    representation:

    $$
    H = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}
    $$

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$H$"

    mat: np.ndarray = (1.0 / np.sqrt(2.0)) * np.array(
        [
            [1.0, 1.0],
            [1.0, -1.0],
        ],
        dtype=np.complex128,
    )

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

PhaseGate

Bases: BaseGate

Parameterized single-qubit phase gate.

Applies \(\mathrm{diag}(1, e^{i\theta})\), leaving \(|0\rangle\) invariant and multiplying \(|1\rangle\) by \(e^{i\theta}\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
theta float

Phase angle \(\theta\) in radians (default: 0.0).

0.0
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class PhaseGate(BaseGate):
    r"""
    Parameterized single-qubit phase gate.

    Applies $\mathrm{diag}(1, e^{i\theta})$, leaving $|0\rangle$
    invariant and multiplying $|1\rangle$ by $e^{i\theta}$.

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        theta: Phase angle $\theta$ in radians (default: `0.0`).
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        theta: float = 0.0,
        **kwargs: object,
    ) -> None:
        theta_val = _validate_angle(theta, type(self).__name__)
        phase = np.exp(1.0j * theta_val)
        super().__init__(
            wires=wires,
            mat=np.array(
                [[1.0, 0.0], [0.0, phase]],
                dtype=np.complex128,
            ),
            **kwargs,
        )
        self.nickname = getattr(
            type(self),
            "nickname",
            rf"$R_{{{_format_angle(theta_val)}}}$",
        )

TGate

Bases: PhaseGate

Single-qubit \(T(\pi/8\)) gate.

Equivalent to PhaseGate with \(\theta = \pi / 4\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
**kwargs object

Additional keyword arguments forwarded to PhaseGate.

{}
Source code in src/quantum_emotion/gates.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class TGate(PhaseGate):
    r"""
    Single-qubit $T(\pi/8$) gate.

    Equivalent to `PhaseGate` with $\theta = \pi / 4$.

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        **kwargs: Additional keyword arguments forwarded to `PhaseGate`.
    """

    nickname = r"$T$"

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, theta=np.pi / 4.0, **kwargs)

SGate

Bases: PhaseGate

Single-qubit phase gate.

Equivalent to PhaseGate with \(\theta = \pi / 2\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Target wire index (0-based integer or 1-tuple).

required
**kwargs object

Additional keyword arguments forwarded to PhaseGate.

{}
Source code in src/quantum_emotion/gates.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
class SGate(PhaseGate):
    r"""
    Single-qubit phase gate.

    Equivalent to `PhaseGate` with $\theta = \pi / 2$.

    Args:
        wires: Target wire index (0-based integer or 1-tuple).
        **kwargs: Additional keyword arguments forwarded to `PhaseGate`.
    """

    nickname = r"$S$"

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, theta=np.pi / 2.0, **kwargs)

CNOT

Bases: BaseGate

Two-qubit Controlled-NOT (\(\mathrm{CNOT}\)) gate.

Applies Pauli-\(X\) to wires[1] (target) conditioned on wires[0] (control) being in state \(|1\rangle\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Two-wire tuple (control, target) of 0-based indices.

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class CNOT(BaseGate):
    r"""
    Two-qubit Controlled-NOT ($\mathrm{CNOT}$) gate.

    Applies Pauli-$X$ to `wires[1]` (target) conditioned on `wires[0]`
    (control) being in state $|1\rangle$.

    Args:
        wires: Two-wire tuple `(control, target)` of 0-based indices.
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$\mathrm{CX}$"

    mat: np.ndarray = np.array(
        [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
            [0.0, 0.0, 1.0, 0.0],
        ],
        dtype=np.complex128,
    )

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

ControlledZ

Bases: BaseGate

Two-qubit Controlled-\(Z\) (\(\mathrm{CZ}\)) gate.

Applies a \(-1\) phase when both wires[0] and wires[1] are in state \(|11\rangle\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Two-wire tuple (wire_0, wire_1) of 0-based indices.

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
class ControlledZ(BaseGate):
    r"""
    Two-qubit Controlled-$Z$ ($\mathrm{CZ}$) gate.

    Applies a $-1$ phase when both `wires[0]` and `wires[1]` are in
    state $|11\rangle$.

    Args:
        wires: Two-wire tuple `(wire_0, wire_1)` of 0-based indices.
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$\mathrm{CZ}$"

    mat: np.ndarray = np.diag([1.0, 1.0, 1.0, -1.0]).astype(np.complex128)

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

ControlledY

Bases: BaseGate

Two-qubit Controlled-\(Y\) (\(\mathrm{CY}\)) gate.

Applies Pauli-\(Y\) to wires[1] (target) conditioned on wires[0] (control) being in state \(|1\rangle\).

Parameters:

Name Type Description Default
wires tuple[int, ...] | int

Two-wire tuple (control, target) of 0-based indices.

required
**kwargs object

Additional keyword arguments forwarded to BaseGate.

{}
Source code in src/quantum_emotion/gates.py
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
class ControlledY(BaseGate):
    r"""
    Two-qubit Controlled-$Y$ ($\mathrm{CY}$) gate.

    Applies Pauli-$Y$ to `wires[1]` (target) conditioned on `wires[0]`
    (control) being in state $|1\rangle$.

    Args:
        wires: Two-wire tuple `(control, target)` of 0-based indices.
        **kwargs: Additional keyword arguments forwarded to `BaseGate`.
    """

    nickname = r"$\mathrm{CY}$"

    mat: np.ndarray = np.array(
        [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 0.0, -1.0j],
            [0.0, 0.0, 1.0j, 0.0],
        ],
        dtype=np.complex128,
    )

    def __init__(
        self,
        wires: tuple[int, ...] | int,
        **kwargs: object,
    ) -> None:
        super().__init__(wires=wires, **kwargs)

ControlledPhaseGate

Bases: BaseGate

Two-qubit controlled phase gate.

Applies \(e^{i\theta}\) only to the \(|11\rangle\) basis state.

Parameters:

Name Type Description Default
wires tuple[int, int]

Two-wire tuple (control, target).

required
theta float

Controlled phase angle in radians.

required
Source code in src/quantum_emotion/gates.py
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
class ControlledPhaseGate(BaseGate):
    r"""
    Two-qubit controlled phase gate.

    Applies $e^{i\theta}$ only to the $|11\rangle$ basis state.

    Args:
        wires: Two-wire tuple `(control, target)`.
        theta: Controlled phase angle in radians.
    """

    def __init__(
        self,
        wires: tuple[int, int],
        theta: float,
    ) -> None:
        if not isinstance(wires, (tuple, list)):
            raise TypeError(
                "".join(
                    (
                        "ControlledPhaseGate wires must be a 2-tuple or ",
                        "list of integers.",
                    )
                ),
            )
        if len(wires) != 2:
            raise ValueError("ControlledPhaseGate requires exactly two wires.")
        theta_val = _validate_angle(theta, type(self).__name__)
        super().__init__(
            wires=wires,
            mat=np.diag([1.0, 1.0, 1.0, np.exp(1.0j * theta_val)]),
        )
        self.nickname = rf"$\mathrm{{CR}}_{{{_format_angle(theta_val)}}}$"

ControlledGate

Bases: BaseGate

General controlled-unitary gate.

Applies unitary to the target wires when the first control wire is in state \(|1\rangle\).

Parameters:

Name Type Description Default
control_wire int

0-based control-wire index.

required
unitary BaseGate

Unit U to apply to the target wires.

required
target_wires tuple[int, ...]

Ordered target-wire indices for U.

required
Source code in src/quantum_emotion/gates.py
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
class ControlledGate(BaseGate):
    r"""
    General controlled-unitary gate.

    Applies `unitary` to the target wires when the first control wire
    is in state $|1\rangle$.

    Args:
        control_wire: 0-based control-wire index.
        unitary: Unit U to apply to the target wires.
        target_wires: Ordered target-wire indices for U.
    """

    nickname = r"$\mathrm{CU}$"

    def __init__(
        self,
        control_wire: int,
        unitary: BaseGate,
        target_wires: tuple[int, ...],
    ) -> None:
        if isinstance(control_wire, bool) or not isinstance(control_wire, int):
            raise TypeError("control_wire must be an integer.")
        if not isinstance(unitary, BaseGate):
            raise TypeError("unitary must be a BaseGate.")
        if not unitary.is_unitary:
            raise ValueError("unitary must be unitary.")

        resolved_targets = tuple(target_wires)
        if len(resolved_targets) == 0:
            raise ValueError("ControlledGate requires target wires.")
        if len({control_wire, *resolved_targets}) != 1 + len(resolved_targets):
            raise ValueError(
                "ControlledGate control and target wires must be distinct."
            )
        if len(unitary.wires) != len(resolved_targets):
            raise ValueError(
                "The unitary and target wires must have the same length."
            )

        target_dimension = 2 ** len(resolved_targets)
        identity = np.eye(target_dimension, dtype=np.complex128)
        controlled_matrix = np.block(
            [
                [identity, np.zeros_like(identity)],
                [np.zeros_like(identity), unitary.mat],
            ]
        )
        super().__init__(
            wires=(control_wire, *resolved_targets),
            mat=controlled_matrix,
        )

BellModule

Bases: ModularGate

Two-qubit circuit preparing a Bell state from |00>.

The module applies a Hadamard gate to the first wire followed by a CNOT from the first wire to the second wire.

Source code in src/quantum_emotion/gates.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
class BellModule(ModularGate):
    r"""
    Two-qubit circuit preparing a Bell state from ``|00>``.

    The module applies a Hadamard gate to the first wire followed by a
    CNOT from the first wire to the second wire.
    """

    nickname = r"$\mathrm{Bell}$"

    def __init__(self, wires: tuple[int, int]) -> None:
        if not isinstance(wires, (tuple, list)):
            raise TypeError(
                "BellModule wires must be a 2-tuple or list of integers."
            )
        if len(wires) != 2:
            raise ValueError("BellModule requires exactly two wires.")
        super().__init__(
            CNOT(wires=wires),
            Hadamard(wires=wires[0]),
            wires=wires,
        )

SwapModule

Bases: ModularGate

Two-qubit module exchanging the quantum states of two wires.

Decomposes the \(\mathrm{SWAP}\) operation into three alternating \(\mathrm{CNOT}\) gates:

\[\mathrm{SWAP}_{a, b} = \mathrm{CNOT}_{a, b} \, \mathrm{CNOT}_{b, a} \, \mathrm{CNOT}_{a, b}\]

Parameters:

Name Type Description Default
wires tuple[int, int]

Two-wire tuple or list (wire_a, wire_b) of distinct 0-based indices.

required

Raises:

Type Description
TypeError

If wires is not a 2-tuple or list of integers.

ValueError

If wires does not contain two distinct non-negative integers.

Source code in src/quantum_emotion/gates.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
class SwapModule(ModularGate):
    r"""
    Two-qubit module exchanging the quantum states of two wires.

    Decomposes the $\mathrm{SWAP}$ operation into three alternating
    $\mathrm{CNOT}$ gates:

    $$\mathrm{SWAP}_{a, b} = \mathrm{CNOT}_{a, b} \, \mathrm{CNOT}_{b, a} \, \mathrm{CNOT}_{a, b}$$

    Args:
        wires: Two-wire tuple or list `(wire_a, wire_b)` of distinct
            0-based indices.

    Raises:
        TypeError: If `wires` is not a 2-tuple or list of integers.
        ValueError: If `wires` does not contain two distinct non-negative
            integers.
    """

    nickname = r"$\mathrm{SWAP}$"

    def __init__(self, wires: tuple[int, int]) -> None:
        if not isinstance(wires, (tuple, list)):
            raise TypeError(
                "SwapModule wires must be a 2-tuple or list of integers."
            )
        if len(wires) != 2:
            raise ValueError("SwapModule requires exactly two wires.")
        wire_a, wire_b = wires
        super().__init__(
            CNOT(wires=(wire_a, wire_b)),
            CNOT(wires=(wire_b, wire_a)),
            CNOT(wires=(wire_a, wire_b)),
            wires=wires,
        )

QFTModule

Bases: ModularGate

Quantum Fourier transform circuit.

The module applies the standard decomposition into Hadamard gates, controlled phase rotations, and final wire swaps. The wires are ordered from most significant to least significant in the Fourier transform convention.

Parameters:

Name Type Description Default
wires Sequence[int] | int

Ordered sequence of one or more distinct wires.

required
Source code in src/quantum_emotion/gates.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
class QFTModule(ModularGate):
    r"""
    Quantum Fourier transform circuit.

    The module applies the standard decomposition into Hadamard gates,
    controlled phase rotations, and final wire swaps. The wires are
    ordered from most significant to least significant in the Fourier
    transform convention.

    Args:
        wires: Ordered sequence of one or more distinct wires.
    """

    nickname = r"$\mathrm{QFT}$"

    def __init__(self, wires: Sequence[int] | int) -> None:
        if isinstance(wires, int) and not isinstance(wires, bool):
            resolved_wires = (wires,)
        elif isinstance(wires, Sequence) and not isinstance(
            wires, (str, bytes)
        ):
            resolved_wires = tuple(wires)
        else:
            raise TypeError(
                "QFTModule wires must be an integer or sequence of integers."
            )
        if len(resolved_wires) == 0:
            raise ValueError("QFTModule requires at least one wire.")
        if any(
            not isinstance(w, int) or isinstance(w, bool) or w < 0
            for w in resolved_wires
        ):
            raise ValueError(
                "All wire indices must be non-negative 0-based integers."
            )
        if len(set(resolved_wires)) != len(resolved_wires):
            raise ValueError(
                f"QFTModule wires must be unique, got {resolved_wires}."
            )

        application_order: list[BaseGate] = []
        for target_index, target_wire in enumerate(resolved_wires):
            application_order.append(Hadamard(wires=target_wire))
            for control_index in range(target_index + 1, len(resolved_wires)):
                angle = np.pi / (2 ** (control_index - target_index))
                application_order.append(
                    ControlledPhaseGate(
                        wires=(
                            resolved_wires[control_index],
                            target_wire,
                        ),
                        theta=angle,
                    )
                )

        for index in range(len(resolved_wires) // 2):
            left = resolved_wires[index]
            right = resolved_wires[-index - 1]
            application_order.extend(
                (
                    CNOT(wires=(left, right)),
                    CNOT(wires=(right, left)),
                    CNOT(wires=(left, right)),
                )
            )

        super().__init__(*reversed(application_order), wires=resolved_wires)

InverseQFTModule

Bases: ModularGate

Inverse quantum Fourier transform circuit, i.e. the conjugate of the standard QFT circuit: controlled phases and Hadamard gates are conjugated, and the gate order is reversed. The wire convention matches QFTModule, with wires ordered from most significant to least significant.

Parameters:

Name Type Description Default
wires tuple[int, ...]

Ordered sequence of one or more distinct wires.

required
Source code in src/quantum_emotion/gates.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
class InverseQFTModule(ModularGate):
    r"""
    Inverse quantum Fourier transform circuit, i.e. the conjugate of the
    standard QFT circuit: controlled phases and Hadamard gates are
    conjugated, and the gate order is reversed. The wire convention
    matches `QFTModule`, with wires ordered from most significant to
    least significant.

    Args:
        wires: Ordered sequence of one or more distinct wires.
    """

    nickname = r"$\mathrm{QFT}^{\dagger}$"

    def __init__(self, wires: tuple[int, ...]) -> None:
        resolved_wires = tuple(wires)
        if len(resolved_wires) == 0:
            raise ValueError("InverseQFTModule requires at least one wire.")
        if len(set(resolved_wires)) != len(resolved_wires):
            raise ValueError("InverseQFTModule wires must be distinct.")
        inverse = QFTModule(wires=resolved_wires).inverse()
        super().__init__(*inverse, wires=resolved_wires)

QPEModule

Bases: ModularGate

Quantum phase estimation circuit.

Applies Hadamard gates to the estimation register, controlled powers of an input unitary on the target register, and an inverse QFT over the estimation register.

Parameters:

Name Type Description Default
estimation_wires tuple[int, ...]

Ordered estimation-register wires.

required
target_wires tuple[int, ...]

Wires occupied by the unitary's eigenstate.

required
unitary BaseGate

A unitary gate whose matrix is the operation to estimate.

required
Source code in src/quantum_emotion/gates.py
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
class QPEModule(ModularGate):
    r"""
    Quantum phase estimation circuit.

    Applies Hadamard gates to the estimation register, controlled powers
    of an input unitary on the target register, and an inverse QFT over
    the estimation register.

    Args:
        estimation_wires: Ordered estimation-register wires.
        target_wires: Wires occupied by the unitary's eigenstate.
        unitary: A unitary gate whose matrix is the operation to
            estimate.
    """

    nickname = r"$\mathrm{QPE}$"

    def __init__(
        self,
        estimation_wires: tuple[int, ...],
        target_wires: tuple[int, ...],
        unitary: BaseGate,
    ) -> None:
        estimation = tuple(estimation_wires)
        target = tuple(target_wires)

        if len(estimation) == 0:
            raise ValueError("QPEModule requires estimation wires.")
        if len(set(estimation)) != len(estimation):
            raise ValueError("QPEModule estimation wires must be distinct.")
        if len(target) == 0:
            raise ValueError("QPEModule requires target wires.")
        if len(set(target)) != len(target):
            raise ValueError("QPEModule target wires must be distinct.")
        if set(estimation) & set(target):
            raise ValueError("Estimation and target wires must be disjoint.")
        if not isinstance(unitary, BaseGate):
            raise TypeError("unitary must be a BaseGate.")
        if len(unitary.wires) != len(target):
            raise ValueError(
                "The unitary and target wires must have the same length."
            )
        if not unitary.is_unitary:
            raise ValueError("unitary must be unitary.")

        application_order: list[BaseGate] = []
        for wire in estimation:
            application_order.append(Hadamard(wires=wire))

        for index, control_wire in enumerate(estimation):
            power = 2 ** (len(estimation) - index - 1)
            powered_unitary = BaseGate(
                wires=target,
                mat=np.linalg.matrix_power(unitary.mat, power),
            )
            application_order.append(
                ControlledGate(
                    control_wire=control_wire,
                    unitary=powered_unitary,
                    target_wires=target,
                )
            )

        inverse_qft = InverseQFTModule(wires=estimation)
        application_order.append(inverse_qft)

        super().__init__(
            *reversed(application_order),
            wires=(*estimation, *target),
        )

TeleportationModule

Bases: CompositeGate

Three-qubit quantum teleportation circuit.

Wire wires[0] contains the input state, while wires[1] and wires[2] are Alice's and Bob's entangled-pair wires. Alice's measurement results are recorded under keys and classically control Pauli corrections on Bob's wire.

Parameters:

Name Type Description Default
wires tuple[int, int, int]

Three distinct wires (input, Alice, Bob).

required
keys tuple[int | str, int | str]

Two classical measurement keys for the input and Alice wires, respectively.

('m0', 'm1')
Source code in src/quantum_emotion/gates.py
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
class TeleportationModule(CompositeGate):
    r"""
    Three-qubit quantum teleportation circuit.

    Wire ``wires[0]`` contains the input state, while ``wires[1]`` and
    ``wires[2]`` are Alice's and Bob's entangled-pair wires. Alice's
    measurement results are recorded under ``keys`` and classically
    control Pauli corrections on Bob's wire.

    Args:
        wires: Three distinct wires `(input, Alice, Bob)`.
        keys: Two classical measurement keys for the input and Alice
            wires, respectively.
    """

    is_module = True
    nickname = r"$\mathrm{Teleport}$"

    def __init__(
        self,
        wires: tuple[int, int, int],
        keys: tuple[int | str, int | str] = ("m0", "m1"),
    ) -> None:
        if not isinstance(wires, (tuple, list)):
            raise TypeError(
                "".join(
                    (
                        "TeleportationModule wires must be a 3-tuple or ",
                        "list of integers.",
                    )
                ),
            )
        if len(wires) != 3:
            raise ValueError(
                "TeleportationModule requires exactly three wires."
            )
        if len(set(wires)) != 3:
            raise ValueError("TeleportationModule wires must be distinct.")
        if not isinstance(keys, (tuple, list)):
            raise TypeError(
                "".join(
                    (
                        "TeleportationModule keys must be a 2-tuple or ",
                        "list of keys.",
                    )
                ),
            )
        if len(keys) != 2:
            raise ValueError("TeleportationModule requires exactly two keys.")

        input_wire, alice_wire, bob_wire = wires
        input_key, alice_key = keys
        super().__init__(
            PauliZ(wires=bob_wire).c_if(input_key),
            PauliX(wires=bob_wire).c_if(alice_key),
            Measure(
                wires=(input_wire, alice_wire),
                keys=keys,
            ),
            Hadamard(wires=input_wire),
            CNOT(wires=(input_wire, alice_wire)),
            CNOT(wires=(alice_wire, bob_wire)),
            Hadamard(wires=alice_wire),
        )