Skip to content

Physics

inspeqtor.physics

inspeqtor.physics.solver

solver(
    args: HamiltonianArgs,
    t_eval: ndarray,
    hamiltonian: Callable[
        [HamiltonianArgs, ndarray], ndarray
    ],
    y0: ndarray,
    t0: float,
    t1: float,
    rtol: float = 1e-07,
    atol: float = 1e-07,
    max_steps: int = int(2**16),
) -> ndarray

Solve the Schrodinger equation using the given Hamiltonian

Parameters:

Name Type Description Default
args HamiltonianArgs

The arguments for the Hamiltonian

required
t_eval ndarray

The time points to evaluate the solution

required
hamiltonian Callable[[HamiltonianArgs, ndarray], ndarray]

The Hamiltonian function

required
y0 ndarray

The initial state, set to jnp.eye(2, dtype=jnp.complex128) for unitary matrix

required
t0 float

The initial time

required
t1 float

The final time

required
rtol float

description. Defaults to 1e-7.

1e-07
atol float

description. Defaults to 1e-7.

1e-07
max_steps int

The maxmimum step of evalution of solver. Defaults to int(2**16).

int(2 ** 16)

Returns:

Type Description
ndarray

jnp.ndarray: The solution of the Schrodinger equation at the given time points

Source code in src/inspeqtor/v1/physics.py
 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
def solver(
    args: HamiltonianArgs,
    t_eval: jnp.ndarray,
    hamiltonian: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
    y0: jnp.ndarray,
    t0: float,
    t1: float,
    rtol: float = 1e-7,
    atol: float = 1e-7,
    max_steps: int = int(2**16),
) -> jnp.ndarray:
    """Solve the Schrodinger equation using the given Hamiltonian

    Args:
        args (HamiltonianArgs): The arguments for the Hamiltonian
        t_eval (jnp.ndarray): The time points to evaluate the solution
        hamiltonian (typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray]): The Hamiltonian function
        y0 (jnp.ndarray): The initial state, set to jnp.eye(2, dtype=jnp.complex128) for unitary matrix
        t0 (float): The initial time
        t1 (float): The final time
        rtol (float, optional): _description_. Defaults to 1e-7.
        atol (float, optional): _description_. Defaults to 1e-7.
        max_steps (int, optional): The maxmimum step of evalution of solver. Defaults to int(2**16).

    Returns:
        jnp.ndarray: The solution of the Schrodinger equation at the given time points
    """

    # * Increase time_step to increase accuracy of solver,
    # *     then you have to increase the max_steps too.
    # * Using just a basic solver
    def rhs(t: jnp.ndarray, y: jnp.ndarray, args: HamiltonianArgs):
        return -1j * hamiltonian(args, t) @ y

    term = diffrax.ODETerm(rhs)  # type: ignore
    solver = diffrax.Tsit5()

    solution = diffrax.diffeqsolve(
        term,
        solver,
        t0=t0,
        t1=t1,
        dt0=None,
        stepsize_controller=diffrax.PIDController(
            rtol=rtol,
            atol=atol,
        ),
        y0=y0,
        args=args,
        saveat=diffrax.SaveAt(ts=t_eval),
        max_steps=max_steps,
    )

    # Normailized the solution
    ys = solution.ys
    # assert isinstance(ys, jnp.ndarray)

    return jax.vmap(normalizer)(ys)  # type: ignore

inspeqtor.physics.auto_rotating_frame_hamiltonian

auto_rotating_frame_hamiltonian(
    hamiltonian: Callable[
        [HamiltonianArgs, ndarray], ndarray
    ],
    frame: ndarray,
    explicit_deriv: bool = False,
)

Implement the Hamiltonian in the rotating frame with H_I = U(t) @ H @ U^dagger(t) + i * U(t) @ dU^dagger(t)/dt

Parameters:

Name Type Description Default
hamiltonian Callable

The hamiltonian function

required
frame ndarray

The frame matrix

