Skip to content

QuantumState

An extended class of Statevector from Qiskit.

This class extends the Statevector class from Qiskit to provide additional functionalities specific to quantum state manipulations and measurements.

Attributes:

Name Type Description
_num_of_qubit int

The number of qubits in the quantum state.

See Also

Qiskit Statevector documentation

Source code in QIRT/quantum_state.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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
class QuantumState:
    """An extended class of Statevector from Qiskit.

    This class extends the Statevector class from Qiskit to provide additional
    functionalities specific to quantum state manipulations and measurements.

    Attributes:
        _num_of_qubit (int): The number of qubits in the quantum state.

    See Also:
        [Qiskit Statevector documentation](https://qiskit.org/documentation/stubs/qiskit.quantum_info.Statevector.html)
    """

    # TODO: Add Bell measurement method.

    def __init__(
        self,
        data: np.ndarray | list | Statevector | Operator | QiskitQC | Instruction,
        dims: int | tuple | list | None = None,
    ):
        """Initialize a QuantumState object.

        This constructor initializes the QuantumState object by calling the
        constructor of the base Statevector class from Qiskit. It also calculates
        and stores the number of qubits in the quantum state.

        Args:
            data (np.array or list or Statevector or Operator or QuantumCircuit or qiskit.circuit.Instruction):
                Data from which the statevector can be constructed. This can be either a complex
                vector, another statevector, a ``Operator`` with only one column or a
                ``QuantumCircuit`` or ``Instruction``.  If the data is a circuit or instruction,
                the statevector is constructed by assuming that all qubits are initialized to the
                zero state.
            dims (int or tuple or list): Optional. The subsystem dimension of the state (See additional information).
        """
        if isinstance(data, (list | np.ndarray)):
            # Normalize the state vector
            data = np.asarray(data, dtype=complex)
            data /= np.linalg.norm(data)
        self.state_vector = Statevector(data, dims)
        self._num_of_qubit = int(np.log2(len(self.state_vector.data)))

    @property
    def data(self) -> NDArray[np.complex128]:
        """Get the data of the quantum state vector.

        This property returns the data of the quantum state vector stored in the object.

        Returns:
            NDArray[np.complex128]: The data of the quantum state vector.
        """
        return self.state_vector.data

    @property
    def num_of_qubit(self) -> int:
        """Get the number of qubits in the quantum state.

        This property returns the total number of qubits that are currently
        represented in the quantum state vector.

        Returns:
            int: The number of qubits in the quantum state.
        """
        return self._num_of_qubit

    @classmethod
    def from_label(cls, *args: str | tuple[complex, str]) -> QuantumState:
        """Create a state vector from input coefficients and label strings.

        Examples:
            >>> QuantumState.from_label("0", "1")
            (|0> + |1>)/√2 QuantumState object.

            >>> QuantumState.from_label("00", "01", "10", "11")
            (|00> + |01> + |10> + |11>)/2 = |++> QuantumState object.

            >>> QuantumState.from_label("+", (-1, "-"))
            (|+> - |->)/√2 QuantumState object.

            >>> QuantumState.from_label((2**0.5, "0"), "+", (-1, "-"))
            (√2|0> + |+> - |->)/2 = |+> QuantumState object.

            >>> QuantumState.from_label("0", (1j, "1"))
            (|0> + i|1>)/√2 = |i> QuantumState object.

        Args:
            args (str | Tuple[complex, str]): Input label strings or tuples of coefficients and label strings.

        Returns:
            QuantumState: The state vector object.

        Raises:
            QiskitError: If labels contain invalid characters or if labels have different numbers of qubits.
        """
        # Separate the input into coefficients and labels
        coefficients: list[complex] = []
        labels: list[str] = []
        for i, arg in enumerate(args):
            if isinstance(arg, tuple):  # Check if the input is a tuple of coefficient and label or just a label
                coefficients.append(arg[0])
                labels.append(arg[1])
            else:
                coefficients.append(1.0)
                labels.append(arg)

            if not Ket.check_valid(labels[i]):
                raise QiskitError("Invalid label string.")

            if len(labels[0]) != len(labels[i]):
                raise QiskitError("Each label's number of qubits must be the same.")

            labels[i] = Ket.to_qiskit_notation(labels[i])  # Convert the label to qiskit notation

        # Create the state vector based on the input
        state_vector: Statevector = Statevector.from_label(labels[0]) * coefficients[0]
        for coefficient, label in zip(coefficients[1:], labels[1:]):
            state_vector += Statevector.from_label(label) * coefficient

        state_vector /= state_vector.trace() ** 0.5  # Normalize the state
        return QuantumState(state_vector)

    def tensor(self, other: QuantumState) -> QuantumState:
        """Return the tensor product state self ⊗ other.

        This method calculates the tensor product of the quantum states stored in the
        object and another given quantum state, returning the resulting quantum state.

        Args:
            other (QuantumState): The other quantum state to tensor with.

        Returns:
            QuantumState: the tensor product operator self ⊗ other.
        """
        return QuantumState(self.state_vector.tensor(other.state_vector))

    def entropy(self) -> np.float64:
        """Calculate and return the Shannon  entropy of the quantum state.

        The Shannon  entropy is a measure of the quantum state's uncertainty or mixedness.

        Returns:
            np.float64: The Shannon  entropy of the quantum state, calculated in base 2.
        """
        entropy = stats.entropy(self.state_vector.probabilities(), base=2)
        if type(entropy) is np.float64:
            return entropy
        raise QiskitError("Entropy calculation failed.")

    def apply(self, other: QuantumCircuit, qargs: list[int] | None = None) -> QuantumState:
        """Apply a quantum circuit to the quantum state.

        This method applies the given operator to the quantum state, evolving it
        according to the operator's effect.

        Args:
            other (QuantumCircuit):
                The operator used to evolve the quantum state.
            qargs (list[int] | None, optional): A list of subsystem positions of
                the QuantumState to apply the operator on. Defaults to None.

        Returns:
            QuantumState: The quantum state after evolution.

        Raises:
            QiskitError: If the operator dimension does not match the specified
                quantum state subsystem dimensions.
        """
        # REVERSE the order of qubits to fit qiskit notation
        reversed_state_vector: Statevector = self.state_vector.reverse_qargs()
        evolved_state_vector: Statevector = reversed_state_vector.evolve(other._qiskit_qc, qargs).reverse_qargs()
        return QuantumState(evolved_state_vector)

    def to_matrix(self) -> NDArray[np.complex128]:
        """Convert the quantum state vector to a column matrix representation.

        This method takes the quantum state vector stored in the object and converts
        it into a column matrix form, which can be useful for various matrix-based
        operations and calculations.

        Returns:
            NDArray[np.complex128]: The quantum state represented as a column matrix.
        """
        flat_vector = self.state_vector.data
        matrix = flat_vector[np.newaxis].T
        return matrix

    # TODO: Add optional argument to disable coefficient simplification in draw() & draw_measurement() methods.
    # TODO: Add document about draw() & draw_measurement() methods' output options:
    #           target_basis can be "-" to hide the corresponding qubit or "*" to auto-choose basis.
    def draw(
        self,
        output: str = "latex",
        target_basis: list[str] | str | None = None,
        show_qubit_index: bool = True,
        output_length: int = 2,
        source: bool = False,
    ):
        """Visualize the statevector.

        This method provides different visualization options for the quantum state vector,
        such as LaTeX, matrix/vector form, or other specified formats.

        Args:
            output (str, optional): Visualization method. Defaults to "latex". Options include:
                - "matrix" or "vector": Outputs the QuantumState as a LaTeX formatted matrix.
                - "latex": Outputs the QuantumState as a LaTeX formatted expression.
                - "repr": ASCII TextMatrix of the QuantumState's `__repr__`.
                - "text": ASCII TextMatrix that can be printed in the console.
                - "qsphere": Matplotlib figure rendering the QuantumState using `plot_state_qsphere()`.
                - "hinton": Matplotlib figure rendering the QuantumState using `plot_state_hinton()`.
                - "bloch": Matplotlib figure rendering the QuantumState using `plot_bloch_multivector()`.
                - "city": Matplotlib figure rendering the QuantumState using `plot_state_city()`.
                - "paulivec": Matplotlib figure rendering the QuantumState using `plot_state_paulivec()`.
            target_basis (List[str] | str | None, optional): The target basis for visualization. Defaults to None.
            show_qubit_index (bool, optional): Whether to show qubit indices in the visualization. Defaults to True.
            output_length (int, optional): The number of terms in each line, defined as 2^output_length.
                Defaults to 2 (i.e., 4 terms per line).
            source (bool, optional): Whether to return the latex source code for the visualization option "matrix" and
                "latex". Defaults to False.

        Returns:
            (matplotlib.Figure | str | TextMatrix | IPython.display.Latex | Latex): The visualization
                output depending on the chosen method.
        """
        match output:
            case "matrix" | "vector":
                return latex_drawer.matrix_to_latex(self.to_matrix(), source=source)
            case "latex":
                return latex_drawer.state_to_latex(
                    state=self,
                    current_basis=["z"] * self.num_of_qubit,
                    target_basis=target_basis,
                    show_qubit_index=show_qubit_index,
                    output_length=output_length,
                    source=source,
                )
            case "repr" | "text" | "qsphere" | "hinton" | "city" | "paulivec":
                return self.state_vector.draw(output=output)
            case "bloch":
                reversed_state_vector = self.state_vector.reverse_qargs()
                return reversed_state_vector.draw(output=output)
            case _:
                raise QiskitError("Invalid output format.")

    def draw_measurement(
        self,
        measure_bit: list[int] | str,
        target_basis: list[str] | str = [],
        show_qubit_index: bool = True,
        output_length: int = 2,
        source: bool = False,
    ) -> str | Latex:
        """Visualize the measurement results of the quantum state.

        This method performs a measurement on specified qubits and visualizes the
        resulting quantum states and their measurement outcomes in a specified format.

        Args:
            measure_bit (List[int] | str): The bits (qubits) to measure. Can be a list
                of indices or a string specifying the bits.
            target_basis (List[str] | str, optional): The basis in which to perform the
                measurement. Defaults to basis with minimum entropy.
            show_qubit_index (bool, optional): Whether to show qubit indices in the
                visualization. Defaults to True.
            output_length (int, optional): The number of terms in each line, defined as
                2^output_length. Defaults to 2 (i.e., 4 terms per line).
            source (bool, optional): Whether to return the source code for the
                visualization. Defaults to False.

        Returns:
            (str | Latex): The visualization of the measurement results,
                either as an image or a string representing the source code.

        Raises:
            QiskitError: If the measurement basis or bit specifications are invalid.
        """
        _, _, measure_state_list, system_state_list, measure_basis, system_basis = self._measurement(
            measure_bit, target_basis
        )
        return latex_drawer.measure_result_to_latex(
            measure_state_list=measure_state_list,
            system_state_list=system_state_list,
            measure_basis=measure_basis,
            system_basis=system_basis,
            measure_bit=measure_bit,
            show_qubit_index=show_qubit_index,
            output_length=output_length,
            source=source,
        )

    def state_after_measurement(
        self, measure_bit: list[int] | str, target_basis: list[str] | str = []
    ) -> list[QuantumState]:
        """Simulate quantum measurement and return resulting states.

        This method simulates the measurement of specified qubits in a given basis and returns the possible
        post-measurement states of the system.

        Examples:
            >>> state = QuantumState.from_label("000", "111")

            Measure qubit 0 in Z-basis:
            >>> z_states = state.state_after_measurement(measure_bit=[0], target_basis="z--")
            >>> z_states[0].draw()
            |000>
            >>> z_states[1].draw()
            |111>

            Measure qubit 0 in X-basis:
            >>> x_states = state.state_after_measurement(measure_bit=[0], target_basis="x--")
            >>> x_states[0].draw()
            1/√2(|+++> + |+-->)
            >>> x_states[1].draw()
            1/√2(|-+-> - |--+>)

            Measure qubit 0 in Y-basis:
            >>> y_states = state.state_after_measurement(measure_bit=[0], target_basis="y--")
            >>> y_states[0].draw()
            1/√2(|i00> - i|i11>)
            >>> y_states[1].draw()
            1/√2(|j00> + i|j11>)

            Measure qubit 2 in Y-basis:
            >>> y_states = state.state_after_measurement(measure_bit=[2], target_basis="--y")
            >>> y_states[0].draw()
            1/√2(|00i> - i|11i>)
            >>> y_states[1].draw()
            1/√2(|00j> + i|11j>)

            Measure qubits 1 and 2 in X-basis:
            >>> x_states = state.state_after_measurement(measure_bit=[1, 2], target_basis="-xx")
            >>> x_states[0b00].draw()
            |+++>
            >>> x_states[0b01].draw()
            |-+->
            >>> x_states[0b10].draw()
            |--+>
            >>> x_states[0b11].draw()
            |+-->

        Understanding and Using the Results:
            1. List Structure:
            The returned list contains QuantumState objects, each representing a possible
            post-measurement state. The number of states in the list depends on the number
            of measured qubits.

            2. Indexing:
            - For a single qubit measurement (in any basis: Z, X, or Y):
                * states[0]: State corresponding to the measurement result '0'
                * states[1]: State corresponding to the measurement result '1'
            - For multi-qubit measurements:
                The index corresponds to the binary representation of the measurement outcome.
                E.g., for a two-qubit measurement:
                * states[0b00]: Outcome '00'
                * states[0b01]: Outcome '01'
                * states[0b10]: Outcome '10'
                * states[0b11]: Outcome '11'

            3. Basis-Specific Interpretations:
            - Z-basis: '0' represents |0>, '1' represents |1>
            - X-basis: '0' represents |+>, '1' represents |->
            - Y-basis: '0' represents |+i>, '1' represents |-i>

        Args:
            measure_bit (List[int] | str): Indices of qubits to be measured. Can be a list of integers
                or a string of qubit indices (e.g., "01" for qubits 0 and 1).
            target_basis (List[str] | str, optional): Measurement basis for each measured qubit.
                Supported bases are "x", "y", "z". If not specified, Z-basis is used by default.
                Can be a list of strings or a string (e.g., ["x", "z"] or "xz").

        Returns:
            List[QuantumState]: A list of possible post-measurement quantum states. Each state
            represents a possible outcome of the measurement process.
        """
        _, z_basis_system_state_list, _, _, _, _ = self._measurement(measure_bit=measure_bit, target_basis=target_basis)
        return z_basis_system_state_list

    def _basis_convert(
        self,
        target_basis: list[str] | str = [],
        current_basis: list[str] | str = [],
        algorithm: str = "local",
    ) -> tuple[QuantumState, list[str]]:
        """Convert the quantum state to a target basis.

        This method converts the quantum state from its current basis to a specified
        target basis using a quantum circuit. If the target basis is not fully specified,
        it will auto-choose the basis with minimum entropy for unspecified qubits.

        Args:
            target_basis (List[str] | str, optional): The target basis for conversion. Defaults to an empty list.
            current_basis (List[str] | str, optional): The current basis of the quantum state.
                Defaults to an empty list.
            algorithm (str, optional): The algorithm used for finding the minimum entropy basis. Defaults to "global".
                Options are:
                - "global": Global minimum entropy basis conversion.
                - "local": Local minimum entropy basis conversion.

        Returns:
            (tuple[QuantumState, List[str]]): The converted quantum state and the list of the basis used for conversion.

        Raises:
            QiskitError: If the input basis is invalid or if an invalid algorithm is specified.
        """
        # Default target_basis is auto choose basis with minimum entropy (basis = "*")
        target_basis = list(target_basis) + ["*"] * (self.num_of_qubit - len(target_basis))
        # Default current_basis is Z basis
        current_basis = list(current_basis) + ["z"] * (self.num_of_qubit - len(current_basis))

        # Check if input is valid
        if re.match(R"^[\-\*xyz]+$", "".join(target_basis)) is None:
            raise QiskitError("Invalid basis.")

        # Empty list to save auto-choose-basis index
        auto_basis_index = []
        # Convert basis using QuantumCircuit
        convert_circ = QuantumCircuit(self.num_of_qubit)
        for i in range(self.num_of_qubit):
            if target_basis[i] == current_basis[i]:
                continue
            if target_basis[i] == "*" or target_basis[i] == "-":
                auto_basis_index.append(i)
                continue
            convert_circ._xyz_convert_circ(target_basis=target_basis[i], current_basis=current_basis[i], qubit_index=i)
            current_basis[i] = target_basis[i]

        converted_state = self.apply(convert_circ)
        if not auto_basis_index:
            return (converted_state, current_basis)

        # If user don't specify which basis to convert, convert basis to basis with minimum entropy
        match algorithm:
            case "global":
                if len(auto_basis_index) > 8:
                    print(
                        "Notice: global minimum entropy basis convert with more then 8 qubits might take a long time."
                    )
                optimize_basis = converted_state._global_min_entropy_basis(auto_basis_index, current_basis)
            case "local":
                optimize_basis = converted_state._local_min_entropy_basis(auto_basis_index, current_basis)
            case _:
                raise QiskitError("Invalid min_entropy_basis_find_method.")

        return converted_state._basis_convert(target_basis=optimize_basis, current_basis=current_basis)

    def _global_min_entropy_basis(self, auto_basis_index: list[int], current_basis: list[str]) -> list[str]:
        """Find the basis with global minimum entropy.

        This method searches for the basis configuration that minimizes the entropy
        of the quantum state globally, by trying all possible combinations of the
        specified bases at the auto-choose-basis indices.

        Args:
            auto_basis_index (List[int]): Indices of the qubits for which the basis
                should be auto-chosen to minimize entropy.
            current_basis (List[str]): The current basis of the quantum state.

        Returns:
            List[str]: The basis configuration with the global minimum entropy.
        """
        num_of_auto_basis = len(auto_basis_index)
        min_entropy = float("inf")
        min_basis = current_basis.copy()
        try_basis = current_basis.copy()
        for basis in itertools.product(["z", "x", "y"], repeat=num_of_auto_basis):
            for i in range(num_of_auto_basis):
                try_basis[auto_basis_index[i]] = basis[i]
                try_state = self._basis_convert(target_basis=try_basis, current_basis=current_basis)[0]
            if (entropy := try_state.entropy()) < min_entropy:
                min_entropy = entropy
                min_basis = try_basis.copy()
        return min_basis

    def _local_min_entropy_basis(self, auto_basis_index: list[int], current_basis: list[str]) -> list[str]:
        """Find the basis with local minimum entropy.

        This method searches for the basis configuration that locally minimizes the entropy
        of the quantum state by iteratively selecting the best basis for each qubit.

        Args:
            auto_basis_index (List[int]): Indices of the qubits for which the basis should be auto-chosen to
                minimize entropy.
            current_basis (List[str]): The current basis of the quantum state.

        Returns:
            List[str]: The basis configuration with the local minimum entropy.
        """
        # Step 1: Change all auto-choose-basis to y, e.g. [-, -, -, -] -> [z, z, z, z], calculate entropy
        # Step 2,3: Same as Step 1, but with x-basis and y-basis
        # Step 4: from Step 1 to 3, choose the basis with minimum entropy.
        min_entropy = float("inf")
        min_basis = current_basis.copy()
        for basis in ["z", "x", "y"]:
            try_basis = min_basis.copy()
            for i in auto_basis_index:
                try_basis[i] = basis
            try_state = self._basis_convert(target_basis=try_basis, current_basis=current_basis)[0]
            if (entropy := try_state.entropy()) < min_entropy:
                min_entropy = entropy
                min_basis = try_basis.copy()

        # Step 1: Change the first auto-choose-basis to y, e.g. [-, -, -, -] -> [y, -, -, -], calculate entropy,
        # Step 2,3: Same as Step 1, but with x-basis and z-basis
        # Step 4: from Step 1 to 3, choose the basis with minimum entropy.
        # Step 5: Repeat Step 1 to 4 for the second auto-choose-basis, and so on. (greedy)
        # e.g. [-, -, -, -] -> [x, -, -, -] -> [x, z, -, -] -> [x, z, y, -] -> [x, z, y, z]
        for i in auto_basis_index:
            try_basis = min_basis.copy()
            for basis in ["y", "x", "z"]:
                try_basis[i] = basis
                try_state = self._basis_convert(target_basis=try_basis, current_basis=current_basis)[0]
                if (entropy_tmp := try_state.entropy()) < min_entropy:
                    min_entropy = entropy_tmp
                    min_basis[i] = basis
        return min_basis

    def _measurement(
        self, measure_bit: list[int] | str, target_basis: list[str] | str = []
    ) -> tuple[list[QuantumState], list[QuantumState], list[QuantumState], list[QuantumState], list[str], list[str]]:
        """Perform a measurement on the quantum state.

        This method measures the specified qubits in the given basis and returns the
        resulting quantum states and measurement outcomes.

        Args:
            measure_bit (List[int] | str): The bits (qubits) to measure. Can be a list
                of indices or a string specifying the bits.
            target_basis (List[str] | str, optional): The basis in which to perform the
                measurement. Defaults to basis with minimum entropy.

        Returns:
            (tuple[list[QuantumState], list[QuantumState], list[QuantumState], list[QuantumState], list[str], list[str]]):
                - z_basis_measure_state_list: Measurement states in the Z basis.
                - z_basis_system_state_list: System states in the Z basis.
                - measure_state_list: Measurement states in the original basis.
                - system_state_list: System states in the original basis.
                - measure_basis: The basis used for the measurement.
                - system_basis: The system basis after conversion.
        """  # noqa: E501
        if isinstance(measure_bit, str):
            measure_bit = [int(i) for i in measure_bit]

        converted_state, system_basis = self._basis_convert(
            target_basis=target_basis, current_basis=["z"] * self.num_of_qubit
        )
        measure_basis = [system_basis[i] for i in measure_bit]

        # crate empty list for output
        z_basis_measure_state_list: list[QuantumState] = [None] * 2 ** len(measure_bit)
        z_basis_system_state_list: list[QuantumState] = [None] * 2 ** len(measure_bit)
        measure_state_list: list[QuantumState] = [None] * 2 ** len(measure_bit)
        system_state_list: list[QuantumState] = [None] * 2 ** len(measure_bit)

        for i in range(2 ** len(measure_bit)):
            # Convert i to binary string with leading zeros
            project_label = format(i, f"0{len(measure_bit)}b")

            # Perform projection measurement
            system_state = converted_state._perform_projection_measurement(measure_bit, project_label)
            if system_state is None:
                continue

            measure_state_label = "".join(
                Ket.from_basis_and_label(basis, label) for basis, label in zip(measure_basis, project_label)
            )
            z_basis_measure_state = self.from_label(measure_state_label)

            z_basis_measure_state_list[i] = z_basis_measure_state
            z_basis_system_state_list[i] = system_state._basis_convert(
                target_basis=["z"] * self.num_of_qubit, current_basis=system_basis
            )[0]
            measure_state_list[i] = z_basis_measure_state._basis_convert(target_basis=measure_basis)[0]
            system_state_list[i] = system_state

        return (
            z_basis_measure_state_list,
            z_basis_system_state_list,
            measure_state_list,
            system_state_list,
            measure_basis,
            system_basis,
        )

    def _perform_projection_measurement(self, measure_bit: list[int], project_label: str) -> QuantumState | None:
        """Perform a projection measurement on the given quantum state.

        This method performs a projection measurement on the specified qubits in the given projection
        state and returns the post-measurement system state.

        Args:
            measure_bit (List[int]): The indices of qubits to measure.
            project_label (str): The label of the projection state.
                For example, "0" for |0><0|, "1" for |1><1|, "0+" for |0+><0+|, etc.

        Returns:
            QuantumState | None: The post-measurement system state, or None if the state is zero.
        """
        project_label = Ket.to_qiskit_notation(project_label)
        extend_project_label = ["I"] * self.num_of_qubit
        for bit, label in zip(measure_bit, project_label):
            extend_project_label[bit] = label
        project_operator = Operator.from_label("".join(extend_project_label))

        result_state_vector = self.state_vector.evolve(project_operator)

        normalize_factor = result_state_vector.trace() ** 0.5
        if normalize_factor < 1e-10:
            return None
        result_state_vector /= normalize_factor
        return QuantumState(result_state_vector)

    def _perform_single_shot_measurement(self, measure_bit: list[int]) -> tuple[str, QuantumState]:
        """Perform a single shot measurement on the given quantum state.

        This method measures the specified qubits in the given state and returns
        the measurement result along with the post-measurement system state.

        Args:
            measure_bit (List[int]): The indices of qubits to measure.

        Returns:
            Tuple[str, QuantumState]: A tuple containing:
                - measure_ket (str): The measurement result as a ket string.
                - system_state (QuantumState): The post-measurement system state.

        Note:
            This method reverses qubit ordering to match Qiskit's notation for measurement,
            and then reverses the result to match standard textbook notation.
        """
        measure_result: tuple[str, Statevector] = Statevector(self.data).measure(
            qargs=[self.num_of_qubit - 1 - i for i in measure_bit]  # REVERSE the order of qubits to fit qiskit notation
        )
        measure_ket: str = measure_result[0][::-1]  # REVERSE the order of qubits to fit textbook notation
        system_state = QuantumState(measure_result[1])
        return measure_ket, system_state

