Skip to content

superconducting

Devices.

ATS

Bases: FluxDevice

ATS Device.

Source code in jaxquantum/devices/superconducting/ats.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 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
@struct.dataclass
class ATS(FluxDevice):
    """
    ATS Device.
    """

    def common_ops(self):
        """Written in the linear basis."""
        ops = {}

        N = self.N_pre_diag
        ops["id"] = identity(N)
        ops["a"] = destroy(N)
        ops["a_dag"] = create(N)
        ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
        ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])
        return ops

    def phi_zpf(self):
        """Return Phase ZPF."""
        return (2 * self.params["Ec"] / self.params["El"]) ** (0.25)

    def n_zpf(self):
        """Return Charge ZPF."""
        return (self.params["El"] / (32 * self.params["Ec"])) ** (0.25)

    def get_linear_ω(self):
        """Get frequency of linear terms."""
        return jnp.sqrt(8 * self.params["El"] * self.params["Ec"])

    def get_H_linear(self):
        """Return linear terms in H."""
        w = self.get_linear_ω()
        return w * (
            self.linear_ops["a_dag"] @ self.linear_ops["a"]
            + 0.5 * self.linear_ops["id"]
        )

    @staticmethod
    def get_H_nonlinear_static(phi_op, Ej, dEj, Ej2, phi_sum, phi_delta):
        cos_phi_op = cosm(phi_op)
        sin_phi_op = sinm(phi_op)

        cos_2phi_op = cos_phi_op @ cos_phi_op - sin_phi_op @ sin_phi_op
        sin_2phi_op = 2 * cos_phi_op @ sin_phi_op

        H_nl_Ej = (
            -2
            * Ej
            * (
                cos_phi_op * jnp.cos(2 * jnp.pi * phi_delta)
                - sin_phi_op * jnp.sin(2 * jnp.pi * phi_delta)
            )
            * jnp.cos(2 * jnp.pi * phi_sum)
        )
        H_nl_dEj = (
            2
            * dEj
            * (
                sin_phi_op * jnp.cos(2 * jnp.pi * phi_delta)
                + cos_phi_op * jnp.sin(2 * jnp.pi * phi_delta)
            )
            * jnp.sin(2 * jnp.pi * phi_sum)
        )
        H_nl_Ej2 = (
            2
            * Ej2
            * (
                cos_2phi_op * jnp.cos(2 * 2 * jnp.pi * phi_delta)
                - sin_2phi_op * jnp.sin(2 * 2 * jnp.pi * phi_delta)
            )
            * jnp.cos(2 * 2 * jnp.pi * phi_sum)
        )

        H_nl = H_nl_Ej + H_nl_dEj + H_nl_Ej2

        # id_op = jqt.identity_like(phi_op)
        # phi_delta_ext_op = self.params["phi_delta_ext"] * id_op
        # H_nl_old = - 2 * Ej * jqt.cosm(phi_op + 2 * jnp.pi * phi_delta_ext_op) * jnp.cos(2 * jnp.pi * self.params["phi_sum_ext"])
        # H_nl_old += 2 * dEj * jqt.sinm(phi_op + 2 * jnp.pi * phi_delta_ext_op) * jnp.sin(2 * jnp.pi * self.params["phi_sum_ext"])
        # H_nl_old += 2 * Ej2 * jqt.cosm(2*phi_op + 2 * 2 * jnp.pi * phi_delta_ext_op) * jnp.cos(2 * 2 * jnp.pi * self.params["phi_sum_ext"])

        return H_nl

    def get_H_nonlinear(self, phi_op):
        """Return nonlinear terms in H."""

        Ej = self.params["Ej"]
        dEj = self.params["dEj"]
        Ej2 = self.params["Ej2"]

        phi_sum = self.params["phi_sum_ext"]
        phi_delta = self.params["phi_delta_ext"]

        return ATS.get_H_nonlinear_static(phi_op, Ej, dEj, Ej2, phi_sum, phi_delta)

    def get_H_full(self):
        """Return full H in linear basis."""
        phi_b = self.linear_ops["phi"]
        H_nl = self.get_H_nonlinear(phi_b)
        H = self.get_H_linear() + H_nl
        return H

    def potential(self, phi):
        """Return potential energy for a given phi."""

        phi_delta_ext = self.params["phi_delta_ext"]
        phi_sum_ext = self.params["phi_sum_ext"]

        V = 0.5 * self.params["El"] * (2 * jnp.pi * phi) ** 2
        V += (
            -2
            * self.params["Ej"]
            * jnp.cos(2 * jnp.pi * (phi + phi_delta_ext))
            * jnp.cos(2 * jnp.pi * phi_sum_ext)
        )
        V += (
            2
            * self.params["dEj"]
            * jnp.sin(2 * jnp.pi * (phi + phi_delta_ext))
            * jnp.sin(2 * jnp.pi * phi_sum_ext)
        )
        V += (
            2
            * self.params["Ej2"]
            * jnp.cos(2 * 2 * jnp.pi * (phi + phi_delta_ext))
            * jnp.cos(2 * 2 * jnp.pi * phi_sum_ext)
        )

        return V

common_ops()

Written in the linear basis.

Source code in jaxquantum/devices/superconducting/ats.py
21
22
23
24
25
26
27
28
29
30
31
def common_ops(self):
    """Written in the linear basis."""
    ops = {}

    N = self.N_pre_diag
    ops["id"] = identity(N)
    ops["a"] = destroy(N)
    ops["a_dag"] = create(N)
    ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
    ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])
    return ops

get_H_full()

Return full H in linear basis.

Source code in jaxquantum/devices/superconducting/ats.py
111
112
113
114
115
116
def get_H_full(self):
    """Return full H in linear basis."""
    phi_b = self.linear_ops["phi"]
    H_nl = self.get_H_nonlinear(phi_b)
    H = self.get_H_linear() + H_nl
    return H

get_H_linear()

Return linear terms in H.

Source code in jaxquantum/devices/superconducting/ats.py
45
46
47
48
49
50
51
def get_H_linear(self):
    """Return linear terms in H."""
    w = self.get_linear_ω()
    return w * (
        self.linear_ops["a_dag"] @ self.linear_ops["a"]
        + 0.5 * self.linear_ops["id"]
    )

get_H_nonlinear(phi_op)

Return nonlinear terms in H.

Source code in jaxquantum/devices/superconducting/ats.py
 99
100
101
102
103
104
105
106
107
108
109
def get_H_nonlinear(self, phi_op):
    """Return nonlinear terms in H."""

    Ej = self.params["Ej"]
    dEj = self.params["dEj"]
    Ej2 = self.params["Ej2"]

    phi_sum = self.params["phi_sum_ext"]
    phi_delta = self.params["phi_delta_ext"]

    return ATS.get_H_nonlinear_static(phi_op, Ej, dEj, Ej2, phi_sum, phi_delta)

get_linear_ω()

Get frequency of linear terms.

Source code in jaxquantum/devices/superconducting/ats.py
41
42
43
def get_linear_ω(self):
    """Get frequency of linear terms."""
    return jnp.sqrt(8 * self.params["El"] * self.params["Ec"])

n_zpf()

Return Charge ZPF.

Source code in jaxquantum/devices/superconducting/ats.py
37
38
39
def n_zpf(self):
    """Return Charge ZPF."""
    return (self.params["El"] / (32 * self.params["Ec"])) ** (0.25)

phi_zpf()

Return Phase ZPF.

Source code in jaxquantum/devices/superconducting/ats.py
33
34
35
def phi_zpf(self):
    """Return Phase ZPF."""
    return (2 * self.params["Ec"] / self.params["El"]) ** (0.25)

potential(phi)

Return potential energy for a given phi.

Source code in jaxquantum/devices/superconducting/ats.py
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
def potential(self, phi):
    """Return potential energy for a given phi."""

    phi_delta_ext = self.params["phi_delta_ext"]
    phi_sum_ext = self.params["phi_sum_ext"]

    V = 0.5 * self.params["El"] * (2 * jnp.pi * phi) ** 2
    V += (
        -2
        * self.params["Ej"]
        * jnp.cos(2 * jnp.pi * (phi + phi_delta_ext))
        * jnp.cos(2 * jnp.pi * phi_sum_ext)
    )
    V += (
        2
        * self.params["dEj"]
        * jnp.sin(2 * jnp.pi * (phi + phi_delta_ext))
        * jnp.sin(2 * jnp.pi * phi_sum_ext)
    )
    V += (
        2
        * self.params["Ej2"]
        * jnp.cos(2 * 2 * jnp.pi * (phi + phi_delta_ext))
        * jnp.cos(2 * 2 * jnp.pi * phi_sum_ext)
    )

    return V

Device

Bases: ABC

Source code in jaxquantum/devices/base/base.py
 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