required
Source code in src/inspeqtor/v1/physics.py
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
def auto_rotating_frame_hamiltonian(
    hamiltonian: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
    frame: jnp.ndarray,
    explicit_deriv: bool = False,
):
    """Implement the Hamiltonian in the rotating frame with
    H_I = U(t) @ H @ U^dagger(t) + i * U(t) @ dU^dagger(t)/dt

    Args:
        hamiltonian (Callable): The hamiltonian function
        frame (jnp.ndarray): The frame matrix
    """

    is_diagonal = False
    # Check if the frame is diagonal matrix
    if jnp.count_nonzero(frame - jnp.diag(jnp.diagonal(frame))) == 0:
        is_diagonal = True

    # Check if the jax_enable_x64 is True
    if not jax.config.read("jax_enable_x64") or is_diagonal:

        def frame_unitary(t: jnp.ndarray) -> jnp.ndarray:
            # NOTE: This is the same as the below, as we sure that the frame is diagonal
            return jnp.diag(jnp.exp(1j * jnp.diagonal(frame) * t))

    else:

        def frame_unitary(t: jnp.ndarray) -> jnp.ndarray:
            return jax.scipy.linalg.expm(1j * frame * t)

    def derivative_frame_unitary(t: jnp.ndarray) -> jnp.ndarray:
        # NOTE: Assume that the frame is time independent.
        return 1j * frame @ frame_unitary(t)

    def rotating_frame_hamiltonian_v0(args: HamiltonianArgs, t: jnp.ndarray):
        return frame_unitary(t) @ hamiltonian(args, t) @ jnp.transpose(
            jnp.conjugate(frame_unitary(t))
        ) + 1j * (
            derivative_frame_unitary(t) @ jnp.transpose(jnp.conjugate(frame_unitary(t)))
        )

    def rotating_frame_hamiltonian(args: HamiltonianArgs, t: jnp.ndarray):
        # NOTE: Assume that the product of derivative and conjugate of frame unitary is identity
        return (
            frame_unitary(t)
            @ hamiltonian(args, t)
            @ jnp.transpose(jnp.conjugate(frame_unitary(t)))
            - frame
        )

    return (
        rotating_frame_hamiltonian_v0 if explicit_deriv else rotating_frame_hamiltonian
    )

inspeqtor.physics.explicit_auto_rotating_frame_hamiltonian

explicit_auto_rotating_frame_hamiltonian(
    hamiltonian: Callable[
        [HamiltonianArgs, ndarray], ndarray
    ],
    frame: ndarray,
)

Implement the Hamiltonian in the rotating frame with H_I = U(t) @ H @ U^dagger(t) + i * U(t) @ dU^dagger(t)/dt

Note

This is the implementation of auto_rotating_frame_hamiltonian that perform explicit derivative.

Parameters:

Name Type Description Default
hamiltonian Callable

The hamiltonian function

required
frame ndarray

The frame matrix

required
Source code in src/inspeqtor/v1/physics.py
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
def explicit_auto_rotating_frame_hamiltonian(
    hamiltonian: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
    frame: jnp.ndarray,
):
    """Implement the Hamiltonian in the rotating frame with
    H_I = U(t) @ H @ U^dagger(t) + i * U(t) @ dU^dagger(t)/dt

    Note:
        This is the implementation of `auto_rotating_frame_hamiltonian`
        that perform explicit derivative.

    Args:
        hamiltonian (Callable): The hamiltonian function
        frame (jnp.ndarray): The frame matrix
    """

    def frame_unitary(t: jnp.ndarray) -> jnp.ndarray:
        return jax.scipy.linalg.expm(1j * frame * t)

    def derivative_frame_unitary(t: jnp.ndarray) -> jnp.ndarray:
        # NOTE: Assume that the frame is time independent.
        return 1j * frame @ frame_unitary(t)

    def rotating_frame_hamiltonian_v0(args: HamiltonianArgs, t: jnp.ndarray):
        return frame_unitary(t) @ hamiltonian(args, t) @ jnp.transpose(
            jnp.conjugate(frame_unitary(t))
        ) + 1j * (
            derivative_frame_unitary(t) @ jnp.transpose(jnp.conjugate(frame_unitary(t)))
        )

    return rotating_frame_hamiltonian_v0

inspeqtor.physics.a

a(dims: int) -> ndarray

Annihilation operator of given dims

Parameters:

Name Type Description Default
dims int

Number of states

required