data: NDArray[np.complex128] property

Get the data of the quantum state vector.

This property returns the data of the quantum state vector stored in the object.

Returns:

Type Description
NDArray[complex128]

NDArray[np.complex128]: The data of the quantum state vector.

num_of_qubit: int property

Get the number of qubits in the quantum state.

This property returns the total number of qubits that are currently represented in the quantum state vector.

Returns:

Name Type Description
int int

The number of qubits in the quantum state.

__init__(data, dims=None)

Initialize a QuantumState object.

This constructor initializes the QuantumState object by calling the constructor of the base Statevector class from Qiskit. It also calculates and stores the number of qubits in the quantum state.

Parameters:

Name Type Description Default
data array or list or Statevector or Operator or QuantumCircuit or Instruction

Data from which the statevector can be constructed. This can be either a complex vector, another statevector, a Operator with only one column or a QuantumCircuit or Instruction. If the data is a circuit or instruction, the statevector is constructed by assuming that all qubits are initialized to the zero state.

required
dims int or tuple or list

Optional. The subsystem dimension of the state (See additional information).

None
Source code in QIRT/quantum_state.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(
    self,
    data: np.ndarray | list | Statevector | Operator | QiskitQC | Instruction,
    dims: int | tuple | list | None = None,
):
    """Initialize a QuantumState object.

    This constructor initializes the QuantumState object by calling the
    constructor of the base Statevector class from Qiskit. It also calculates
    and stores the number of qubits in the quantum state.

    Args:
        data (np.array or list or Statevector or Operator or QuantumCircuit or qiskit.circuit.Instruction):
            Data from which the statevector can be constructed. This can be either a complex
            vector, another statevector, a ``Operator`` with only one column or a
            ``QuantumCircuit`` or ``Instruction``.  If the data is a circuit or instruction,
            the statevector is constructed by assuming that all qubits are initialized to the
            zero state.
        dims (int or tuple or list): Optional. The subsystem dimension of the state (See additional information).
    """
    if isinstance(data, (list | np.ndarray)):
        # Normalize the state vector
        data = np.asarray(data, dtype=complex)
        data /= np.linalg.norm(data)
    self.state_vector = Statevector(data, dims)
    self._num_of_qubit = int(np.log2(len(self.state_vector.data)))