@struct.dataclass
class Device(ABC):
    DEFAULT_BASIS = BasisTypes.fock
    DEFAULT_HAMILTONIAN = HamiltonianTypes.full

    N: int = struct.field(pytree_node=False)
    N_pre_diag: int = struct.field(pytree_node=False)
    params: Dict[str, Any]
    _label: int = struct.field(pytree_node=False)
    _basis: BasisTypes = struct.field(pytree_node=False)
    _hamiltonian: HamiltonianTypes = struct.field(pytree_node=False)

    @classmethod
    def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
        """This can be overridden by subclasses."""
        pass

    @classmethod
    def create(
        cls,
        N,
        params,
        label=0,
        N_pre_diag=None,
        use_linear=False,
        hamiltonian: HamiltonianTypes = None,
        basis: BasisTypes = None,
    ):
        """Create a device.

        Args:
            N (int): dimension of Hilbert space.
            params (dict): parameters of the device.
            label (int, optional): label for the device. Defaults to 0. This is useful when you have multiple of the same device type in the same system.
            N_pre_diag (int, optional): dimension of Hilbert space before diagonalization. Defaults to None, in which case it is set to N. This must be greater than or rqual to N.
            use_linear (bool): whether to use the linearized device. Defaults to False. This will override the hamiltonian keyword argument. This is a bit redundant with hamiltonian, but it is kept for backwards compatibility.
            hamiltonian (HamiltonianTypes, optional): type of Hamiltonian. Defaults to None, in which case the full hamiltonian is used.
            basis (BasisTypes, optional): type of basis. Defaults to None, in which case the fock basis is used.
        """

        if N_pre_diag is None:
            N_pre_diag = N

        assert N_pre_diag >= N, "N_pre_diag must be greater than or equal to N."

        _basis = basis if basis is not None else cls.DEFAULT_BASIS
        _hamiltonian = (
            hamiltonian if hamiltonian is not None else cls.DEFAULT_HAMILTONIAN
        )

        if use_linear:
            _hamiltonian = HamiltonianTypes.linear

        cls.param_validation(N, N_pre_diag, params, _hamiltonian, _basis)

        return cls(N, N_pre_diag, params, label, _basis, _hamiltonian)

    @property
    def basis(self):
        return self._basis

    @property
    def hamiltonian(self):
        return self._hamiltonian

    @property
    def label(self):
        return self.__class__.__name__ + str(self._label)

    @property
    def linear_ops(self):
        return self.common_ops()

    @property
    def original_ops(self):
        return self.common_ops()

    @property
    def ops(self):
        return self.full_ops()

    @abstractmethod
    def common_ops(self) -> Dict[str, Qarray]:
        """Set up common ops in the specified basis."""

    @abstractmethod
    def get_linear_ω(self):
        """Get frequency of linear terms."""

    @abstractmethod
    def get_H_linear(self):
        """Return linear terms in H."""

    @abstractmethod
    def get_H_full(self):
        """Return full H."""

    def get_H(self):
        """
        Return diagonalized H. Explicitly keep only diagonal elements of matrix.
        """
        return self.get_op_in_H_eigenbasis(
            self._get_H_in_original_basis()
        ).keep_only_diag_elements()

    def _get_H_in_original_basis(self):
        """This returns the Hamiltonian in the original specified basis. This can be overridden by subclasses."""

        if self.hamiltonian == HamiltonianTypes.linear:
            return self.get_H_linear()
        elif self.hamiltonian == HamiltonianTypes.full:
            return self.get_H_full()

    def _calculate_eig_systems(self):
        evs, evecs = jnp.linalg.eigh(self._get_H_in_original_basis().data)  # Hermitian
        idxs_sorted = jnp.argsort(evs)
        return evs[idxs_sorted], evecs[:, idxs_sorted]

    @property
    def eig_systems(self):
        eig_systems = {}
        eig_systems["vals"], eig_systems["vecs"] = self._calculate_eig_systems()

        eig_systems["vecs"] = eig_systems["vecs"]
        eig_systems["vals"] = eig_systems["vals"]
        return eig_systems

    def get_op_in_H_eigenbasis(self, op: Qarray):
        evecs = self.eig_systems["vecs"][:, : self.N]
        dims = [[self.N], [self.N]]
        return get_op_in_new_basis(op, evecs, dims)

    def get_op_data_in_H_eigenbasis(self, op: Array):
        evecs = self.eig_systems["vecs"][:, : self.N]
        return get_op_data_in_new_basis(op, evecs)

    def get_vec_in_H_eigenbasis(self, vec: Qarray):
        evecs = self.eig_systems["vecs"][:, : self.N]
        if vec.qtype == Qtypes.ket:
            dims = [[self.N], [1]]
        else:
            dims = [[1], [self.N]]
        return get_vec_in_new_basis(vec, evecs, dims)

    def get_vec_data_in_H_eigenbasis(self, vec: Array):
        evecs = self.eig_systems["vecs"][:, : self.N]
        return get_vec_data_in_new_basis(vec, evecs)

    def full_ops(self):
        # TODO: use JAX vmap here

        linear_ops = self.linear_ops
        ops = {}
        for name, op in linear_ops.items():
            ops[name] = self.get_op_in_H_eigenbasis(op)

        return ops

common_ops() abstractmethod

Set up common ops in the specified basis.

Source code in jaxquantum/devices/base/base.py
148
149
150
@abstractmethod
def common_ops(self) -> Dict[str, Qarray]:
    """Set up common ops in the specified basis."""

create(N, params, label=0, N_pre_diag=None, use_linear=False, hamiltonian=None, basis=None) classmethod

Create a device.

Parameters:

Name Type Description Default
N int

dimension of Hilbert space.

required
params dict

parameters of the device.

required
label int

label for the device. Defaults to 0. This is useful when you have multiple of the same device type in the same system.

0
N_pre_diag int

dimension of Hilbert space before diagonalization. Defaults to None, in which case it is set to N. This must be greater than or rqual to N.

None
use_linear bool

whether to use the linearized device. Defaults to False. This will override the hamiltonian keyword argument. This is a bit redundant with hamiltonian, but it is kept for backwards compatibility.

False
hamiltonian HamiltonianTypes

type of Hamiltonian. Defaults to None, in which case the full hamiltonian is used.

None
basis BasisTypes

type of basis. Defaults to None, in which case the fock basis is used.

None
Source code in jaxquantum/devices/base/base.py
 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
@classmethod
def create(
    cls,
    N,
    params,
    label=0,
    N_pre_diag=None,
    use_linear=False,
    hamiltonian: HamiltonianTypes = None,
    basis: BasisTypes = None,
):
    """Create a device.

    Args:
        N (int): dimension of Hilbert space.
        params (dict): parameters of the device.
        label (int, optional): label for the device. Defaults to 0. This is useful when you have multiple of the same device type in the same system.
        N_pre_diag (int, optional): dimension of Hilbert space before diagonalization. Defaults to None, in which case it is set to N. This must be greater than or rqual to N.
        use_linear (bool): whether to use the linearized device. Defaults to False. This will override the hamiltonian keyword argument. This is a bit redundant with hamiltonian, but it is kept for backwards compatibility.
        hamiltonian (HamiltonianTypes, optional): type of Hamiltonian. Defaults to None, in which case the full hamiltonian is used.
        basis (BasisTypes, optional): type of basis. Defaults to None, in which case the fock basis is used.
    """

    if N_pre_diag is None:
        N_pre_diag = N

    assert N_pre_diag >= N, "N_pre_diag must be greater than or equal to N."

    _basis = basis if basis is not None else cls.DEFAULT_BASIS
    _hamiltonian = (
        hamiltonian if hamiltonian is not None else cls.DEFAULT_HAMILTONIAN
    )

    if use_linear:
        _hamiltonian = HamiltonianTypes.linear

    cls.param_validation(N, N_pre_diag, params, _hamiltonian, _basis)

    return cls(N, N_pre_diag, params, label, _basis, _hamiltonian)

get_H()

Return diagonalized H. Explicitly keep only diagonal elements of matrix.

Source code in jaxquantum/devices/base/base.py
164
165
166
167
168
169
170
def get_H(self):
    """
    Return diagonalized H. Explicitly keep only diagonal elements of matrix.
    """
    return self.get_op_in_H_eigenbasis(
        self._get_H_in_original_basis()
    ).keep_only_diag_elements()

get_H_full() abstractmethod

Return full H.

Source code in jaxquantum/devices/base/base.py
160
161
162
@abstractmethod
def get_H_full(self):
    """Return full H."""

get_H_linear() abstractmethod

Return linear terms in H.

Source code in jaxquantum/devices/base/base.py
156
157
158
@abstractmethod
def get_H_linear(self):
    """Return linear terms in H."""

get_linear_ω() abstractmethod

Get frequency of linear terms.

Source code in jaxquantum/devices/base/base.py
152
153
154
@abstractmethod
def get_linear_ω(self):
    """Get frequency of linear terms."""

param_validation(N, N_pre_diag, params, hamiltonian, basis) classmethod

This can be overridden by subclasses.

Source code in jaxquantum/devices/base/base.py
79
80
81
82
@classmethod
def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
    """This can be overridden by subclasses."""
    pass

Drive

Bases: ABC