Returns:

Type Description
ndarray

jnp.ndarray: Annihilation operator

Source code in src/inspeqtor/v1/physics.py
242
243
244
245
246
247
248
249
250
251
def a(dims: int) -> jnp.ndarray:
    """Annihilation operator of given dims

    Args:
        dims (int): Number of states

    Returns:
        jnp.ndarray: Annihilation operator
    """
    return jnp.diag(jnp.sqrt(jnp.arange(1, dims)), 1)

inspeqtor.physics.a_dag

a_dag(dims: int) -> ndarray

Creation operator of given dims

Parameters:

Name Type Description Default
dims int

Number of states

required

Returns:

Type Description
ndarray

jnp.ndarray: Creation operator

Source code in src/inspeqtor/v1/physics.py
254
255
256
257
258
259
260
261
262
263
def a_dag(dims: int) -> jnp.ndarray:
    """Creation operator of given dims

    Args:
        dims (int): Number of states

    Returns:
        jnp.ndarray: Creation operator
    """
    return jnp.diag(jnp.sqrt(jnp.arange(1, dims)), -1)

inspeqtor.physics.N

N(dims: int) -> ndarray

Number operator of given dims

Parameters:

Name Type Description Default
dims int

Number of states

required

Returns:

Type Description
ndarray

jnp.ndarray: Number operator

Source code in src/inspeqtor/v1/physics.py
266
267
268
269
270
271
272
273
274
275
def N(dims: int) -> jnp.ndarray:
    """Number operator of given dims

    Args:
        dims (int): Number of states

    Returns:
        jnp.ndarray: Number operator
    """
    return jnp.diag(jnp.arange(dims))

inspeqtor.physics.tensor

tensor(operator: ndarray, position: int, total_qubits: int)
Source code in src/inspeqtor/v1/physics.py
278
279
280
281
282
def tensor(operator: jnp.ndarray, position: int, total_qubits: int):
    return jnp.kron(
        jnp.eye(operator.shape[0] ** position),
        jnp.kron(operator, jnp.eye(operator.shape[0] ** (total_qubits - position - 1))),
    )

inspeqtor.physics.make_signal_fn

make_signal_fn(
    get_envelope: Callable[
        [ControlParam], Callable[[ndarray], ndarray]
    ],
    drive_frequency: float,
    dt: float,
)

Make the envelope function into signal with drive frequency

Parameters:

Name Type Description Default
get_envelope Callable

The envelope function in unit of dt

required
drive_frequency float

drive freuqency in unit of GHz

required
dt float

The dt provived will be used to convert envelope unit to ns, set to 1 if the envelope function is already in unit of ns

required
Source code in src/inspeqtor/v1/physics.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def make_signal_fn(
    get_envelope: typing.Callable[
        [ControlParam], typing.Callable[[jnp.ndarray], jnp.ndarray]
    ],
    drive_frequency: float,
    dt: float,
):
    """Make the envelope function into signal with drive frequency

    Args:
        get_envelope (Callable): The envelope function in unit of dt
        drive_frequency (float): drive freuqency in unit of GHz
        dt (float): The dt provived will be used to convert envelope unit to ns,
                    set to 1 if the envelope function is already in unit of ns
    """

    def signal(control_parameters: ControlParam, t: jnp.ndarray):
        return jnp.real(
            get_envelope(control_parameters)(t / dt)
            * jnp.exp(1j * (2 * jnp.pi * drive_frequency * t))
        )

    return signal

inspeqtor.physics.gate_fidelity

gate_fidelity(U: ndarray, V: ndarray) -> ndarray

Calculate the gate fidelity between U and V

Parameters:

Name Type Description Default
U ndarray

Unitary operator to be targetted

required
V ndarray

Unitary operator to be compared

required

Returns:

Type Description
ndarray

jnp.ndarray: Gate fidelity

Source code in src/inspeqtor/v1/physics.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def gate_fidelity(U: jnp.ndarray, V: jnp.ndarray) -> jnp.ndarray:
    """Calculate the gate fidelity between U and V

    Args:
        U (jnp.ndarray): Unitary operator to be targetted
        V (jnp.ndarray): Unitary operator to be compared

    Returns:
        jnp.ndarray: Gate fidelity
    """
    up = jnp.trace(U.conj().T @ V)
    down = jnp.sqrt(jnp.trace(U.conj().T @ U) * jnp.trace(V.conj().T @ V))

    return jnp.abs(up / down) ** 2