apply(other, qargs=None)

Apply a quantum circuit to the quantum state.

This method applies the given operator to the quantum state, evolving it according to the operator's effect.

Parameters:

Name Type Description Default
other QuantumCircuit

The operator used to evolve the quantum state.

required
qargs list[int] | None

A list of subsystem positions of the QuantumState to apply the operator on. Defaults to None.

None

Returns:

Name Type Description
QuantumState QuantumState

The quantum state after evolution.

Raises:

Type Description
QiskitError

If the operator dimension does not match the specified quantum state subsystem dimensions.

Source code in QIRT/quantum_state.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def apply(self, other: QuantumCircuit, qargs: list[int] | None = None) -> QuantumState:
    """Apply a quantum circuit to the quantum state.

    This method applies the given operator to the quantum state, evolving it
    according to the operator's effect.

    Args:
        other (QuantumCircuit):
            The operator used to evolve the quantum state.
        qargs (list[int] | None, optional): A list of subsystem positions of
            the QuantumState to apply the operator on. Defaults to None.

    Returns:
        QuantumState: The quantum state after evolution.

    Raises:
        QiskitError: If the operator dimension does not match the specified
            quantum state subsystem dimensions.
    """
    # REVERSE the order of qubits to fit qiskit notation
    reversed_state_vector: Statevector = self.state_vector.reverse_qargs()
    evolved_state_vector: Statevector = reversed_state_vector.evolve(other._qiskit_qc, qargs).reverse_qargs()
    return QuantumState(evolved_state_vector)