Source code in jaxquantum/devices/superconducting/drive.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
@struct.dataclass
class Drive(ABC):
    N: int = struct.field(pytree_node=False)
    ωd: float
    _label: int = struct.field(pytree_node=False)

    @classmethod
    def create(cls, M_max, ωd, label=0):
        cls.M_max = M_max
        N = 2 * M_max + 1
        return cls(N, ωd, label)

    @property
    def label(self):
        return self.__class__.__name__ + str(self._label)

    @property
    def ops(self):
        return self.common_ops()

    def common_ops(self) -> Dict[str, Qarray]:
        ops = {}

        M_max = self.M_max

        # Construct M = ∑ₘ m|m><m| operator in drive charge basis
        ops["M"] = jnp2jqt(jnp.diag(jnp.arange(-M_max, M_max + 1)))

        # Construct Id = ∑ₘ|m><m| in the drive charge basis
        ops["id"] = jnp2jqt(jnp.identity(2 * M_max + 1))

        # Construct M₊ ≡ exp(iθ) and M₋ ≡ exp(-iθ) operators for drive
        ops["M-"] = jnp2jqt(jnp.eye(2 * M_max + 1, k=1))
        ops["M+"] = jnp2jqt(jnp.eye(2 * M_max + 1, k=-1))

        # Construct cos(θ) ≡ 1/2 * [M₊ + M₋] = 1/2 * ∑ₘ|m+1><m| + h.c
        ops["cos(θ)"] = 0.5 * (ops["M+"] + ops["M-"])

        # Construct sin(θ) ≡ -i/2 * [M₊ - M₋] = -i/2 * ∑ₘ|m+1><m| + h.c
        ops["sin(θ)"] = -0.5j * (ops["M+"] - ops["M-"])

        # Construct more general drive operators cos(kθ) and sin(kθ)
        for k in range(2, M_max + 1):
            ops[f"M_+{k}"] = jnp2jqt(jnp.eye(2 * M_max + 1, k=-k))
            ops[f"M_-{k}"] = jnp2jqt(jnp.eye(2 * M_max + 1, k=k))
            ops[f"cos({k}θ)"] = 0.5 * (ops[f"M_+{k}"] + ops[f"M_-{k}"])
            ops[f"sin({k}θ)"] = -0.5j * (ops[f"M_+{k}"] - ops[f"M_-{k}"])

        return ops

    #############################################################

    def get_H(self):
        """
        Bare "drive" Hamiltonian (ωd * M) in the extended Hilbert space.
        """
        return self.ωd * self.ops["M"]

get_H()

Bare "drive" Hamiltonian (ωd * M) in the extended Hilbert space.

Source code in jaxquantum/devices/superconducting/drive.py
68
69
70
71
72
def get_H(self):
    """
    Bare "drive" Hamiltonian (ωd * M) in the extended Hilbert space.
    """
    return self.ωd * self.ops["M"]

FluxDevice

Bases: Device

Source code in jaxquantum/devices/superconducting/flux_base.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
@struct.dataclass
class FluxDevice(Device):
    @abstractmethod
    def phi_zpf(self):
        """Return Phase ZPF."""

    def _calculate_wavefunctions_fock(self, phi_vals):
        """Calculate wavefunctions at phi_exts."""
        phi_osc = self.phi_zpf() * jnp.sqrt(2)  # length of oscillator
        phi_vals = jnp.array(phi_vals)

        # calculate basis functions
        basis_functions = []
        for n in range(self.N_pre_diag):
            basis_functions.append(
                harm_osc_wavefunction(n, phi_vals, jnp.real(phi_osc))
            )
        basis_functions = jnp.array(basis_functions)

        # transform to better diagonal basis
        basis_functions_in_H_eigenbasis = self.get_vec_data_in_H_eigenbasis(
            basis_functions
        )

        # the below is equivalent to evecs_in_H_eigenbasis @ basis_functions_in_H_eigenbasis
        # since evecs in H_eigenbasis is diagonal, i.e. the identity matrix
        wavefunctions = basis_functions_in_H_eigenbasis
        return wavefunctions

    def _calculate_wavefunctions_charge(self, phi_vals):
        phi_vals = jnp.array(phi_vals)

        # calculate basis functions
        basis_functions = []
        n_max = (self.N_pre_diag - 1) // 2
        for n in jnp.arange(-n_max, n_max + 1):
            basis_functions.append(
                1 / (jnp.sqrt(2 * jnp.pi)) * jnp.exp(1j * n * (2 * jnp.pi * phi_vals))
            )
        basis_functions = jnp.array(basis_functions)

        # transform to better diagonal basis
        basis_functions_in_H_eigenbasis = self.get_vec_data_in_H_eigenbasis(
            basis_functions
        )

        # the below is equivalent to evecs_in_H_eigenbasis @ basis_functions_in_H_eigenbasis
        # since evecs in H_eigenbasis is diagonal, i.e. the identity matrix
        phase_correction_factors = (1j ** (jnp.arange(0, self.N_pre_diag))).reshape(
            self.N_pre_diag, 1
        )  # TODO: review why these are needed...
        wavefunctions = basis_functions_in_H_eigenbasis * phase_correction_factors
        return wavefunctions

    @abstractmethod
    def potential(self, phi):
        """Return potential energy as a function of phi."""

    def plot_wavefunctions(self, phi_vals, max_n=None, which=None, ax=None, mode="abs"):
        if self.basis == BasisTypes.fock:
            _calculate_wavefunctions = self._calculate_wavefunctions_fock
        elif self.basis == BasisTypes.charge:
            _calculate_wavefunctions = self._calculate_wavefunctions_charge
        else:
            raise NotImplementedError(
                f"The {self.basis} is not yet supported for plotting wavefunctions."
            )

        """Plot wavefunctions at phi_exts."""
        wavefunctions = _calculate_wavefunctions(phi_vals)
        energy_levels = self.eig_systems["vals"][: self.N]

        potential = self.potential(phi_vals)

        if ax is None:
            fig, ax = plt.subplots(1, 1, figsize=(3.5, 2.5), dpi=1000)
        else:
            fig = ax.get_figure()

        min_val = None
        max_val = None

        assert max_n is None or which is None, "Can't specify both max_n and which"

        max_n = self.N if max_n is None else max_n
        levels = range(max_n) if which is None else which

        for n in levels:
            if mode == "abs":
                wf_vals = jnp.abs(wavefunctions[n, :]) ** 2
            elif mode == "real":
                wf_vals = wavefunctions[n, :].real
            elif mode == "imag":
                wf_vals = wavefunctions[n, :].imag

            wf_vals += energy_levels[n]
            curr_min_val = min(wf_vals)
            curr_max_val = max(wf_vals)

            if min_val is None or curr_min_val < min_val:
                min_val = curr_min_val

            if max_val is None or curr_max_val > max_val:
                max_val = curr_max_val

            ax.plot(
                phi_vals, wf_vals, label=f"$|${n}$\\rangle$", linestyle="-", linewidth=1
            )
            ax.fill_between(phi_vals, energy_levels[n], wf_vals, alpha=0.5)

        ax.plot(
            phi_vals,
            potential,
            label="potential",
            color="black",
            linestyle="-",
            linewidth=1,
        )

        ax.set_ylim([min_val - 1, max_val + 1])

        ax.set_xlabel(r"$\Phi/\Phi_0$")
        ax.set_ylabel(r"Energy [GHz]")

        if mode == "abs":
            title_str = r"$|\psi_n(\Phi)|^2$"
        elif mode == "real":
            title_str = r"Re($\psi_n(\Phi)$)"
        elif mode == "imag":
            title_str = r"Im($\psi_n(\Phi)$)"

        ax.set_title(f"{title_str}")

        plt.legend(fontsize=6)
        fig.tight_layout()

        return ax

phi_zpf() abstractmethod

Return Phase ZPF.

Source code in jaxquantum/devices/superconducting/flux_base.py
18
19
20
@abstractmethod
def phi_zpf(self):
    """Return Phase ZPF."""

potential(phi) abstractmethod

Return potential energy as a function of phi.

Source code in jaxquantum/devices/superconducting/flux_base.py
70
71
72
@abstractmethod
def potential(self, phi):
    """Return potential energy as a function of phi."""

Fluxonium

Bases: FluxDevice

Fluxonium Device.

Source code in jaxquantum/devices/superconducting/fluxonium.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@struct.dataclass
class Fluxonium(FluxDevice):
    """
    Fluxonium Device.
    """

    def common_ops(self):
        """Written in the linear basis."""
        ops = {}

        N = self.N_pre_diag
        ops["id"] = jqt.identity(N)
        ops["a"] = jqt.destroy(N)
        ops["a_dag"] = jqt.create(N)
        ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
        ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])

        ops["cos(φ/2)"] = jqt.cosm(ops["phi"] / 2)
        ops["sin(φ/2)"] = jqt.sinm(ops["phi"] / 2)

        return ops

    def n_zpf(self):
        n_zpf = (self.params["El"] / (32.0 * self.params["Ec"])) ** (0.25)
        return n_zpf

    def phi_zpf(self):
        """Return Phase ZPF."""
        return (2 * self.params["Ec"] / self.params["El"]) ** (0.25)

    def get_linear_ω(self):
        """Get frequency of linear terms."""
        return jnp.sqrt(8 * self.params["Ec"] * self.params["El"])

    def get_H_linear(self):
        """Return linear terms in H."""
        w = self.get_linear_ω()
        return w * (
            self.linear_ops["a_dag"] @ self.linear_ops["a"]
            + 0.5 * self.linear_ops["id"]
        )

    def get_H_full(self):
        """Return full H in linear basis."""

        phi_op = self.linear_ops["phi"]
        return self.get_H_linear() + self.get_H_nonlinear(phi_op)

    def get_H_nonlinear(self, phi_op):
        op_cos_phi = jqt.cosm(phi_op)
        op_sin_phi = jqt.sinm(phi_op)

        phi_ext = self.params["phi_ext"]
        Hcos = op_cos_phi * jnp.cos(2.0 * jnp.pi * phi_ext) + op_sin_phi * jnp.sin(
            2.0 * jnp.pi * phi_ext
        )
        H_nl = -self.params["Ej"] * Hcos
        return H_nl

    def potential(self, phi):
        """Return potential energy for a given phi."""
        phi_ext = self.params["phi_ext"]
        V_linear = 0.5 * self.params["El"] * (2 * jnp.pi * phi) ** 2

        if self.hamiltonian == HamiltonianTypes.linear:
            return V_linear

        V_nonlinear = -self.params["Ej"] * jnp.cos(2.0 * jnp.pi * (phi - phi_ext))
        if self.hamiltonian == HamiltonianTypes.full:
            return V_linear + V_nonlinear