inspeqtor.physics.process_fidelity

process_fidelity(
    superop: ndarray, target_superop: ndarray
) -> ndarray
Source code in src/inspeqtor/v1/physics.py
509
510
511
512
513
def process_fidelity(superop: jnp.ndarray, target_superop: jnp.ndarray) -> jnp.ndarray:
    # Calculate the fidelity
    # TODO: check if this is correct
    fidelity = jnp.trace(jnp.matmul(target_superop.conj().T, superop)) / 4
    return fidelity

inspeqtor.physics.avg_gate_fidelity_from_superop

avg_gate_fidelity_from_superop(
    U: ndarray, target_U: ndarray
) -> ndarray
Source code in src/inspeqtor/v1/physics.py
516
517
518
519
520
521
def avg_gate_fidelity_from_superop(
    U: jnp.ndarray, target_U: jnp.ndarray
) -> jnp.ndarray:
    dim = 2
    avg_fid = (dim * process_fidelity(U, target_U) + 1) / (dim + 1)
    return jnp.real(avg_fid)

inspeqtor.physics.to_superop

to_superop(U: ndarray) -> ndarray
Source code in src/inspeqtor/v1/physics.py
524
525
def to_superop(U: jnp.ndarray) -> jnp.ndarray:
    return jnp.kron(U.conj(), U)

inspeqtor.physics.state_tomography

state_tomography(
    expval: Array,
    num_qubits: int,
    order: list[ExpectationValue],
) -> Array
Source code in src/inspeqtor/v2/physics.py
 6
 7
 8
 9
10
11
12
13
14
def state_tomography(
    expval: Array, num_qubits: int, order: list[ExpectationValue]
) -> Array:
    operators = jnp.array([get_observable_operator(exp.observable) for exp in order])
    dims = 2**num_qubits
    return (
        jnp.sum(jnp.expand_dims(expval, axis=[-1, -2]) * operators, axis=0)
        + jnp.eye(dims)
    ) / dims

inspeqtor.physics.check_valid_density_matrix

check_valid_density_matrix(rho: ndarray)

Check if the provided matrix is valid density matrix

Parameters:

Name Type Description Default
rho ndarray

description

required
Source code in src/inspeqtor/v1/physics.py
532
533
534
535
536
537
538
539
540
def check_valid_density_matrix(rho: jnp.ndarray):
    """Check if the provided matrix is valid density matrix

    Args:
        rho (jnp.ndarray): _description_
    """
    # Check if the density matrix is valid
    assert jnp.allclose(jnp.trace(rho), 1.0), "Density matrix is not trace 1"
    assert jnp.allclose(rho, rho.conj().T), "Density matrix is not Hermitian"

inspeqtor.physics.check_hermitian

check_hermitian(op: ndarray)

Check if the provided matrix is Hermitian

Parameters:

Name Type Description Default
op ndarray

Matrix to be assert

required
Source code in src/inspeqtor/v1/physics.py
543
544
545
546
547
548
549
def check_hermitian(op: jnp.ndarray):
    """Check if the provided matrix is Hermitian

    Args:
        op (jnp.ndarray): Matrix to be assert
    """
    assert jnp.allclose(op, op.conj().T), "Matrix is not Hermitian"

inspeqtor.physics.direct_AGF_estimation_fn

direct_AGF_estimation_fn(target_unitary: ndarray)
Source code in src/inspeqtor/v1/physics.py
596
597
598
599
600
601
602
def direct_AGF_estimation_fn(target_unitary: jnp.ndarray):
    coeff = direct_AFG_estimation_coefficients(target_unitary)

    def inner_fn(expectation_values: jnp.ndarray):
        return direct_AFG_estimation(coeff, expectation_values)

    return inner_fn

inspeqtor.physics.calculate_exp

calculate_exp(
    unitary: ndarray,
    operator: ndarray,
    density_matrix: ndarray,
) -> ndarray