draw(output='latex', target_basis=None, show_qubit_index=True, output_length=2, source=False)

Visualize the statevector.

This method provides different visualization options for the quantum state vector, such as LaTeX, matrix/vector form, or other specified formats.

Parameters:

Name Type Description Default
output str

Visualization method. Defaults to "latex". Options include: - "matrix" or "vector": Outputs the QuantumState as a LaTeX formatted matrix. - "latex": Outputs the QuantumState as a LaTeX formatted expression. - "repr": ASCII TextMatrix of the QuantumState's __repr__. - "text": ASCII TextMatrix that can be printed in the console. - "qsphere": Matplotlib figure rendering the QuantumState using plot_state_qsphere(). - "hinton": Matplotlib figure rendering the QuantumState using plot_state_hinton(). - "bloch": Matplotlib figure rendering the QuantumState using plot_bloch_multivector(). - "city": Matplotlib figure rendering the QuantumState using plot_state_city(). - "paulivec": Matplotlib figure rendering the QuantumState using plot_state_paulivec().

'latex'
target_basis List[str] | str | None

The target basis for visualization. Defaults to None.

None
show_qubit_index bool

Whether to show qubit indices in the visualization. Defaults to True.

True
output_length int

The number of terms in each line, defined as 2^output_length. Defaults to 2 (i.e., 4 terms per line).