common_ops()

Written in the linear basis.

Source code in jaxquantum/devices/superconducting/fluxonium.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def common_ops(self):
    """Written in the linear basis."""
    ops = {}

    N = self.N_pre_diag
    ops["id"] = jqt.identity(N)
    ops["a"] = jqt.destroy(N)
    ops["a_dag"] = jqt.create(N)
    ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
    ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])

    ops["cos(φ/2)"] = jqt.cosm(ops["phi"] / 2)
    ops["sin(φ/2)"] = jqt.sinm(ops["phi"] / 2)

    return ops

get_H_full()

Return full H in linear basis.

Source code in jaxquantum/devices/superconducting/fluxonium.py
56
57
58
59
60
def get_H_full(self):
    """Return full H in linear basis."""

    phi_op = self.linear_ops["phi"]
    return self.get_H_linear() + self.get_H_nonlinear(phi_op)

get_H_linear()

Return linear terms in H.

Source code in jaxquantum/devices/superconducting/fluxonium.py
48
49
50
51
52
53
54
def get_H_linear(self):
    """Return linear terms in H."""
    w = self.get_linear_ω()
    return w * (
        self.linear_ops["a_dag"] @ self.linear_ops["a"]
        + 0.5 * self.linear_ops["id"]
    )

get_linear_ω()

Get frequency of linear terms.

Source code in jaxquantum/devices/superconducting/fluxonium.py
44
45
46
def get_linear_ω(self):
    """Get frequency of linear terms."""
    return jnp.sqrt(8 * self.params["Ec"] * self.params["El"])

phi_zpf()

Return Phase ZPF.

Source code in jaxquantum/devices/superconducting/fluxonium.py
40
41
42
def phi_zpf(self):
    """Return Phase ZPF."""
    return (2 * self.params["Ec"] / self.params["El"]) ** (0.25)

potential(phi)

Return potential energy for a given phi.

Source code in jaxquantum/devices/superconducting/fluxonium.py
73
74
75
76
77
78
79
80
81
82
83
def potential(self, phi):
    """Return potential energy for a given phi."""
    phi_ext = self.params["phi_ext"]
    V_linear = 0.5 * self.params["El"] * (2 * jnp.pi * phi) ** 2

    if self.hamiltonian == HamiltonianTypes.linear:
        return V_linear

    V_nonlinear = -self.params["Ej"] * jnp.cos(2.0 * jnp.pi * (phi - phi_ext))
    if self.hamiltonian == HamiltonianTypes.full:
        return V_linear + V_nonlinear

IdealQubit

Bases: Device

Ideal qubit Device.

Source code in jaxquantum/devices/superconducting/ideal_qubit.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@struct.dataclass
class IdealQubit(Device):
    """
    Ideal qubit Device.
    """

    @classmethod
    def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
        """This can be overridden by subclasses."""
        assert basis == BasisTypes.fock, (
            "IdealQubit is a two-level system defined in the Fock basis."
        )
        assert hamiltonian == HamiltonianTypes.full, (
            "IdealQubit requires a full Hamiltonian."
        )
        assert N == N_pre_diag == 2, "IdealQubit is a two-level system."
        assert "ω" in params, "IdealQubit requires a frequency parameter 'ω'."

    def common_ops(self):
        """Written in the linear basis."""
        ops = {}

        assert self.N_pre_diag == 2
        assert self.N == 2

        N = self.N_pre_diag
        ops["id"] = identity(N)
        ops["sigmaz"] = sigmaz()
        ops["sigmax"] = sigmax()
        ops["sigmay"] = sigmay()
        ops["sigmam"] = sigmam()
        ops["sigmap"] = sigmap()

        return ops

    def get_linear_ω(self):
        """Get frequency of linear terms."""
        return self.params["ω"]

    def get_H_linear(self):
        """Return linear terms in H."""
        w = self.get_linear_ω()
        return (w / 2) * self.linear_ops["sigma_z"]

    def get_H_full(self):
        """Return full H in linear basis."""
        return self.get_H_linear()

common_ops()

Written in the linear basis.

Source code in jaxquantum/devices/superconducting/ideal_qubit.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def common_ops(self):
    """Written in the linear basis."""
    ops = {}

    assert self.N_pre_diag == 2
    assert self.N == 2

    N = self.N_pre_diag
    ops["id"] = identity(N)
    ops["sigmaz"] = sigmaz()
    ops["sigmax"] = sigmax()
    ops["sigmay"] = sigmay()
    ops["sigmam"] = sigmam()
    ops["sigmap"] = sigmap()

    return ops

get_H_full()

Return full H in linear basis.

Source code in jaxquantum/devices/superconducting/ideal_qubit.py
57
58
59
def get_H_full(self):
    """Return full H in linear basis."""
    return self.get_H_linear()

get_H_linear()

Return linear terms in H.

Source code in jaxquantum/devices/superconducting/ideal_qubit.py
52
53
54
55
def get_H_linear(self):
    """Return linear terms in H."""
    w = self.get_linear_ω()
    return (w / 2) * self.linear_ops["sigma_z"]

get_linear_ω()

Get frequency of linear terms.

Source code in jaxquantum/devices/superconducting/ideal_qubit.py
48
49
50
def get_linear_ω(self):
    """Get frequency of linear terms."""
    return self.params["ω"]

param_validation(N, N_pre_diag, params, hamiltonian, basis) classmethod

This can be overridden by subclasses.

Source code in jaxquantum/devices/superconducting/ideal_qubit.py
19
20
21
22
23
24
25
26
27
28
29
@classmethod
def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
    """This can be overridden by subclasses."""
    assert basis == BasisTypes.fock, (
        "IdealQubit is a two-level system defined in the Fock basis."
    )
    assert hamiltonian == HamiltonianTypes.full, (
        "IdealQubit requires a full Hamiltonian."
    )
    assert N == N_pre_diag == 2, "IdealQubit is a two-level system."
    assert "ω" in params, "IdealQubit requires a frequency parameter 'ω'."

KNO

Bases: Device

Kerr Nonlinear Oscillator Device.

Source code in jaxquantum/devices/superconducting/kno.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@struct.dataclass
class KNO(Device):
    """
    Kerr Nonlinear Oscillator Device.
    """

    @classmethod
    def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
        """This can be overridden by subclasses."""
        assert basis == BasisTypes.fock, (
            "Kerr Nonlinear Oscillator must be defined in the Fock basis."
        )
        assert hamiltonian == HamiltonianTypes.full, (
            "Kerr Nonlinear Oscillator uses a full Hamiltonian."
        )
        assert "ω" in params and "α" in params, (
            "Kerr Nonlinear Oscillator requires frequency 'ω' and anharmonicity 'α' as parameters."
        )

    def common_ops(self):
        ops = {}

        N = self.N
        ops["id"] = identity(N)
        ops["a"] = destroy(N)
        ops["a_dag"] = create(N)
        ops["phi"] = (ops["a"] + ops["a_dag"]) / jnp.sqrt(2)
        ops["n"] = 1j * (ops["a_dag"] - ops["a"]) / jnp.sqrt(2)
        return ops

    def get_linear_ω(self):
        """Get frequency of linear terms."""
        return self.params["ω"]

    def get_anharm(self):
        """Get anharmonicity."""
        return self.params["α"]

    def get_H_linear(self):
        """Return linear terms in H."""
        w = self.get_linear_ω()
        return w * self.linear_ops["a_dag"] @ self.linear_ops["a"]

    def get_H_full(self):
        """Return full H in linear basis."""
        α = self.get_anharm()

        return self.get_H_linear() + (α / 2) * (
            self.linear_ops["a_dag"]
            @ self.linear_ops["a_dag"]
            @ self.linear_ops["a"]
            @ self.linear_ops["a"]
        )

get_H_full()

Return full H in linear basis.

Source code in jaxquantum/devices/superconducting/kno.py
57
58
59
60
61
62
63
64
65
66
def get_H_full(self):
    """Return full H in linear basis."""
    α = self.get_anharm()

    return self.get_H_linear() + (α / 2) * (
        self.linear_ops["a_dag"]
        @ self.linear_ops["a_dag"]
        @ self.linear_ops["a"]
        @ self.linear_ops["a"]
    )

get_H_linear()

Return linear terms in H.

Source code in jaxquantum/devices/superconducting/kno.py
52
53
54
55
def get_H_linear(self):
    """Return linear terms in H."""
    w = self.get_linear_ω()
    return w * self.linear_ops["a_dag"] @ self.linear_ops["a"]

get_anharm()

Get anharmonicity.