Calculate the expectation value for given unitary, observable (operator), initial state (density_matrix). Shape of all arguments must be boardcastable.

Parameters:

Name Type Description Default
unitary ndarray

Unitary operator

required
operator ndarray

Quantum Observable

required
density_matrix ndarray

Intial state in form of density matrix.

required

Returns:

Type Description
ndarray

jnp.ndarray: Expectation value of quantum observable.

Source code in src/inspeqtor/v1/physics.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
def calculate_exp(
    unitary: jnp.ndarray, operator: jnp.ndarray, density_matrix: jnp.ndarray
) -> jnp.ndarray:
    """Calculate the expectation value for given unitary, observable (operator), initial state (density_matrix).
    Shape of all arguments must be boardcastable.

    Args:
        unitary (jnp.ndarray): Unitary operator
        operator (jnp.ndarray): Quantum Observable
        density_matrix (jnp.ndarray): Intial state in form of density matrix.

    Returns:
        jnp.ndarray: Expectation value of quantum observable.
    """
    rho = jnp.matmul(
        unitary, jnp.matmul(density_matrix, unitary.conj().swapaxes(-2, -1))
    )
    temp = jnp.matmul(rho, operator)
    return jnp.real(jnp.sum(jnp.diagonal(temp, axis1=-2, axis2=-1), axis=-1))

inspeqtor.physics.make_trotterization_solver

make_trotterization_solver(
    hamiltonian: Callable[..., ndarray],
    total_dt: int,
    dt: float,
    trotter_steps: int,
    y0: ndarray,
)

Retutn whitebox function compute using Trotterization strategy.

Parameters:

Name Type Description Default
hamiltonian Callable[..., ndarray]

The Hamiltonian function of the system

required
total_dt int

The total duration of control sequence

required
dt float

The duration of time step in nanosecond.

required
trotter_steps int

The number of trotterization step.

required
y0 ndarray

The initial unitary state. Defaults to jnp.eye(2, dtype=jnp.complex128)

required

Returns:

Type Description

typing.Callable[..., jnp.ndarray]: Trotterization Whitebox function

Source code in src/inspeqtor/v1/physics.py
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
def make_trotterization_solver(
    hamiltonian: typing.Callable[..., jnp.ndarray],
    total_dt: int,
    dt: float,
    trotter_steps: int,
    y0: jnp.ndarray,
):
    """Retutn whitebox function compute using Trotterization strategy.

    Args:
        hamiltonian (typing.Callable[..., jnp.ndarray]): The Hamiltonian function of the system
        total_dt (int): The total duration of control sequence
        dt (float, optional): The duration of time step in nanosecond.
        trotter_steps (int, optional): The number of trotterization step.
        y0 (jnp.ndarray): The initial unitary state. Defaults to jnp.eye(2, dtype=jnp.complex128)

    Returns:
        typing.Callable[..., jnp.ndarray]: Trotterization Whitebox function
    """
    hamiltonian = jax.jit(hamiltonian)
    time_step = jnp.linspace(0, total_dt * dt, trotter_steps)

    def whitebox(control_parameters: jnp.ndarray):
        hamiltonians = jax.vmap(hamiltonian, in_axes=(None, 0))(
            control_parameters, time_step
        )
        unitaries = jax.scipy.linalg.expm(
            -1j * (time_step[1] - time_step[0]) * hamiltonians
        )
        # * Nice explanation of scan
        # * https://www.nelsontang.com/blog/a-friendly-introduction-to-scan-with-jax
        _, unitaries = jax.lax.scan(unitaries_prod, y0, unitaries)
        return unitaries

    return whitebox

inspeqtor.physics.lindblad_solver

lindblad_solver(
    args: HamiltonianArgs,
    t_eval: ndarray,
    hamiltonian: Callable[
        [HamiltonianArgs, ndarray], ndarray
    ],
    lindblad_ops: list[ndarray],
    rho0: ndarray,
    t0: float,
    t1: float,
    rtol: float = 1e-07,
    atol: float = 1e-07,
    max_steps: int = int(2**16),
) -> ndarray

Solve the Lindblad Master equation without flattening matrices