2
source bool

Whether to return the latex source code for the visualization option "matrix" and "latex". Defaults to False.

False

Returns:

Type Description
Figure | str | TextMatrix | Latex | Latex

The visualization output depending on the chosen method.

Source code in QIRT/quantum_state.py
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
def draw(
    self,
    output: str = "latex",
    target_basis: list[str] | str | None = None,
    show_qubit_index: bool = True,
    output_length: int = 2,
    source: bool = False,
):
    """Visualize the statevector.

    This method provides different visualization options for the quantum state vector,
    such as LaTeX, matrix/vector form, or other specified formats.

    Args:
        output (str, optional): Visualization method. Defaults to "latex". Options include:
            - "matrix" or "vector": Outputs the QuantumState as a LaTeX formatted matrix.
            - "latex": Outputs the QuantumState as a LaTeX formatted expression.
            - "repr": ASCII TextMatrix of the QuantumState's `__repr__`.
            - "text": ASCII TextMatrix that can be printed in the console.
            - "qsphere": Matplotlib figure rendering the QuantumState using `plot_state_qsphere()`.
            - "hinton": Matplotlib figure rendering the QuantumState using `plot_state_hinton()`.
            - "bloch": Matplotlib figure rendering the QuantumState using `plot_bloch_multivector()`.
            - "city": Matplotlib figure rendering the QuantumState using `plot_state_city()`.
            - "paulivec": Matplotlib figure rendering the QuantumState using `plot_state_paulivec()`.
        target_basis (List[str] | str | None, optional): The target basis for visualization. Defaults to None.
        show_qubit_index (bool, optional): Whether to show qubit indices in the visualization. Defaults to True.
        output_length (int, optional): The number of terms in each line, defined as 2^output_length.
            Defaults to 2 (i.e., 4 terms per line).
        source (bool, optional): Whether to return the latex source code for the visualization option "matrix" and
            "latex". Defaults to False.

    Returns:
        (matplotlib.Figure | str | TextMatrix | IPython.display.Latex | Latex): The visualization
            output depending on the chosen method.
    """
    match output:
        case "matrix" | "vector":
            return latex_drawer.matrix_to_latex(self.to_matrix(), source=source)
        case "latex":
            return latex_drawer.state_to_latex(
                state=self,
                current_basis=["z"] * self.num_of_qubit,
                target_basis=target_basis,
                show_qubit_index=show_qubit_index,
                output_length=output_length,
                source=source,
            )
        case "repr" | "text" | "qsphere" | "hinton" | "city" | "paulivec":
            return self.state_vector.draw(output=output)
        case "bloch":
            reversed_state_vector = self.state_vector.reverse_qargs()
            return reversed_state_vector.draw(output=output)
        case _:
            raise QiskitError("Invalid output format.")