Source code in jaxquantum/devices/superconducting/kno.py
48
49
50
def get_anharm(self):
    """Get anharmonicity."""
    return self.params["α"]

get_linear_ω()

Get frequency of linear terms.

Source code in jaxquantum/devices/superconducting/kno.py
44
45
46
def get_linear_ω(self):
    """Get frequency of linear terms."""
    return self.params["ω"]

param_validation(N, N_pre_diag, params, hamiltonian, basis) classmethod

This can be overridden by subclasses.

Source code in jaxquantum/devices/superconducting/kno.py
20
21
22
23
24
25
26
27
28
29
30
31
@classmethod
def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
    """This can be overridden by subclasses."""
    assert basis == BasisTypes.fock, (
        "Kerr Nonlinear Oscillator must be defined in the Fock basis."
    )
    assert hamiltonian == HamiltonianTypes.full, (
        "Kerr Nonlinear Oscillator uses a full Hamiltonian."
    )
    assert "ω" in params and "α" in params, (
        "Kerr Nonlinear Oscillator requires frequency 'ω' and anharmonicity 'α' as parameters."
    )

Qarray

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

    # Initialization ----
    @classmethod
    def create(cls, data, dims=None, bdims=None):
        # Step 1: Prepare data ----
        data = jnp.asarray(data)

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

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

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

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

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

        dims = (tuple(dims[0]), tuple(dims[1]))

        check_dims(dims, bdims, data.shape)

        qdims = Qdims(dims)

        # NOTE: Constantly tidying up on Qarray creation might be a bit overkill.
        # It increases the compilation time, but only very slightly
        # increased the runtime of the jit compiled function.
        # We could instead use this tidy_up where we think we need it.
        data = tidy_up(data, SETTINGS["auto_tidyup_atol"])

        return cls(data, qdims, bdims)

    # ----

    @classmethod
    def from_list(cls, qarr_list: List[Qarray]) -> Qarray:
        """Create a Qarray from a list of Qarrays."""

        data = jnp.array([qarr.data for qarr in qarr_list])

        if len(qarr_list) == 0:
            dims = ((), ())
            bdims = ()
        else:
            dims = qarr_list[0].dims
            bdims = qarr_list[0].bdims

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

        bdims = (len(qarr_list),) + bdims

        return cls.create(data, dims=dims, bdims=bdims)

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

        Args:
            qarr_arr (list): nested list of Qarrays

        Returns:
            Qarray: Qarray object
        """
        if isinstance(qarr_arr, Qarray):
            return qarr_arr

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

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

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

    # Properties ----
    @property
    def qtype(self):
        return self._qdims.qtype

    @property
    def dtype(self):
        return self._data.dtype

    @property
    def dims(self):
        return self._qdims.dims

    @property
    def bdims(self):
        return self._bdims

    @property
    def qdims(self):
        return self._qdims

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

    @property
    def data(self):
        return self._data

    @property
    def shaped_data(self):
        return self._data.reshape(self.bdims + self.dims[0] + self.dims[1])

    @property
    def shape(self):
        return self.data.shape

    @property
    def is_batched(self):
        return len(self.bdims) > 0

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

    def reshape_bdims(self, *args):
        """Reshape the batch dimensions of the Qarray."""
        new_bdims = tuple(args)

        if prod(new_bdims) == 0:
            new_shape = new_bdims
        else:
            new_shape = new_bdims + (prod(self.dims[0]),) + (-1,)
        return Qarray.create(
            self.data.reshape(new_shape),
            dims=self.dims,
            bdims=new_bdims,
        )

    def space_to_qdims(self, space_dims: List[int]):
        if isinstance(space_dims[0], (list, tuple)):
            return space_dims

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

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

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

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

        Returns:
            Qarray: reshaped Qarray.
        """

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

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

        return Qarray.create(self.data, dims=new_qdims, bdims=new_bdims)

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

        TODO: review and maybe deprecate this method.
        """
        dims = self.dims
        data = jnp.resize(self.data, new_shape)
        return Qarray.create(
            data,
            dims=dims,
        )

    def __len__(self):
        """Length of the Qarray."""
        if len(self.bdims) > 0:
            return self.data.shape[0]
        else:
            raise ValueError("Cannot get length of a non-batched Qarray.")

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

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

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

        return jnp.all(self.data == other.data)

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

    # ----

    # Elementary Math ----
    def __matmul__(self, other):
        if not isinstance(other, Qarray):
            return NotImplemented
        _qdims_new = self._qdims @ other._qdims
        return Qarray.create(
            self.data @ other.data,
            dims=_qdims_new.dims,
        )

    # NOTE: not possible to reach this.
    # def __rmatmul__(self, other):
    #     if not isinstance(other, Qarray):
    #         return NotImplemented

    #     _qdims_new = other._qdims @ self._qdims
    #     return Qarray.create(
    #         other.data @ self.data,
    #         dims=_qdims_new.dims,
    #     )

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

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

        return Qarray.create(
            other * self.data,
            dims=self._qdims.dims,
        )

    def __rmul__(self, other):
        # NOTE: not possible to reach this.
        # if isinstance(other, Qarray):
        #     return self.__rmatmul__(other)

        return self.__mul__(other)

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

    def __truediv__(self, other):
        """For Qarray's, this only really makes sense in the context of division by a scalar."""

        if isinstance(other, Qarray):
            raise ValueError("Cannot divide a Qarray by another Qarray.")

        return self.__mul__(1 / other)

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

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

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

        return NotImplemented

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

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

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

        if self.data.shape[-2] == self.data.shape[-1]:
            other = other + 0.0j
            if not robust_isscalar(other) and len(other.shape) > 0:  # not a scalar
                other = other.reshape(other.shape + (1, 1))
            other = Qarray.create(
                other * jnp.eye(self.data.shape[-2], dtype=self.data.dtype),
                dims=self.dims,
            )
            return self.__sub__(other)

        return NotImplemented

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

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

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

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

        return powm(self, other)

    # ----

    # String Representation ----
    def _str_header(self):
        out = ", ".join(
            [
                "Quantum array: dims = " + str(self.dims),
                "bdims = " + str(self.bdims),
                "shape = " + str(self._data.shape),
                "type = " + str(self.qtype),
            ]
        )
        return out

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

    @property
    def header(self):
        """Print the header of the Qarray."""
        return self._str_header()

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

    # ----

    # Utilities ----
    def copy(self, memo=None):
        # return Qarray.create(deepcopy(self.data), dims=self.dims)
        return self.__deepcopy__(memo)

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

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

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

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

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

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

        def func(*args, **kwargs):
            res = method_f(self.data, *args, **kwargs)

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

        return func

    # ----

    # Conversions / Reshaping ----
    def dag(self):
        return dag(self)

    def to_dm(self):
        return ket2dm(self)

    def is_dm(self):
        return self.qtype == Qtypes.oper

    def is_vec(self):
        return self.qtype == Qtypes.ket or self.qtype == Qtypes.bra

    def to_ket(self):
        return to_ket(self)

    def transpose(self, *args):
        return transpose(self, *args)

    def keep_only_diag_elements(self):
        return keep_only_diag_elements(self)

    # ----

    # Math Functions ----
    def unit(self):
        return unit(self)

    def norm(self):
        return norm(self)

    def expm(self):
        return expm(self)

    def powm(self, n):
        return powm(self, n)

    def cosm(self):
        return cosm(self)

    def sinm(self):
        return sinm(self)

    def tr(self, **kwargs):
        return tr(self, **kwargs)

    def trace(self, **kwargs):
        return tr(self, **kwargs)

    def ptrace(self, indx):
        return ptrace(self, indx)

    def eigenstates(self):
        return eigenstates(self)

    def eigenenergies(self):
        return eigenenergies(self)

    def collapse(self, mode="sum"):
        return collapse(self, mode=mode)

header property

Print the header of the Qarray.

__deepcopy__(memo)

Need to override this when defininig getattr.

Source code in jaxquantum/core/qarray.py
435
436
437
438
439
440
441
442
def __deepcopy__(self, memo):
    """Need to override this when defininig __getattr__."""

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

__len__()

Length of the Qarray.

Source code in jaxquantum/core/qarray.py
251
252
253
254
255
256
def __len__(self):
    """Length of the Qarray."""
    if len(self.bdims) > 0:
        return self.data.shape[0]
    else:
        raise ValueError("Cannot get length of a non-batched Qarray.")

__truediv__(other)

For Qarray's, this only really makes sense in the context of division by a scalar.

Source code in jaxquantum/core/qarray.py
319
320
321
322
323
324
325
def __truediv__(self, other):
    """For Qarray's, this only really makes sense in the context of division by a scalar."""

    if isinstance(other, Qarray):
        raise ValueError("Cannot divide a Qarray by another Qarray.")

    return self.__mul__(1 / other)

from_array(qarr_arr) classmethod

Create a Qarray from a nested list of Qarrays.

Parameters:

Name Type Description Default
qarr_arr list

nested list of Qarrays

required

Returns:

Name Type Description
Qarray Qarray