Source code in src/inspeqtor/v1/physics.py
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
def lindblad_solver(
    args: HamiltonianArgs,
    t_eval: jnp.ndarray,
    hamiltonian: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
    lindblad_ops: list[jnp.ndarray],
    rho0: jnp.ndarray,
    t0: float,
    t1: float,
    rtol: float = 1e-7,
    atol: float = 1e-7,
    max_steps: int = int(2**16),
) -> jnp.ndarray:
    """Solve the Lindblad Master equation without flattening matrices"""

    def commutator(A, B):
        return A @ B - B @ A

    def anti_commutator(A, B):
        return A @ B + B @ A

    # Direct matrix RHS function - no reshaping needed
    def lindblad_rhs(t, rho, args: HamiltonianArgs):
        H = hamiltonian(args, t)

        # Coherent evolution term: -i[H, ρ]
        coherent_term = -1j * commutator(H, rho)

        # Dissipative terms from all Lindblad operators
        dissipative_term = jnp.zeros_like(rho)

        for L in lindblad_ops:
            L_dag = jnp.conjugate(L.T)
            term1 = L @ rho @ L_dag
            term2 = anti_commutator(L_dag @ L, rho)
            dissipative_term = dissipative_term + (term1 - 0.5 * term2)

        return coherent_term + dissipative_term

    term = diffrax.ODETerm(lindblad_rhs)
    solver = diffrax.Tsit5()
    # solver = diffrax.Dopri5()

    solution = diffrax.diffeqsolve(
        term,
        solver,
        t0=t0,
        t1=t1,
        dt0=None,
        stepsize_controller=diffrax.PIDController(
            rtol=rtol,
            atol=atol,
        ),
        y0=rho0,
        args=args,
        saveat=diffrax.SaveAt(ts=t_eval),
        max_steps=max_steps,
    )

    # Process the matrices to ensure hermiticity and unit trace
    def process_density_matrix(rho):
        # Ensure Hermiticity
        rho = 0.5 * (rho + jnp.conjugate(rho.T))
        # Normalize to trace = 1
        return rho / jnp.trace(rho)

    # Process all matrices
    return jax.vmap(process_density_matrix)(solution.ys)

Library

inspeqtor.physics.library

inspeqtor.physics.library.transmon_hamiltonian

transmon_hamiltonian(
    params: HamiltonianArgs,
    t: ndarray,
    qubit_info: QubitInformation,
    signal: Callable[[HamiltonianArgs, ndarray], ndarray],
) -> ndarray

Lab frame hamiltonian of the transmon model

Parameters:

Name Type Description Default
params HamiltonianParameters

The parameter of the pulse for hamiltonian

required
t ndarray

The time to evaluate the Hamiltonian

required
qubit_info QubitInformation

The information of qubit

required
signal Callable[..., ndarray]

The pulse signal

required

Returns:

Type Description
ndarray

jnp.ndarray: The Hamiltonian

Source code in src/inspeqtor/v1/predefined.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def transmon_hamiltonian(
    params: HamiltonianArgs,
    t: jnp.ndarray,
    qubit_info: QubitInformation,
    signal: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
) -> jnp.ndarray:
    """Lab frame hamiltonian of the transmon model

    Args:
        params (HamiltonianParameters): The parameter of the pulse for hamiltonian
        t (jnp.ndarray): The time to evaluate the Hamiltonian
        qubit_info (QubitInformation): The information of qubit
        signal (Callable[..., jnp.ndarray]): The pulse signal

    Returns:
        jnp.ndarray: The Hamiltonian
    """

    a0 = 2 * jnp.pi * qubit_info.frequency
    a1 = 2 * jnp.pi * qubit_info.drive_strength

    return ((a0 / 2) * Z) + (a1 * signal(params, t) * X)

inspeqtor.physics.library.rotating_transmon_hamiltonian

rotating_transmon_hamiltonian(
    params: HamiltonianArgs,
    t: ndarray,
    qubit_info: QubitInformation,
    signal: Callable[[HamiltonianArgs, ndarray], ndarray],
) -> ndarray

Rotating frame hamiltonian of the transmon model

Parameters:

Name Type Description Default
params HamiltonianParameters

The parameter of the pulse for hamiltonian

required
t ndarray

The time to evaluate the Hamiltonian