draw_measurement(measure_bit, target_basis=[], show_qubit_index=True, output_length=2, source=False)

Visualize the measurement results of the quantum state.

This method performs a measurement on specified qubits and visualizes the resulting quantum states and their measurement outcomes in a specified format.

Parameters:

Name Type Description Default
measure_bit List[int] | str

The bits (qubits) to measure. Can be a list of indices or a string specifying the bits.

required
target_basis List[str] | str

The basis in which to perform the measurement. Defaults to basis with minimum entropy.

[]
show_qubit_index bool

Whether to show qubit indices in the visualization. Defaults to True.

True
output_length int

The number of terms in each line, defined as 2^output_length. Defaults to 2 (i.e., 4 terms per line).

2
source bool

Whether to return the source code for the visualization. Defaults to False.

False

Returns:

Type Description
str | Latex

The visualization of the measurement results, either as an image or a string representing the source code.

Raises:

Type Description
QiskitError

If the measurement basis or bit specifications are invalid.

Source code in QIRT/quantum_state.py
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
def draw_measurement(
    self,
    measure_bit: list[int] | str,
    target_basis: list[str] | str = [],
    show_qubit_index: bool = True,
    output_length: int = 2,
    source: bool = False,
) -> str | Latex:
    """Visualize the measurement results of the quantum state.

    This method performs a measurement on specified qubits and visualizes the
    resulting quantum states and their measurement outcomes in a specified format.

    Args:
        measure_bit (List[int] | str): The bits (qubits) to measure. Can be a list
            of indices or a string specifying the bits.
        target_basis (List[str] | str, optional): The basis in which to perform the
            measurement. Defaults to basis with minimum entropy.
        show_qubit_index (bool, optional): Whether to show qubit indices in the
            visualization. Defaults to True.
        output_length (int, optional): The number of terms in each line, defined as
            2^output_length. Defaults to 2 (i.e., 4 terms per line).
        source (bool, optional): Whether to return the source code for the
            visualization. Defaults to False.

    Returns:
        (str | Latex): The visualization of the measurement results,
            either as an image or a string representing the source code.

    Raises:
        QiskitError: If the measurement basis or bit specifications are invalid.
    """
    _, _, measure_state_list, system_state_list, measure_basis, system_basis = self._measurement(
        measure_bit, target_basis
    )
    return latex_drawer.measure_result_to_latex(
        measure_state_list=measure_state_list,
        system_state_list=system_state_list,
        measure_basis=measure_basis,
        system_basis=system_basis,
        measure_bit=measure_bit,
        show_qubit_index=show_qubit_index,
        output_length=output_length,
        source=source,
    )

entropy()

Calculate and return the Shannon entropy of the quantum state.

The Shannon entropy is a measure of the quantum state's uncertainty or mixedness.

Returns:

Type Description
float64

np.float64: The Shannon entropy of the quantum state, calculated in base 2.