Qarray object

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

    Args:
        qarr_arr (list): nested list of Qarrays

    Returns:
        Qarray: Qarray object
    """
    if isinstance(qarr_arr, Qarray):
        return qarr_arr

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

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

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

from_list(qarr_list) classmethod

Create a Qarray from a list of Qarrays.

Source code in jaxquantum/core/qarray.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
@classmethod
def from_list(cls, qarr_list: List[Qarray]) -> Qarray:
    """Create a Qarray from a list of Qarrays."""

    data = jnp.array([qarr.data for qarr in qarr_list])

    if len(qarr_list) == 0:
        dims = ((), ())
        bdims = ()
    else:
        dims = qarr_list[0].dims
        bdims = qarr_list[0].bdims

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

    bdims = (len(qarr_list),) + bdims

    return cls.create(data, dims=dims, bdims=bdims)

reshape_bdims(*args)

Reshape the batch dimensions of the Qarray.

Source code in jaxquantum/core/qarray.py
193
194
195
196
197
198
199
200
201
202
203
204
205
def reshape_bdims(self, *args):
    """Reshape the batch dimensions of the Qarray."""
    new_bdims = tuple(args)

    if prod(new_bdims) == 0:
        new_shape = new_bdims
    else:
        new_shape = new_bdims + (prod(self.dims[0]),) + (-1,)
    return Qarray.create(
        self.data.reshape(new_shape),
        dims=self.dims,
        bdims=new_bdims,
    )

reshape_qdims(*args)

Reshape the quantum dimensions of the Qarray.

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

Parameters:

Name Type Description Default
*args

new Hilbert dimensions for the Qarray.

()

Returns:

Name Type Description
Qarray

reshaped Qarray.

Source code in jaxquantum/core/qarray.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def reshape_qdims(self, *args):
    """Reshape the quantum dimensions of the Qarray.

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

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

    Returns:
        Qarray: reshaped Qarray.
    """

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

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

    return Qarray.create(self.data, dims=new_qdims, bdims=new_bdims)

resize(new_shape)

Resize the Qarray to a new shape.

TODO: review and maybe deprecate this method.

Source code in jaxquantum/core/qarray.py
239
240
241
242
243
244
245
246
247
248
249
def resize(self, new_shape):
    """Resize the Qarray to a new shape.

    TODO: review and maybe deprecate this method.
    """
    dims = self.dims
    data = jnp.resize(self.data, new_shape)
    return Qarray.create(
        data,
        dims=dims,
    )

Resonator

Bases: FluxDevice

Resonator Device.

Source code in jaxquantum/devices/superconducting/resonator.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@struct.dataclass
class Resonator(FluxDevice):
    """
    Resonator Device.
    """

    def common_ops(self):
        """Written in the linear basis."""
        ops = {}

        N = self.N_pre_diag
        ops["id"] = identity(N)
        ops["a"] = destroy(N)
        ops["a_dag"] = create(N)
        ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
        ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])

        return ops

    def phi_zpf(self):
        """Return Phase ZPF."""
        return (2 * self.params["Ec"] / self.params["El"]) ** (0.25)

    def n_zpf(self):
        n_zpf = (self.params["El"] / (32.0 * self.params["Ec"])) ** (0.25)
        return n_zpf

    def get_linear_ω(self):
        """Get frequency of linear terms."""
        return jnp.sqrt(8 * self.params["El"] * self.params["Ec"])

    def get_H_linear(self):
        """Return linear terms in H."""
        w = self.get_linear_ω()
        return w * (self.linear_ops["a_dag"] @ self.linear_ops["a"] + 1 / 2)

    def get_H_full(self):
        """Return full H in linear basis."""
        return self.get_H_linear()

    def potential(self, phi):
        """Return potential energy for a given phi."""
        return 0.5 * self.params["El"] * (2 * jnp.pi * phi) ** 2

common_ops()

Written in the linear basis.

Source code in jaxquantum/devices/superconducting/resonator.py
20
21
22
23
24
25
26
27
28
29
30
31
def common_ops(self):
    """Written in the linear basis."""
    ops = {}

    N = self.N_pre_diag
    ops["id"] = identity(N)
    ops["a"] = destroy(N)
    ops["a_dag"] = create(N)
    ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
    ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])

    return ops

get_H_full()

Return full H in linear basis.

Source code in jaxquantum/devices/superconducting/resonator.py
50
51
52
def get_H_full(self):
    """Return full H in linear basis."""
    return self.get_H_linear()

get_H_linear()

Return linear terms in H.

Source code in jaxquantum/devices/superconducting/resonator.py
45
46
47
48
def get_H_linear(self):
    """Return linear terms in H."""
    w = self.get_linear_ω()
    return w * (self.linear_ops["a_dag"] @ self.linear_ops["a"] + 1 / 2)

get_linear_ω()

Get frequency of linear terms.

Source code in jaxquantum/devices/superconducting/resonator.py
41
42
43
def get_linear_ω(self):
    """Get frequency of linear terms."""
    return jnp.sqrt(8 * self.params["El"] * self.params["Ec"])

phi_zpf()

Return Phase ZPF.

Source code in jaxquantum/devices/superconducting/resonator.py
33
34
35
def phi_zpf(self):
    """Return Phase ZPF."""
    return (2 * self.params["Ec"] / self.params["El"]) ** (0.25)

potential(phi)

Return potential energy for a given phi.

Source code in jaxquantum/devices/superconducting/resonator.py
54
55
56
def potential(self, phi):
    """Return potential energy for a given phi."""
    return 0.5 * self.params["El"] * (2 * jnp.pi * phi) ** 2

Transmon

Bases: FluxDevice

Transmon Device.

Source code in jaxquantum/devices/superconducting/transmon.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@struct.dataclass
class Transmon(FluxDevice):
    """
    Transmon Device.
    """

    DEFAULT_BASIS = BasisTypes.charge
    DEFAULT_HAMILTONIAN = HamiltonianTypes.full

    @classmethod
    def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
        """This can be overridden by subclasses."""
        if hamiltonian == HamiltonianTypes.linear:
            assert basis == BasisTypes.fock, (
                "Linear Hamiltonian only works with Fock basis."
            )
        elif hamiltonian == HamiltonianTypes.truncated:
            assert basis == BasisTypes.fock, (
                "Truncated Hamiltonian only works with Fock basis."
            )
        elif hamiltonian == HamiltonianTypes.full:
            assert basis in [BasisTypes.charge, BasisTypes.single_charge], (
                "Full Hamiltonian only works with Cooper pair charge or single-electron charge bases."
            )

        # Set the gate offset charge to zero if not provided
        if "ng" not in params:
            params["ng"] = 0.0

        assert (N_pre_diag - 1) % 2 == 0, "N_pre_diag must be odd."

    def common_ops(self):
        """Written in the specified basis."""

        ops = {}

        N = self.N_pre_diag

        if self.basis == BasisTypes.fock:
            ops["id"] = identity(N)
            ops["a"] = destroy(N)
            ops["a_dag"] = create(N)
            ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
            ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])

        elif self.basis == BasisTypes.charge:
            """
            Here H = 4 * Ec (n - ng)² - Ej cos(φ) in the Cooper pair charge basis. 
            """
            ops["id"] = identity(N)
            ops["cos(φ)"] = 0.5 * (jnp2jqt(jnp.eye(N, k=1) + jnp.eye(N, k=-1)))
            ops["sin(φ)"] = 0.5j * (jnp2jqt(jnp.eye(N, k=1) - jnp.eye(N, k=-1)))
            n_max = (N - 1) // 2
            ops["n"] = jnp2jqt(jnp.diag(jnp.arange(-n_max, n_max + 1)))

            n_minus_ng_array = jnp.arange(-n_max, n_max + 1) - self.params[
                "ng"
            ] * jnp.ones(N)
            ops["H_charge"] = jnp2jqt(
                jnp.diag(4 * self.params["Ec"] * n_minus_ng_array**2)
            )

        elif self.basis == BasisTypes.single_charge:
            """
            Here H = Ec (n - 2ng)² - Ej cos(φ) in the single-electron charge basis. Using Eq. (5.36) of Kyle Serniak's
            thesis, we have H = Ec ∑ₙ(n - 2*ng) |n⟩⟨n| - Ej/2 * ∑ₙ|n⟩⟨n+2| + h.c where n counts the number of electrons, 
            not Cooper pairs. Note, we use 2ng instead of ng to match the gate offset charge convention of the transmon 
            (as done in Kyle's thesis).
            """
            n_max = (N - 1) // 2

            ops["id"] = identity(N)
            ops["cos(φ)"] = 0.5 * (jnp2jqt(jnp.eye(N, k=2) + jnp.eye(N, k=-2)))
            ops["sin(φ)"] = 0.5j * (jnp2jqt(jnp.eye(N, k=2) - jnp.eye(N, k=-2)))
            ops["cos(φ/2)"] = 0.5 * (jnp2jqt(jnp.eye(N, k=1) + jnp.eye(N, k=-1)))
            ops["sin(φ/2)"] = 0.5j * (jnp2jqt(jnp.eye(N, k=1) - jnp.eye(N, k=-1)))
            ops["n"] = jnp2jqt(jnp.diag(jnp.arange(-n_max, n_max + 1)))

            n_minus_ng_array = jnp.arange(-n_max, n_max + 1) - 2 * self.params[
                "ng"
            ] * jnp.ones(N)
            ops["H_charge"] = jnp2jqt(jnp.diag(self.params["Ec"] * n_minus_ng_array**2))

        return ops

    @property
    def Ej(self):
        return self.params["Ej"]

    def phi_zpf(self):
        """Return Phase ZPF."""
        return (2 * self.params["Ec"] / self.Ej) ** (0.25)

    def n_zpf(self):
        """Return Charge ZPF."""
        return (self.Ej / (32 * self.params["Ec"])) ** (0.25)

    def get_linear_ω(self):
        """Get frequency of linear terms."""
        return jnp.sqrt(8 * self.params["Ec"] * self.Ej)

    def get_H_linear(self):
        """Return linear terms in H."""
        w = self.get_linear_ω()
        return w * self.original_ops["a_dag"] @ self.original_ops["a"]

    def get_H_full(self):
        """Return full H in specified basis."""
        return self.original_ops["H_charge"] - self.Ej * self.original_ops["cos(φ)"]

    def get_H_truncated(self):
        """Return truncated H in specified basis."""
        phi_op = self.original_ops["phi"]
        fourth_order_term = -(1 / 24) * self.Ej * phi_op @ phi_op @ phi_op @ phi_op
        sixth_order_term = (
            (1 / 720) * self.Ej * phi_op @ phi_op @ phi_op @ phi_op @ phi_op @ phi_op
        )
        return self.get_H_linear() + fourth_order_term + sixth_order_term

    def _get_H_in_original_basis(self):
        """This returns the Hamiltonian in the original specified basis. This can be overridden by subclasses."""

        if self.hamiltonian == HamiltonianTypes.linear:
            return self.get_H_linear()
        elif self.hamiltonian == HamiltonianTypes.full:
            return self.get_H_full()
        elif self.hamiltonian == HamiltonianTypes.truncated:
            return self.get_H_truncated()

    def potential(self, phi):
        """Return potential energy for a given phi."""
        if self.hamiltonian == HamiltonianTypes.linear:
            return 0.5 * self.Ej * (2 * jnp.pi * phi) ** 2
        elif self.hamiltonian == HamiltonianTypes.full:
            return -self.Ej * jnp.cos(2 * jnp.pi * phi)
        elif self.hamiltonian == HamiltonianTypes.truncated:
            phi_scaled = 2 * jnp.pi * phi
            second_order = 0.5 * self.Ej * phi_scaled**2
            fourth_order = -(1 / 24) * self.Ej * phi_scaled**4
            sixth_order = (1 / 720) * self.Ej * phi_scaled**6
            return second_order + fourth_order + sixth_order

    def calculate_wavefunctions(self, phi_vals):
        """Calculate wavefunctions at phi_exts."""

        if self.basis == BasisTypes.fock:
            return super().calculate_wavefunctions(phi_vals)
        elif self.basis == BasisTypes.single_charge:
            raise NotImplementedError(
                "Wavefunctions for single charge basis not yet implemented."
            )
        elif self.basis == BasisTypes.charge:
            phi_vals = jnp.array(phi_vals)

            n_labels = jnp.diag(self.original_ops["n"].data)

            wavefunctions = []
            for nj in range(self.N_pre_diag):
                wavefunction = []
                for phi in phi_vals:
                    wavefunction.append(
                        (1j**nj / jnp.sqrt(2 * jnp.pi))
                        * jnp.sum(
                            self.eig_systems["vecs"][:, nj]
                            * jnp.exp(1j * phi * n_labels)
                        )
                    )
                wavefunctions.append(jnp.array(wavefunction))
            return jnp.array(wavefunctions)

calculate_wavefunctions(phi_vals)

Calculate wavefunctions at phi_exts.

Source code in jaxquantum/devices/superconducting/transmon.py
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
def calculate_wavefunctions(self, phi_vals):
    """Calculate wavefunctions at phi_exts."""

    if self.basis == BasisTypes.fock:
        return super().calculate_wavefunctions(phi_vals)
    elif self.basis == BasisTypes.single_charge:
        raise NotImplementedError(
            "Wavefunctions for single charge basis not yet implemented."
        )
    elif self.basis == BasisTypes.charge:
        phi_vals = jnp.array(phi_vals)

        n_labels = jnp.diag(self.original_ops["n"].data)

        wavefunctions = []
        for nj in range(self.N_pre_diag):
            wavefunction = []
            for phi in phi_vals:
                wavefunction.append(
                    (1j**nj / jnp.sqrt(2 * jnp.pi))
                    * jnp.sum(
                        self.eig_systems["vecs"][:, nj]
                        * jnp.exp(1j * phi * n_labels)
                    )
                )
            wavefunctions.append(jnp.array(wavefunction))
        return jnp.array(wavefunctions)

common_ops()

Written in the specified basis.

Source code in jaxquantum/devices/superconducting/transmon.py
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
def common_ops(self):
    """Written in the specified basis."""

    ops = {}

    N = self.N_pre_diag

    if self.basis == BasisTypes.fock:
        ops["id"] = identity(N)
        ops["a"] = destroy(N)
        ops["a_dag"] = create(N)
        ops["phi"] = self.phi_zpf() * (ops["a"] + ops["a_dag"])
        ops["n"] = 1j * self.n_zpf() * (ops["a_dag"] - ops["a"])

    elif self.basis == BasisTypes.charge:
        """
        Here H = 4 * Ec (n - ng)² - Ej cos(φ) in the Cooper pair charge basis. 
        """
        ops["id"] = identity(N)
        ops["cos(φ)"] = 0.5 * (jnp2jqt(jnp.eye(N, k=1) + jnp.eye(N, k=-1)))
        ops["sin(φ)"] = 0.5j * (jnp2jqt(jnp.eye(N, k=1) - jnp.eye(N, k=-1)))
        n_max = (N - 1) // 2
        ops["n"] = jnp2jqt(jnp.diag(jnp.arange(-n_max, n_max + 1)))

        n_minus_ng_array = jnp.arange(-n_max, n_max + 1) - self.params[
            "ng"
        ] * jnp.ones(N)
        ops["H_charge"] = jnp2jqt(
            jnp.diag(4 * self.params["Ec"] * n_minus_ng_array**2)
        )

    elif self.basis == BasisTypes.single_charge:
        """
        Here H = Ec (n - 2ng)² - Ej cos(φ) in the single-electron charge basis. Using Eq. (5.36) of Kyle Serniak's
        thesis, we have H = Ec ∑ₙ(n - 2*ng) |n⟩⟨n| - Ej/2 * ∑ₙ|n⟩⟨n+2| + h.c where n counts the number of electrons, 
        not Cooper pairs. Note, we use 2ng instead of ng to match the gate offset charge convention of the transmon 
        (as done in Kyle's thesis).
        """
        n_max = (N - 1) // 2

        ops["id"] = identity(N)
        ops["cos(φ)"] = 0.5 * (jnp2jqt(jnp.eye(N, k=2) + jnp.eye(N, k=-2)))
        ops["sin(φ)"] = 0.5j * (jnp2jqt(jnp.eye(N, k=2) - jnp.eye(N, k=-2)))
        ops["cos(φ/2)"] = 0.5 * (jnp2jqt(jnp.eye(N, k=1) + jnp.eye(N, k=-1)))
        ops["sin(φ/2)"] = 0.5j * (jnp2jqt(jnp.eye(N, k=1) - jnp.eye(N, k=-1)))
        ops["n"] = jnp2jqt(jnp.diag(jnp.arange(-n_max, n_max + 1)))

        n_minus_ng_array = jnp.arange(-n_max, n_max + 1) - 2 * self.params[
            "ng"
        ] * jnp.ones(N)
        ops["H_charge"] = jnp2jqt(jnp.diag(self.params["Ec"] * n_minus_ng_array**2))

    return ops

get_H_full()

Return full H in specified basis.

Source code in jaxquantum/devices/superconducting/transmon.py
122
123
124
def get_H_full(self):
    """Return full H in specified basis."""
    return self.original_ops["H_charge"] - self.Ej * self.original_ops["cos(φ)"]

get_H_linear()

Return linear terms in H.

Source code in jaxquantum/devices/superconducting/transmon.py
117
118
119
120
def get_H_linear(self):
    """Return linear terms in H."""
    w = self.get_linear_ω()
    return w * self.original_ops["a_dag"] @ self.original_ops["a"]

get_H_truncated()

Return truncated H in specified basis.

Source code in jaxquantum/devices/superconducting/transmon.py
126
127
128
129
130
131
132
133
def get_H_truncated(self):
    """Return truncated H in specified basis."""
    phi_op = self.original_ops["phi"]
    fourth_order_term = -(1 / 24) * self.Ej * phi_op @ phi_op @ phi_op @ phi_op
    sixth_order_term = (
        (1 / 720) * self.Ej * phi_op @ phi_op @ phi_op @ phi_op @ phi_op @ phi_op
    )
    return self.get_H_linear() + fourth_order_term + sixth_order_term

get_linear_ω()

Get frequency of linear terms.

Source code in jaxquantum/devices/superconducting/transmon.py
113
114
115
def get_linear_ω(self):
    """Get frequency of linear terms."""
    return jnp.sqrt(8 * self.params["Ec"] * self.Ej)

n_zpf()

Return Charge ZPF.

Source code in jaxquantum/devices/superconducting/transmon.py
109
110
111
def n_zpf(self):
    """Return Charge ZPF."""
    return (self.Ej / (32 * self.params["Ec"])) ** (0.25)

param_validation(N, N_pre_diag, params, hamiltonian, basis) classmethod

This can be overridden by subclasses.

Source code in jaxquantum/devices/superconducting/transmon.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@classmethod
def param_validation(cls, N, N_pre_diag, params, hamiltonian, basis):
    """This can be overridden by subclasses."""
    if hamiltonian == HamiltonianTypes.linear:
        assert basis == BasisTypes.fock, (
            "Linear Hamiltonian only works with Fock basis."
        )
    elif hamiltonian == HamiltonianTypes.truncated:
        assert basis == BasisTypes.fock, (
            "Truncated Hamiltonian only works with Fock basis."
        )
    elif hamiltonian == HamiltonianTypes.full:
        assert basis in [BasisTypes.charge, BasisTypes.single_charge], (
            "Full Hamiltonian only works with Cooper pair charge or single-electron charge bases."
        )

    # Set the gate offset charge to zero if not provided
    if "ng" not in params:
        params["ng"] = 0.0

    assert (N_pre_diag - 1) % 2 == 0, "N_pre_diag must be odd."

phi_zpf()

Return Phase ZPF.

Source code in jaxquantum/devices/superconducting/transmon.py
105
106
107
def phi_zpf(self):
    """Return Phase ZPF."""
    return (2 * self.params["Ec"] / self.Ej) ** (0.25)

potential(phi)

Return potential energy for a given phi.

Source code in jaxquantum/devices/superconducting/transmon.py
145
146
147
148
149
150
151
152
153
154
155
156
def potential(self, phi):
    """Return potential energy for a given phi."""
    if self.hamiltonian == HamiltonianTypes.linear:
        return 0.5 * self.Ej * (2 * jnp.pi * phi) ** 2
    elif self.hamiltonian == HamiltonianTypes.full:
        return -self.Ej * jnp.cos(2 * jnp.pi * phi)
    elif self.hamiltonian == HamiltonianTypes.truncated:
        phi_scaled = 2 * jnp.pi * phi
        second_order = 0.5 * self.Ej * phi_scaled**2
        fourth_order = -(1 / 24) * self.Ej * phi_scaled**4
        sixth_order = (1 / 720) * self.Ej * phi_scaled**6
        return second_order + fourth_order + sixth_order

TunableTransmon

Bases: Transmon

Tunable Transmon Device.

Source code in jaxquantum/devices/superconducting/tunable_transmon.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@struct.dataclass
class TunableTransmon(Transmon):
    """
    Tunable Transmon Device.
    """

    @property
    def Ej(self):
        Ejsum = self.params["Ej1"] + self.params["Ej2"]
        phi_ext = 2 * jnp.pi * self.params["phi_ext"]
        gamma = self.params["Ej2"] / self.params["Ej1"]
        d = (gamma - 1) / (gamma + 1)
        external_flux_factor = jnp.abs(
            jnp.sqrt(jnp.cos(phi_ext / 2) ** 2 + d**2 * jnp.sin(phi_ext / 2) ** 2)
        )
        return Ejsum * external_flux_factor

cosm(qarr)

Matrix cosine wrapper.

Parameters:

Name Type Description Default
qarr Qarray

quantum array

required

Returns:

Type Description
Qarray

matrix cosine

Source code in jaxquantum/core/qarray.py
744
745
746
747
748
749
750
751
752
753
754
755
def cosm(qarr: Qarray) -> Qarray:
    """Matrix cosine wrapper.

    Args:
        qarr (Qarray): quantum array

    Returns:
        matrix cosine
    """
    dims = qarr.dims
    data = cosm_data(qarr.data)
    return Qarray.create(data, dims=dims)

create(N)

creation operator

Parameters:

Name Type Description Default
N

Hilbert space size

required

Returns:

Type Description
Qarray

creation operator in Hilber Space of size N

Source code in jaxquantum/core/operators.py
 98
 99
100
101
102
103
104
105
106
107
def create(N) -> Qarray:
    """creation operator

    Args:
        N: Hilbert space size

    Returns:
        creation operator in Hilber Space of size N
    """
    return Qarray.create(jnp.diag(jnp.sqrt(jnp.arange(1, N)), k=-1))

destroy(N)

annihilation operator

Parameters:

Name Type Description Default
N

Hilbert space size

required

Returns:

Type Description
Qarray

annilation operator in Hilber Space of size N

Source code in jaxquantum/core/operators.py
86
87
88
89
90
91
92
93
94
95
def destroy(N) -> Qarray:
    """annihilation operator

    Args:
        N: Hilbert space size

    Returns:
        annilation operator in Hilber Space of size N
    """
    return Qarray.create(jnp.diag(jnp.sqrt(jnp.arange(1, N)), k=1))

harm_osc_wavefunction(n, x, l_osc)

Taken from scqubits... not jit-able

For given quantum number n=0,1,2,... return the value of the harmonic oscillator wave function :math:\psi_n(x) = N H_n(x/l_{osc}) \exp(-x^2/2l_\text{ osc}), N being the proper normalization factor.

Directly uses scipy.special.pbdv (implementation of the parabolic cylinder function) to mitigate numerical stability issues with the more commonly used expression in terms of a Gaussian and a Hermite polynomial factor.

Parameters

n: index of wave function, n=0 is ground state x: coordinate(s) where wave function is evaluated l_osc: oscillator length, defined via <0|x^2|0> = l_osc^2/2

Returns

value of harmonic oscillator wave function
Source code in jaxquantum/devices/common/utils.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def harm_osc_wavefunction(n, x, l_osc):
    r"""
    Taken from scqubits... not jit-able

    For given quantum number n=0,1,2,... return the value of the harmonic
    oscillator wave function :math:`\psi_n(x) = N H_n(x/l_{osc}) \exp(-x^2/2l_\text{
    osc})`, N being the proper normalization factor.

    Directly uses `scipy.special.pbdv` (implementation of the parabolic cylinder
    function) to mitigate numerical stability issues with the more commonly used
    expression in terms of a Gaussian and a Hermite polynomial factor.

    Parameters
    ----------
    n:
        index of wave function, n=0 is ground state
    x:
        coordinate(s) where wave function is evaluated
    l_osc:
        oscillator length, defined via <0|x^2|0> = l_osc^2/2

    Returns
    -------
        value of harmonic oscillator wave function
    """
    x = 2 * jnp.pi * x
    result = pbdv(n, jnp.sqrt(2.0) * x / l_osc)[0]
    result = result / jnp.sqrt(l_osc * jnp.sqrt(jnp.pi) * factorial_approx(n))
    return result

identity(*args, **kwargs)

Identity matrix.

Returns:

Type Description
Qarray

Identity matrix.

Source code in jaxquantum/core/operators.py
122
123
124
125
126
127
128
def identity(*args, **kwargs) -> Qarray:
    """Identity matrix.

    Returns:
        Identity matrix.
    """
    return Qarray.create(jnp.eye(*args, **kwargs))

jnp2jqt(arr, dims=None)

JAX array -> QuTiP state.

Parameters:

Name Type Description Default
jnp_obj

JAX array.

required
dims Optional[Union[DIMS_TYPE, List[int]]]

Qarray dims.

None

Returns:

Type Description

QuTiP state.

Source code in jaxquantum/core/conversions.py
79
80
81
82
83
84
85
86
87
88
89
90
def jnp2jqt(arr: Array, dims: Optional[Union[DIMS_TYPE, List[int]]] = None):
    """JAX array -> QuTiP state.

    Args:
        jnp_obj: JAX array.
        dims: Qarray dims.

    Returns:
        QuTiP state.
    """
    dims = extract_dims(arr, dims) if dims is not None else None
    return Qarray.create(arr, dims=dims)

sigmam()

σ-

Returns:

Type Description
Qarray

σ- Pauli Operator

Source code in jaxquantum/core/operators.py
51
52
53
54
55
56
57
def sigmam() -> Qarray:
    """σ-

    Returns:
        σ- Pauli Operator
    """
    return Qarray.create(jnp.array([[0.0, 0.0], [1.0, 0.0]]))

sigmap()

σ+

Returns:

Type Description
Qarray

σ+ Pauli Operator

Source code in jaxquantum/core/operators.py
60
61
62
63
64
65
66
def sigmap() -> Qarray:
    """σ+

    Returns:
        σ+ Pauli Operator
    """
    return Qarray.create(jnp.array([[0.0, 1.0], [0.0, 0.0]]))

sigmax()

σx

Returns:

Type Description
Qarray

σx Pauli Operator

Source code in jaxquantum/core/operators.py
15
16
17
18
19
20
21
def sigmax() -> Qarray:
    """σx

    Returns:
        σx Pauli Operator
    """
    return Qarray.create(jnp.array([[0.0, 1.0], [1.0, 0.0]]))

sigmay()

σy

Returns:

Type Description
Qarray

σy Pauli Operator

Source code in jaxquantum/core/operators.py
24
25
26
27
28
29
30
def sigmay() -> Qarray:
    """σy

    Returns:
        σy Pauli Operator
    """
    return Qarray.create(jnp.array([[0.0, -1.0j], [1.0j, 0.0]]))

sigmaz()

σz

Returns:

Type Description
Qarray

σz Pauli Operator

Source code in jaxquantum/core/operators.py
33
34
35
36
37
38
39
def sigmaz() -> Qarray:
    """σz

    Returns:
        σz Pauli Operator
    """
    return Qarray.create(jnp.array([[1.0, 0.0], [0.0, -1.0]]))