required
qubit_info QubitInformation

The information of qubit

required
signal Callable[..., ndarray]

The pulse signal

required

Returns:

Type Description
ndarray

jnp.ndarray: The Hamiltonian

Source code in src/inspeqtor/v1/predefined.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def rotating_transmon_hamiltonian(
    params: HamiltonianArgs,
    t: jnp.ndarray,
    qubit_info: QubitInformation,
    signal: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
) -> jnp.ndarray:
    """Rotating frame hamiltonian of the transmon model

    Args:
        params (HamiltonianParameters): The parameter of the pulse for hamiltonian
        t (jnp.ndarray): The time to evaluate the Hamiltonian
        qubit_info (QubitInformation): The information of qubit
        signal (Callable[..., jnp.ndarray]): The pulse signal

    Returns:
        jnp.ndarray: The Hamiltonian
    """
    a0 = 2 * jnp.pi * qubit_info.frequency
    a1 = 2 * jnp.pi * qubit_info.drive_strength

    def f3(params, t):
        return a1 * signal(params, t)

    def f_sigma_x(params, t):
        return f3(params, t) * jnp.cos(a0 * t)

    def f_sigma_y(params, t):
        return f3(params, t) * jnp.sin(a0 * t)

    return f_sigma_x(params, t) * X - f_sigma_y(params, t) * Y

inspeqtor.physics.library.detune_x_hamiltonian

detune_x_hamiltonian(
    hamiltonian: Callable[
        [HamiltonianArgs, ndarray], ndarray
    ],
    detune: float,
) -> Callable[[HamiltonianArgs, ndarray], ndarray]
Source code in src/inspeqtor/v1/predefined.py
816
817
818
819
820
821
822
823
824
825
826
827
828
def detune_x_hamiltonian(
    hamiltonian: typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray],
    detune: float,
) -> typing.Callable[[HamiltonianArgs, jnp.ndarray], jnp.ndarray]:
    def detuned_hamiltonian(
        params: HamiltonianArgs,
        t: jnp.ndarray,
        *args,
        **kwargs,
    ) -> jnp.ndarray:
        return hamiltonian(params, t, *args, **kwargs) + detune * X

    return detuned_hamiltonian

inspeqtor.physics.library.SimulationStrategy

Source code in src/inspeqtor/v1/predefined.py
585
586
587
588
589
class SimulationStrategy(Enum):
    IDEAL = "ideal"
    RANDOM = "random"
    SHOT = "shot"
    NOISY = "noisy"

inspeqtor.physics.library.WhiteboxStrategy

Source code in src/inspeqtor/v1/predefined.py
593
594
595
class WhiteboxStrategy(StrEnum):
    ODE = auto()
    TROTTER = auto()

inspeqtor.physics.library.HamiltonianEnum

Source code in src/inspeqtor/v1/predefined.py
831
832
833
class HamiltonianEnum(StrEnum):
    transmon_hamiltonian = auto()
    rotating_transmon_hamiltonian = auto()

inspeqtor.physics.library.HamiltonianSpec dataclass