Source code in QIRT/quantum_state.py
180
181
182
183
184
185
186
187
188
189
190
191
def entropy(self) -> np.float64:
    """Calculate and return the Shannon  entropy of the quantum state.

    The Shannon  entropy is a measure of the quantum state's uncertainty or mixedness.

    Returns:
        np.float64: The Shannon  entropy of the quantum state, calculated in base 2.
    """
    entropy = stats.entropy(self.state_vector.probabilities(), base=2)
    if type(entropy) is np.float64:
        return entropy
    raise QiskitError("Entropy calculation failed.")

from_label(*args) classmethod

Create a state vector from input coefficients and label strings.

Examples:

>>> QuantumState.from_label("0", "1")
(|0> + |1>)/√2 QuantumState object.
>>> QuantumState.from_label("00", "01", "10", "11")
(|00> + |01> + |10> + |11>)/2 = |++> QuantumState object.
>>> QuantumState.from_label("+", (-1, "-"))
(|+> - |->)/√2 QuantumState object.
>>> QuantumState.from_label((2**0.5, "0"), "+", (-1, "-"))
(√2|0> + |+> - |->)/2 = |+> QuantumState object.
>>> QuantumState.from_label("0", (1j, "1"))
(|0> + i|1>)/√2 = |i> QuantumState object.

Parameters:

Name Type Description Default
args str | Tuple[complex, str]

Input label strings or tuples of coefficients and label strings.

()

Returns:

Name Type Description
QuantumState QuantumState

The state vector object.

Raises:

Type Description
QiskitError

If labels contain invalid characters or if labels have different numbers of qubits.

Source code in QIRT/quantum_state.py
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
@classmethod
def from_label(cls, *args: str | tuple[complex, str]) -> QuantumState:
    """Create a state vector from input coefficients and label strings.

    Examples:
        >>> QuantumState.from_label("0", "1")
        (|0> + |1>)/√2 QuantumState object.

        >>> QuantumState.from_label("00", "01", "10", "11")
        (|00> + |01> + |10> + |11>)/2 = |++> QuantumState object.

        >>> QuantumState.from_label("+", (-1, "-"))
        (|+> - |->)/√2 QuantumState object.

        >>> QuantumState.from_label((2**0.5, "0"), "+", (-1, "-"))
        (√2|0> + |+> - |->)/2 = |+> QuantumState object.

        >>> QuantumState.from_label("0", (1j, "1"))
        (|0> + i|1>)/√2 = |i> QuantumState object.

    Args:
        args (str | Tuple[complex, str]): Input label strings or tuples of coefficients and label strings.

    Returns:
        QuantumState: The state vector object.

    Raises:
        QiskitError: If labels contain invalid characters or if labels have different numbers of qubits.
    """
    # Separate the input into coefficients and labels
    coefficients: list[complex] = []
    labels: list[str] = []
    for i, arg in enumerate(args):
        if isinstance(arg, tuple):  # Check if the input is a tuple of coefficient and label or just a label
            coefficients.append(arg[0])
            labels.append(arg[1])
        else:
            coefficients.append(1.0)
            labels.append(arg)

        if not Ket.check_valid(labels[i]):
            raise QiskitError("Invalid label string.")

        if len(labels[0]) != len(labels[i]):
            raise QiskitError("Each label's number of qubits must be the same.")

        labels[i] = Ket.to_qiskit_notation(labels[i])  # Convert the label to qiskit notation

    # Create the state vector based on the input
    state_vector: Statevector = Statevector.from_label(labels[0]) * coefficients[0]
    for coefficient, label in zip(coefficients[1:], labels[1:]):
        state_vector += Statevector.from_label(label) * coefficient

    state_vector /= state_vector.trace() ** 0.5  # Normalize the state
    return QuantumState(state_vector)

state_after_measurement(measure_bit, target_basis=[])

Simulate quantum measurement and return resulting states.

This method simulates the measurement of specified qubits in a given basis and returns the possible post-measurement states of the system.

Examples:

>>> state = QuantumState.from_label("000", "111")

Measure qubit 0 in Z-basis:

>>> z_states = state.state_after_measurement(measure_bit=[0], target_basis="z--")
>>> z_states[0].draw()
|000>
>>> z_states[1].draw()
|111>

Measure qubit 0 in X-basis:

>>> x_states = state.state_after_measurement(measure_bit=[0], target_basis="x--")
>>> x_states[0].draw()
1/√2(|+++> + |+-->)
>>> x_states[1].draw()
1/√2(|-+-> - |--+>)

Measure qubit 0 in Y-basis:

>>> y_states = state.state_after_measurement(measure_bit=[0], target_basis="y--")
>>> y_states[0].draw()
1/√2(|i00> - i|i11>)
>>> y_states[1].draw()
1/√2(|j00> + i|j11>)

Measure qubit 2 in Y-basis:

>>> y_states = state.state_after_measurement(measure_bit=[2], target_basis="--y")
>>> y_states[0].draw()
1/√2(|00i> - i|11i>)
>>> y_states[1].draw()
1/√2(|00j> + i|11j>)

Measure qubits 1 and 2 in X-basis:

>>> x_states = state.state_after_measurement(measure_bit=[1, 2], target_basis="-xx")
>>> x_states[0b00].draw()
|+++>
>>> x_states[0b01].draw()
|-+->
>>> x_states[0b10].draw()
|--+>
>>> x_states[0b11].draw()
|+-->
Understanding and Using the Results
  1. List Structure: The returned list contains QuantumState objects, each representing a possible post-measurement state. The number of states in the list depends on the number of measured qubits.

  2. Indexing:

  3. For a single qubit measurement (in any basis: Z, X, or Y):
    • states[0]: State corresponding to the measurement result '0'
    • states[1]: State corresponding to the measurement result '1'
  4. For multi-qubit measurements: The index corresponds to the binary representation of the measurement outcome. E.g., for a two-qubit measurement:

    • states[0b00]: Outcome '00'
    • states[0b01]: Outcome '01'
    • states[0b10]: Outcome '10'
    • states[0b11]: Outcome '11'
  5. Basis-Specific Interpretations:

  6. Z-basis: '0' represents |0>, '1' represents |1>
  7. X-basis: '0' represents |+>, '1' represents |->
  8. Y-basis: '0' represents |+i>, '1' represents |-i>