Source code in src/inspeqtor/v2/predefined.py
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
@dataclass
class HamiltonianSpec:
    method: WhiteboxStrategy
    hamiltonian_enum: HamiltonianEnum = HamiltonianEnum.rotating_transmon_hamiltonian
    # For Trotterization
    trotter_steps: int = 1000
    # For ODE sovler
    max_steps = int(2**16)

    def get_hamiltonian_fn(self):
        if self.hamiltonian_enum == HamiltonianEnum.rotating_transmon_hamiltonian:
            return rotating_transmon_hamiltonian
        elif self.hamiltonian_enum == HamiltonianEnum.transmon_hamiltonian:
            return transmon_hamiltonian
        else:
            raise ValueError(f"Unsupport Hamiltonian: {self.hamiltonian_enum}")

    def get_solver(
        self,
        control_sequence: ControlSequence,
        qubit_info: QubitInformation,
        dt: float,
    ):
        """Return Unitary solver from the given specification of the Hamiltonian and solver

        Args:
            control_sequence (ControlSequence): The control sequence object
            qubit_info (QubitInformation): The qubit information object
            dt (float): The time step size of the device

        Raises:
            ValueError: Unsupport Solver method

        Returns:
            typing.Any: The unitary solver
        """
        if self.method == WhiteboxStrategy.TROTTER:
            hamiltonian = partial(
                self.get_hamiltonian_fn(),
                qubit_info=qubit_info,
                signal=make_signal_fn(
                    get_envelope=control_sequence.get_envelope,
                    drive_frequency=qubit_info.frequency,
                    dt=dt,
                ),
            )

            hamiltonian = ravel_transform(hamiltonian, control_sequence)

            whitebox = make_trotterization_solver(
                hamiltonian=hamiltonian,
                total_dt=control_sequence.total_dt,
                dt=dt,
                trotter_steps=self.trotter_steps,
                y0=jnp.eye(2, dtype=jnp.complex128),
            )

        elif self.method == WhiteboxStrategy.ODE:
            t_eval = jnp.linspace(
                0, control_sequence.total_dt * dt, control_sequence.total_dt
            )

            hamiltonian = partial(
                self.get_hamiltonian_fn(),
                qubit_info=qubit_info,
                signal=make_signal_fn(
                    control_sequence.get_envelope,
                    qubit_info.frequency,
                    dt,
                ),
            )

            hamiltonian = ravel_transform(hamiltonian, control_sequence)

            whitebox = partial(
                solver,
                t_eval=t_eval,
                hamiltonian=hamiltonian,
                y0=jnp.eye(2, dtype=jnp.complex_),
                t0=0,
                t1=control_sequence.total_dt * dt,
                max_steps=self.max_steps,
            )
        else:
            raise ValueError("Unsupport method")

        return whitebox

get_solver

get_solver(
    control_sequence: ControlSequence,
    qubit_info: QubitInformation,
    dt: float,
)

Return Unitary solver from the given specification of the Hamiltonian and solver

Parameters:

Name Type Description Default
control_sequence ControlSequence

The control sequence object

required
qubit_info QubitInformation

The qubit information object

required
dt float

The time step size of the device

required

Raises:

Type Description
ValueError

Unsupport Solver method

Returns:

Type Description

typing.Any: The unitary solver

Source code in src/inspeqtor/v2/predefined.py
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
def get_solver(
    self,
    control_sequence: ControlSequence,
    qubit_info: QubitInformation,
    dt: float,
):
    """Return Unitary solver from the given specification of the Hamiltonian and solver

    Args:
        control_sequence (ControlSequence): The control sequence object
        qubit_info (QubitInformation): The qubit information object
        dt (float): The time step size of the device

    Raises:
        ValueError: Unsupport Solver method

    Returns:
        typing.Any: The unitary solver
    """
    if self.method == WhiteboxStrategy.TROTTER:
        hamiltonian = partial(
            self.get_hamiltonian_fn(),
            qubit_info=qubit_info,
            signal=make_signal_fn(
                get_envelope=control_sequence.get_envelope,
                drive_frequency=qubit_info.frequency,
                dt=dt,
            ),
        )

        hamiltonian = ravel_transform(hamiltonian, control_sequence)

        whitebox = make_trotterization_solver(
            hamiltonian=hamiltonian,
            total_dt=control_sequence.total_dt,
            dt=dt,
            trotter_steps=self.trotter_steps,
            y0=jnp.eye(2, dtype=jnp.complex128),
        )

    elif self.method == WhiteboxStrategy.ODE:
        t_eval = jnp.linspace(
            0, control_sequence.total_dt * dt, control_sequence.total_dt
        )

        hamiltonian = partial(
            self.get_hamiltonian_fn(),
            qubit_info=qubit_info,
            signal=make_signal_fn(
                control_sequence.get_envelope,
                qubit_info.frequency,
                dt,
            ),
        )

        hamiltonian = ravel_transform(hamiltonian, control_sequence)

        whitebox = partial(
            solver,
            t_eval=t_eval,
            hamiltonian=hamiltonian,
            y0=jnp.eye(2, dtype=jnp.complex_),
            t0=0,
            t1=control_sequence.total_dt * dt,
            max_steps=self.max_steps,
        )
    else:
        raise ValueError("Unsupport method")

    return whitebox