Parameters:

Name Type Description Default
measure_bit List[int] | str

Indices of qubits to be measured. Can be a list of integers or a string of qubit indices (e.g., "01" for qubits 0 and 1).

required
target_basis List[str] | str

Measurement basis for each measured qubit. Supported bases are "x", "y", "z". If not specified, Z-basis is used by default. Can be a list of strings or a string (e.g., ["x", "z"] or "xz").

[]

Returns:

Type Description
list[QuantumState]

List[QuantumState]: A list of possible post-measurement quantum states. Each state

list[QuantumState]

represents a possible outcome of the measurement process.

Source code in QIRT/quantum_state.py
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
def state_after_measurement(
    self, measure_bit: list[int] | str, target_basis: list[str] | str = []
) -> list[QuantumState]:
    """Simulate quantum measurement and return resulting states.

    This method simulates the measurement of specified qubits in a given basis and returns the possible
    post-measurement states of the system.

    Examples:
        >>> state = QuantumState.from_label("000", "111")

        Measure qubit 0 in Z-basis:
        >>> z_states = state.state_after_measurement(measure_bit=[0], target_basis="z--")
        >>> z_states[0].draw()
        |000>
        >>> z_states[1].draw()
        |111>

        Measure qubit 0 in X-basis:
        >>> x_states = state.state_after_measurement(measure_bit=[0], target_basis="x--")
        >>> x_states[0].draw()
        1/√2(|+++> + |+-->)
        >>> x_states[1].draw()
        1/√2(|-+-> - |--+>)

        Measure qubit 0 in Y-basis:
        >>> y_states = state.state_after_measurement(measure_bit=[0], target_basis="y--")
        >>> y_states[0].draw()
        1/√2(|i00> - i|i11>)
        >>> y_states[1].draw()
        1/√2(|j00> + i|j11>)

        Measure qubit 2 in Y-basis:
        >>> y_states = state.state_after_measurement(measure_bit=[2], target_basis="--y")
        >>> y_states[0].draw()
        1/√2(|00i> - i|11i>)
        >>> y_states[1].draw()
        1/√2(|00j> + i|11j>)

        Measure qubits 1 and 2 in X-basis:
        >>> x_states = state.state_after_measurement(measure_bit=[1, 2], target_basis="-xx")
        >>> x_states[0b00].draw()
        |+++>
        >>> x_states[0b01].draw()
        |-+->
        >>> x_states[0b10].draw()
        |--+>
        >>> x_states[0b11].draw()
        |+-->

    Understanding and Using the Results:
        1. List Structure:
        The returned list contains QuantumState objects, each representing a possible
        post-measurement state. The number of states in the list depends on the number
        of measured qubits.

        2. Indexing:
        - For a single qubit measurement (in any basis: Z, X, or Y):
            * states[0]: State corresponding to the measurement result '0'
            * states[1]: State corresponding to the measurement result '1'
        - For multi-qubit measurements:
            The index corresponds to the binary representation of the measurement outcome.
            E.g., for a two-qubit measurement:
            * states[0b00]: Outcome '00'
            * states[0b01]: Outcome '01'
            * states[0b10]: Outcome '10'
            * states[0b11]: Outcome '11'

        3. Basis-Specific Interpretations:
        - Z-basis: '0' represents |0>, '1' represents |1>
        - X-basis: '0' represents |+>, '1' represents |->
        - Y-basis: '0' represents |+i>, '1' represents |-i>

    Args:
        measure_bit (List[int] | str): Indices of qubits to be measured. Can be a list of integers
            or a string of qubit indices (e.g., "01" for qubits 0 and 1).
        target_basis (List[str] | str, optional): Measurement basis for each measured qubit.
            Supported bases are "x", "y", "z". If not specified, Z-basis is used by default.
            Can be a list of strings or a string (e.g., ["x", "z"] or "xz").

    Returns:
        List[QuantumState]: A list of possible post-measurement quantum states. Each state
        represents a possible outcome of the measurement process.
    """
    _, z_basis_system_state_list, _, _, _, _ = self._measurement(measure_bit=measure_bit, target_basis=target_basis)
    return z_basis_system_state_list

tensor(other)

Return the tensor product state self ⊗ other.

This method calculates the tensor product of the quantum states stored in the object and another given quantum state, returning the resulting quantum state.

Parameters:

Name Type Description Default
other QuantumState

The other quantum state to tensor with.

required

Returns:

Name Type Description
QuantumState QuantumState

the tensor product operator self ⊗ other.

Source code in QIRT/quantum_state.py
166
167
168
169
170
171
172
173
174
175
176
177
178
def tensor(self, other: QuantumState) -> QuantumState:
    """Return the tensor product state self ⊗ other.

    This method calculates the tensor product of the quantum states stored in the
    object and another given quantum state, returning the resulting quantum state.

    Args:
        other (QuantumState): The other quantum state to tensor with.

    Returns:
        QuantumState: the tensor product operator self ⊗ other.
    """
    return QuantumState(self.state_vector.tensor(other.state_vector))

to_matrix()

Convert the quantum state vector to a column matrix representation.

This method takes the quantum state vector stored in the object and converts it into a column matrix form, which can be useful for various matrix-based operations and calculations.

Returns:

Type Description
NDArray[complex128]

NDArray[np.complex128]: The quantum state represented as a column matrix.

Source code in QIRT/quantum_state.py
217
218
219
220
221
222
223
224
225
226
227
228
229
def to_matrix(self) -> NDArray[np.complex128]:
    """Convert the quantum state vector to a column matrix representation.

    This method takes the quantum state vector stored in the object and converts
    it into a column matrix form, which can be useful for various matrix-based
    operations and calculations.

    Returns:
        NDArray[np.complex128]: The quantum state represented as a column matrix.
    """
    flat_vector = self.state_vector.data
    matrix = flat_vector[np.newaxis].T
    return matrix