Skip to content

Data

inspeqtor.data

inspeqtor.data.QubitInformation dataclass

Dataclass to store qubit information

Parameters:

Name Type Description Default
unit str

The string representation of unit, currently support "GHz", "2piGHz", "2piHz", or "Hz".

required
qubit_idx int

the index of the qubit.

required
anharmonicity float

Anhamonicity of the qubit, kept for the sake of completeness.

required
frequency float

Qubit frequency.

required
drive_strength float

Drive strength of qubit, might be specific for IBMQ platform.

required

Raises:

Type Description
ValueError

Fail to convert unit to GHz

Source code in src/inspeqtor/v1/data.py
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
@dataclass
class QubitInformation:
    """Dataclass to store qubit information

    Args:
        unit (str): The string representation of unit, currently support "GHz", "2piGHz", "2piHz", or "Hz".
        qubit_idx (int): the index of the qubit.
        anharmonicity (float): Anhamonicity of the qubit, kept for the sake of completeness.
        frequency (float): Qubit frequency.
        drive_strength (float): Drive strength of qubit, might be specific for IBMQ platform.

    Raises:
        ValueError: Fail to convert unit to GHz
    """

    unit: str
    qubit_idx: int
    anharmonicity: float
    frequency: float
    drive_strength: float
    date: str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    def __post_init__(self):
        self.convert_unit_to_ghz()

    def convert_unit_to_ghz(self):
        """Convert the unit of data stored in self to unit of GHz

        Raises:
            ValueError: Data stored in the unsupported unit
        """
        if self.unit == "GHz":
            pass
        elif self.unit == "Hz":
            self.anharmonicity = self.anharmonicity * 1e-9
            self.frequency = self.frequency * 1e-9
            self.drive_strength = self.drive_strength * 1e-9
        elif self.unit == "2piGHz":
            self.anharmonicity = self.anharmonicity / (2 * jnp.pi)
            self.frequency = self.frequency / (2 * jnp.pi)
            self.drive_strength = self.drive_strength / (2 * jnp.pi)
        elif self.unit == "2piHz":
            self.anharmonicity = self.anharmonicity / (2 * jnp.pi) * 1e-9
            self.frequency = self.frequency / (2 * jnp.pi) * 1e-9
            self.drive_strength = self.drive_strength / (2 * jnp.pi) * 1e-9
        else:
            raise ValueError("Unit must be GHz, 2piGHz, 2piHz, or Hz")

        # Set unit to GHz
        self.unit = "GHz"

    def to_dict(self):
        return asdict(self)

    @classmethod
    def from_dict(cls, dict_qubit_info: dict):
        return cls(**dict_qubit_info)

convert_unit_to_ghz

convert_unit_to_ghz()

Convert the unit of data stored in self to unit of GHz

Raises:

Type Description
ValueError

Data stored in the unsupported unit

Source code in src/inspeqtor/v1/data.py
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
def convert_unit_to_ghz(self):
    """Convert the unit of data stored in self to unit of GHz

    Raises:
        ValueError: Data stored in the unsupported unit
    """
    if self.unit == "GHz":
        pass
    elif self.unit == "Hz":
        self.anharmonicity = self.anharmonicity * 1e-9
        self.frequency = self.frequency * 1e-9
        self.drive_strength = self.drive_strength * 1e-9
    elif self.unit == "2piGHz":
        self.anharmonicity = self.anharmonicity / (2 * jnp.pi)
        self.frequency = self.frequency / (2 * jnp.pi)
        self.drive_strength = self.drive_strength / (2 * jnp.pi)
    elif self.unit == "2piHz":
        self.anharmonicity = self.anharmonicity / (2 * jnp.pi) * 1e-9
        self.frequency = self.frequency / (2 * jnp.pi) * 1e-9
        self.drive_strength = self.drive_strength / (2 * jnp.pi) * 1e-9
    else:
        raise ValueError("Unit must be GHz, 2piGHz, 2piHz, or Hz")

    # Set unit to GHz
    self.unit = "GHz"

inspeqtor.data.DataBundled dataclass

Source code in src/inspeqtor/v1/data.py
16
17
18
19
20
21
22
@jax.tree_util.register_dataclass
@dataclass
class DataBundled:
    control_params: jnp.ndarray
    unitaries: jnp.ndarray
    observables: jnp.ndarray
    aux: jnp.ndarray | None = None

inspeqtor.data.ExpectationValue dataclass

Class representing a single experimental setting of state initialization and observable measurement.

Supports both single-qubit and multi-qubit configurations using string representation: - Observable: "XYZ" (instead of ["X", "Y", "Z"]) - Initial state: "+0r" (instead of ["+", "0", "r"])

Source code in src/inspeqtor/v2/data.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
60
61
62
63
64
65
66
@dataclass
class ExpectationValue:
    """Class representing a single experimental setting of state initialization and observable measurement.

    Supports both single-qubit and multi-qubit configurations using string representation:
    - Observable: "XYZ" (instead of ["X", "Y", "Z"])
    - Initial state: "+0r" (instead of ["+", "0", "r"])
    """

    initial_state: str
    # String where each character represents an observable for one qubit
    observable: str
    # String where each character represents an initial state for one qubit

    def __post_init__(self):
        # Ensure both strings have the same length (number of qubits)
        assert len(self.observable) == len(self.initial_state), (
            f"Observable and initial state must have same number of qubits: {len(self.observable)} != {len(self.initial_state)}"
        )

        # Validate observable characters
        for o in self.observable:
            assert o in "IXYZ", (
                f"Invalid observable '{o}'. Must be one of 'I', 'X', 'Y', or 'Z'"
            )

        # Validate initial state characters
        valid_states = "+-rl01"
        for s in self.initial_state:
            assert s in valid_states, (
                f"Invalid initial state '{s}'. Must be one of {valid_states}"
            )

    def to_dict(self):
        return {
            "initial_state": self.initial_state,
            "observable": self.observable,
        }

    def __eq__(self, __value: object) -> bool:
        if not isinstance(__value, ExpectationValue):
            return False

        return (
            self.initial_state == __value.initial_state
            and self.observable == __value.observable
        )

    @classmethod
    def from_dict(cls, data):
        return cls(**data)

    def __str__(self) -> str:
        return self.initial_state + "/" + self.observable

inspeqtor.data.ExperimentalData dataclass

Dataclass for processing of the characterization dataset. A difference between preprocess and postprocess dataset is that postprocess group expectation values same control parameter id within single row instead of multiple rows.

Source code in src/inspeqtor/v2/data.py
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
@dataclass
class ExperimentalData:
    """Dataclass for processing of the characterization dataset.
    A difference between preprocess and postprocess dataset is that postprocess group
    expectation values same control parameter id within single row instead of multiple rows.
    """

    config: ExperimentConfiguration
    parameter_dataframe: pl.DataFrame
    observed_dataframe: pl.DataFrame
    mode: typing.Literal["expectation_value", "binary"] = "expectation_value"

    def __post_init__(self):
        self.validate()

    def validate(self):
        assert "parameter_id" in self.parameter_dataframe
        assert "parameter_id" in self.observed_dataframe

        assert (
            self.parameter_dataframe["parameter_id"]
            .unique()
            .sort()
            .equals(self.observed_dataframe["parameter_id"].unique().sort())
        )

    def get_parameter(self) -> jnp.ndarray:
        col_selector = ["/".join(param) for param in self.config.parameter_structure]
        return self.parameter_dataframe[col_selector].to_jax("array")

    def get_observed(self) -> jnp.ndarray:
        col_selector = [str(expval) for expval in self.config.expectation_values_order]

        if self.mode == "binary":
            return jnp.array(
                [
                    calculate_expectation_value_from_binary_dataframe(
                        str(exp), self.observed_dataframe
                    )
                    for exp in self.config.expectation_values_order
                ]
            ).transpose()

        return self.observed_dataframe[col_selector].to_jax("array")

    def save_to_folder(self, path: str | Path):
        if isinstance(path, str):
            path = Path(path)

        path.mkdir(parents=True, exist_ok=True)
        self.config.to_file(path)

        self.parameter_dataframe.write_csv(path / "parameter.csv")
        self.observed_dataframe.write_csv(path / "observed.csv")

    @classmethod
    def from_folder(cls, path: str | Path) -> "ExperimentalData":
        if isinstance(path, str):
            path = Path(path)

        config = ExperimentConfiguration.from_file(path)
        parameter_dataframe = pl.read_csv(path / "parameter.csv")
        observed_dataframe = pl.read_csv(path / "observed.csv")

        return cls(
            config=config,
            parameter_dataframe=parameter_dataframe,
            observed_dataframe=observed_dataframe,
        )

    def __eq__(self, __value: object) -> bool:
        if not isinstance(__value, ExperimentalData):
            return False

        return (
            self.config == __value.config
            and self.parameter_dataframe.equals(__value.parameter_dataframe)
            and self.observed_dataframe.equals(__value.observed_dataframe)
        )

    def __str__(self):
        lines = [
            "=" * 60,
            "EXPERIMENTAL DATA",
            str(self.config),
            "",
            "Parameter DataFrame",
            str(self.parameter_dataframe),
            "",
            "Observed DataFrame",
            str(self.observed_dataframe),
            "=" * 60,
        ]
        return "\n".join(lines)

inspeqtor.data.ExperimentConfiguration dataclass

Experiment configuration dataclass

Source code in src/inspeqtor/v2/data.py
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
@dataclass
class ExperimentConfiguration:
    """Experiment configuration dataclass"""

    qubits: typing.Sequence[QubitInformation]
    expectation_values_order: typing.Sequence[ExpectationValue]
    parameter_structure: typing.Sequence[
        typing.Sequence[str]
    ]  # Get from the pulse sequence .get_parameter_names()
    backend_name: str
    shots: int
    EXPERIMENT_IDENTIFIER: str
    EXPERIMENT_TAGS: typing.Sequence[str]
    description: str
    device_cycle_time_ns: float
    sequence_duration_dt: int
    sample_size: int
    date: str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    additional_info: dict[str, str | int | float] = field(default_factory=dict)

    def to_dict(self):
        return {
            **asdict(self),
            "qubits": [qubit.to_dict() for qubit in self.qubits],
            "expectation_values_order": [
                exp.to_dict() for exp in self.expectation_values_order
            ],
        }

    @classmethod
    def from_dict(cls, dict_experiment_config):
        dict_experiment_config["qubits"] = [
            QubitInformation.from_dict(qubit)
            for qubit in dict_experiment_config["qubits"]
        ]

        dict_experiment_config["expectation_values_order"] = [
            ExpectationValue.from_dict(exp)
            for exp in dict_experiment_config["expectation_values_order"]
        ]

        dict_experiment_config["parameter_structure"] = [
            tuple(control) for control in dict_experiment_config["parameter_structure"]
        ]

        return cls(**dict_experiment_config)

    def to_file(self, path: typing.Union[Path, str]):
        if isinstance(path, str):
            path = Path(path)

        # os.makedirs(path, exist_ok=True)
        path.mkdir(parents=True, exist_ok=True)
        with open(path / "config.json", "w") as f:
            json.dump(self.to_dict(), f, indent=4)

    @classmethod
    def from_file(cls, path: typing.Union[Path, str]):
        if isinstance(path, str):
            path = Path(path)
        with open(path / "config.json", "r") as f:
            dict_experiment_config = json.load(f)

        return cls.from_dict(dict_experiment_config)

    def __str__(self):
        lines = [
            "=" * 60,
            "EXPERIMENT CONFIGURATION",
            "=" * 60,
            f"Identifier: {self.EXPERIMENT_IDENTIFIER}",
            f"Backend: {self.backend_name}",
            f"Date: {self.date}",
            f"Description: {self.description}",
            "",
            f"Shots: {self.shots:,}",
            f"Sample Size: {self.sample_size}",
            f"Device Cycle Time: {self.device_cycle_time_ns:.4f} ns",
            f"Sequence Duration: {self.sequence_duration_dt} dt",
            "",
            f"Qubits: {len(self.qubits)}",
            *[f"  - {qubit}" for qubit in self.qubits],
            "",
            f"Expectation Values: {len(self.expectation_values_order)}",
            f"  (States: {set(e.initial_state for e in self.expectation_values_order)})",
            f"  (Observables: {set(e.observable for e in self.expectation_values_order)})",
            "",
            f"Parameter Structure: {self.parameter_structure}",
            f"Tags: {', '.join(self.EXPERIMENT_TAGS)}",
            "=" * 60,
        ]
        return "\n".join(lines)

inspeqtor.data.get_observable_operator

get_observable_operator(observable: str) -> ndarray

Get the full observable operator as a tensor product

Source code in src/inspeqtor/v2/data.py
109
110
111
112
113
114
def get_observable_operator(observable: str) -> jnp.ndarray:
    """Get the full observable operator as a tensor product"""
    ops = [operator_from_label(label) for label in observable]
    if len(ops) == 1:
        return ops[0]
    return tensor_product(*ops)

inspeqtor.data.get_initial_state

get_initial_state(
    initial_state: str, dm: bool = True
) -> ndarray

Get the initial state as state vector or density matrix

Source code in src/inspeqtor/v2/data.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def get_initial_state(initial_state: str, dm: bool = True) -> jnp.ndarray:
    """Get the initial state as state vector or density matrix"""
    states = [state_from_label(label, dm=False) for label in initial_state]

    if len(states) == 1:
        state = states[0]
    else:
        # For multi-qubit state, compute the tensor product
        result = states[0]
        for s in states[1:]:
            result = jnp.kron(result, s)
        state = result

    # Convert to vector shape if needed
    if state.shape == (2, 1) or state.shape == (2 ** len(states), 1):
        # Already in correct shape
        pass
    elif state.shape == (2,) or state.shape == (2 ** len(states),):
        # Reshape to column vector
        state = state.reshape(-1, 1)

    if dm:
        return jnp.outer(state, state.conj())
    return state

inspeqtor.data.get_complete_expectation_values

get_complete_expectation_values(
    num_qubits: int,
    observables: Iterable[Literal["I", "X", "Y", "Z"]] = [
        "I",
        "X",
        "Y",
        "Z",
    ],
    states: Iterable[
        Literal["+", "-", "r", "l", "0", "1"]
    ] = ["+", "-", "r", "l", "0", "1"],
    exclude_all_identities: bool = True,
) -> list[ExpectationValue]

Generate a complete set of expectation values for characterizing a multi-qubit system

Source code in src/inspeqtor/v2/data.py
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
def get_complete_expectation_values(
    num_qubits: int,
    observables: typing.Iterable[typing.Literal["I", "X", "Y", "Z"]] = [
        "I",
        "X",
        "Y",
        "Z",
    ],
    states: typing.Iterable[typing.Literal["+", "-", "r", "l", "0", "1"]] = [
        "+",
        "-",
        "r",
        "l",
        "0",
        "1",
    ],
    exclude_all_identities: bool = True,
) -> list[ExpectationValue]:
    """Generate a complete set of expectation values for characterizing a multi-qubit system"""

    # For n qubits, we need all combinations of observables and states
    result: typing.Iterable[ExpectationValue] = []

    # Generate all combinations of observables
    for obs_combo in itertools.product(observables, repeat=num_qubits):
        for state_combo in itertools.product(states, repeat=num_qubits):
            obs_str = "".join(obs_combo)
            state_str = "".join(state_combo)
            result.append(ExpectationValue(observable=obs_str, initial_state=state_str))

    if exclude_all_identities:
        result = [exp for exp in result if exp.observable != "I" * num_qubits]

    return result

inspeqtor.data.load_data_from_path

load_data_from_path(
    path: str | Path,
    hamiltonian_spec: HamiltonianSpec,
    control_reader=default_control_reader,
) -> LoadedData

Load and prepare the experimental data from given path and hamiltonian spec.

Parameters:

Name Type Description Default
path str | Path

The path to the folder that contain experimental data.

required
hamiltonian_spec HamiltonianSpec

The specification of the Hamiltonian

required
control_reader Any

description. Defaults to default_control_reader.

default_control_reader

Returns:

Name Type Description
LoadedData LoadedData

The object contatin necessary information for device characterization.

Source code in src/inspeqtor/v2/predefined.py
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
def load_data_from_path(
    path: str | pathlib.Path,
    hamiltonian_spec: HamiltonianSpec,
    control_reader=default_control_reader,
) -> LoadedData:
    """Load and prepare the experimental data from given path and hamiltonian spec.

    Args:
        path (str | pathlib.Path): The path to the folder that contain experimental data.
        hamiltonian_spec (HamiltonianSpec): The specification of the Hamiltonian
        control_reader (typing.Any, optional): _description_. Defaults to default_control_reader.

    Returns:
        LoadedData: The object contatin necessary information for device characterization.
    """
    exp_data = ExperimentalData.from_folder(path)
    control_sequence = control_reader(path)

    assert isinstance(control_sequence, ControlSequence)

    qubit_info = exp_data.config.qubits[0]
    dt = exp_data.config.device_cycle_time_ns

    whitebox = hamiltonian_spec.get_solver(
        control_sequence,
        qubit_info,
        dt,
    )

    return prepare_data(exp_data, control_sequence, whitebox)

inspeqtor.data.save_data_to_path

save_data_to_path(
    path: str | Path,
    experiment_data: ExperimentalData,
    control_sequence: ControlSequence,
)

Save the experimental data to the path

Parameters:

Name Type Description Default
path str | Path

The path to folder to save the experimental data

required
experiment_data ExperimentData

The experimental data object

required
control_sequence ControlSequence

The control sequence that used to create the experimental data.

required

Returns:

Name Type Description
None
Source code in src/inspeqtor/v2/predefined.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def save_data_to_path(
    path: str | pathlib.Path,
    experiment_data: ExperimentalData,
    control_sequence: ControlSequence,
):
    """Save the experimental data to the path

    Args:
        path (str | pathlib.Path): The path to folder to save the experimental data
        experiment_data (ExperimentData): The experimental data object
        control_sequence (ControlSequence): The control sequence that used to create the experimental data.

    Returns:
        None:
    """
    path = pathlib.Path(path)
    path.mkdir(parents=True, exist_ok=True)
    experiment_data.save_to_folder(path)
    control_sequence.to_file(path)

inspeqtor.data.LoadedData dataclass

A utility dataclass holding objects necessary for device characterization.

Source code in src/inspeqtor/v2/utils.py
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass
class LoadedData:
    """A utility dataclass holding objects necessary for device characterization."""

    experiment_data: ExperimentalData
    control_parameters: jnp.ndarray
    unitaries: jnp.ndarray
    observed_values: jnp.ndarray
    control_sequence: ControlSequence
    whitebox: typing.Callable
    noisy_whitebox: typing.Callable | None = None
    noisy_unitaries: jnp.ndarray | None = None

inspeqtor.data.prepare_data

prepare_data(
    exp_data: ExperimentalData,
    control_sequence: ControlSequence,
    whitebox: Callable,
) -> LoadedData

Prepare the data for easy accessing from experiment data, control sequence, and Whitebox.

Parameters:

Name Type Description Default
exp_data ExperimentData

ExperimentData instance

required
control_sequence ControlSequence

Control sequence of the experiment

required
whitebox Callable

Ideal unitary solver.

required

Returns:

Name Type Description
LoadedData LoadedData

LoadedData instance

Source code in src/inspeqtor/v2/utils.py
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
def prepare_data(
    exp_data: ExperimentalData,
    control_sequence: ControlSequence,
    whitebox: typing.Callable,
) -> LoadedData:
    """Prepare the data for easy accessing from experiment data, control sequence, and Whitebox.

    Args:
        exp_data (ExperimentData): `ExperimentData` instance
        control_sequence (ControlSequence): Control sequence of the experiment
        whitebox (typing.Callable): Ideal unitary solver.

    Returns:
        LoadedData: `LoadedData` instance
    """
    logging.info(f"Loaded data from {exp_data.config.EXPERIMENT_IDENTIFIER}")

    control_parameters = exp_data.get_parameter()

    expectation_values = exp_data.get_observed()
    unitaries = jax.vmap(whitebox)(control_parameters)

    logging.info(
        f"Finished preparing the data for the experiment {exp_data.config.EXPERIMENT_IDENTIFIER}"
    )

    return LoadedData(
        experiment_data=exp_data,
        control_parameters=control_parameters,
        unitaries=unitaries[:, -1, :, :],
        observed_values=expectation_values,
        control_sequence=control_sequence,
        whitebox=whitebox,
    )

Library

inspeqtor.data.library

inspeqtor.data.library.get_predefined_data_model_m1

get_predefined_data_model_m1(
    detune: float = 0.0001,
    get_envelope_transformer=get_envelope_transformer,
    trotterization: bool = True,
    trotter_steps: int = 10000,
)
Source code in src/inspeqtor/v2/predefined.py
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
def get_predefined_data_model_m1(
    detune: float = 0.0001,
    get_envelope_transformer=get_envelope_transformer,
    trotterization: bool = True,
    trotter_steps: int = 10_000,
):
    dt = 2 / 9
    real_qubit_info = QubitInformation(
        unit="GHz",
        qubit_idx=0,
        anharmonicity=-0.2,
        frequency=5.0,
        drive_strength=0.1,
    )
    # The drive frequenct is detune by .01%

    characterized_qubit_info = QubitInformation(
        unit="GHz",
        qubit_idx=0,
        anharmonicity=-0.2,
        frequency=5.0 * (1 + detune),
        drive_strength=0.1,
    )

    control_seq = get_drag_pulse_v2_sequence(
        qubit_info_drive_strength=characterized_qubit_info.drive_strength,
        min_beta=0.0,
        max_beta=10.0,
        dt=dt,
    )

    signal_fn = make_signal_fn(
        get_envelope=get_envelope_transformer(control_seq),
        drive_frequency=characterized_qubit_info.frequency,
        dt=dt,
    )
    hamiltonian = partial(
        transmon_hamiltonian, qubit_info=real_qubit_info, signal=signal_fn
    )
    frame = (jnp.pi * characterized_qubit_info.frequency) * Z
    hamiltonian = auto_rotating_frame_hamiltonian(hamiltonian, frame=frame)

    if trotterization:
        _solver = make_trotterization_solver(
            hamiltonian=hamiltonian,
            total_dt=control_seq.total_dt,
            dt=dt,
            trotter_steps=trotter_steps,
            y0=jnp.eye(2, dtype=jnp.complex128),
        )

    else:
        _solver = partial(
            solver,
            t_eval=jnp.linspace(0, control_seq.total_dt * dt, 321),
            hamiltonian=hamiltonian,
            y0=jnp.eye(2, dtype=jnp.complex128),
            t0=0,
            t1=control_seq.total_dt * dt,
        )

    ideal_hamiltonian = partial(
        transmon_hamiltonian,
        qubit_info=characterized_qubit_info,
        signal=signal_fn,  # Already used the characterized_qubit
    )
    ideal_hamiltonian = auto_rotating_frame_hamiltonian(ideal_hamiltonian, frame=frame)

    if trotterization:
        whitebox = make_trotterization_solver(
            hamiltonian=ideal_hamiltonian,
            total_dt=control_seq.total_dt,
            dt=dt,
            trotter_steps=trotter_steps,
            y0=jnp.eye(2, dtype=jnp.complex128),
        )
    else:
        whitebox = partial(
            solver,
            t_eval=jnp.linspace(0, control_seq.total_dt * dt, 321),
            hamiltonian=ideal_hamiltonian,
            y0=jnp.eye(2, dtype=jnp.complex128),
            t0=0,
            t1=control_seq.total_dt * dt,
        )

    return SyntheticDataModel(
        control_sequence=control_seq,
        qubit_information=characterized_qubit_info,
        dt=dt,
        ideal_hamiltonian=ideal_hamiltonian,
        total_hamiltonian=hamiltonian,
        solver=_solver,
        quantum_device=None,
        whitebox=whitebox,
    )

inspeqtor.data.library.generate_single_qubit_experimental_data

generate_single_qubit_experimental_data(
    key: ndarray,
    hamiltonian: Callable[..., ndarray],
    sample_size: int = 10,
    shots: int = 1000,
    strategy: SimulationStrategy = SHOT,
    qubit_inforamtion: QubitInformation = get_mock_qubit_information(),
    control_sequence: ControlSequence = get_drag_pulse_v2_sequence(
        drive_strength
    ),
    max_steps: int = int(2**16),
    method: WhiteboxStrategy = ODE,
    trotter_steps: int = 1000,
    expectation_value_receipt: list[
        ExpectationValue
    ] = get_complete_expectation_values(1),
) -> tuple[
    ExperimentalData,
    ControlSequence,
    ndarray,
    Callable[[ndarray], ndarray],
]

Generate simulated dataset

Parameters:

Name Type Description Default
key ndarray

Random key

required
hamiltonian Callable[..., ndarray]

Total Hamiltonian of the device

required
sample_size int

Sample size of the control parameters. Defaults to 10.

10
shots int

Number of shots used to estimate expectation value, will be used if SimulationStrategy is SHOT, otherwise ignored. Defaults to 1000.

1000
strategy SimulationStrategy

Simulation strategy. Defaults to SimulationStrategy.RANDOM.

SHOT
get_qubit_information_fn Callable[[], QubitInformation]

Function that return qubit information. Defaults to get_mock_qubit_information.

required
get_control_sequence_fn Callable[[], ControlSequence]

Function that return control sequence. Defaults to get_multi_drag_control_sequence_v3.

required
max_steps int

Maximum step of solver. Defaults to int(2**16).

int(2 ** 16)
method WhiteboxStrategy

Unitary solver method. Defaults to WhiteboxStrategy.ODE.

ODE
trotter_steps int

Trotterization step. Defualts to 1000

1000

Raises:

Type Description
NotImplementedError

Not support strategy

Returns:

Type Description
tuple[ExperimentalData, ControlSequence, ndarray, Callable[[ndarray], ndarray]]

tuple[ExperimentData, ControlSequence, jnp.ndarray, typing.Callable[[jnp.ndarray], jnp.ndarray]]: tuple of (1) Experiment data, (2) Pulse sequence, (3) Noisy unitary, (4) Noisy solver

Source code in src/inspeqtor/v2/predefined.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
def generate_single_qubit_experimental_data(
    key: jnp.ndarray,
    hamiltonian: typing.Callable[..., jnp.ndarray],
    sample_size: int = 10,
    shots: int = 1000,
    strategy: SimulationStrategy = SimulationStrategy.SHOT,
    qubit_inforamtion: QubitInformation = get_mock_qubit_information(),
    control_sequence: ControlSequence = get_drag_pulse_v2_sequence(
        get_mock_qubit_information().drive_strength
    ),
    max_steps: int = int(2**16),
    method: WhiteboxStrategy = WhiteboxStrategy.ODE,
    trotter_steps: int = 1000,
    expectation_value_receipt: list[ExpectationValue] = get_complete_expectation_values(
        1
    ),
) -> tuple[
    ExperimentalData,
    ControlSequence,
    jnp.ndarray,
    typing.Callable[[jnp.ndarray], jnp.ndarray],
]:
    """Generate simulated dataset

    Args:
        key (jnp.ndarray): Random key
        hamiltonian (typing.Callable[..., jnp.ndarray]): Total Hamiltonian of the device
        sample_size (int, optional): Sample size of the control parameters. Defaults to 10.
        shots (int, optional): Number of shots used to estimate expectation value, will be used if `SimulationStrategy` is `SHOT`, otherwise ignored. Defaults to 1000.
        strategy (SimulationStrategy, optional): Simulation strategy. Defaults to SimulationStrategy.RANDOM.
        get_qubit_information_fn (typing.Callable[ [], QubitInformation ], optional): Function that return qubit information. Defaults to get_mock_qubit_information.
        get_control_sequence_fn (typing.Callable[ [], ControlSequence ], optional): Function that return control sequence. Defaults to get_multi_drag_control_sequence_v3.
        max_steps (int, optional): Maximum step of solver. Defaults to int(2**16).
        method (WhiteboxStrategy, optional): Unitary solver method. Defaults to WhiteboxStrategy.ODE.
        trotter_steps (int): Trotterization step. Defualts to 1000

    Raises:
        NotImplementedError: Not support strategy

    Returns:
        tuple[ExperimentData, ControlSequence, jnp.ndarray, typing.Callable[[jnp.ndarray], jnp.ndarray]]: tuple of (1) Experiment data, (2) Pulse sequence, (3) Noisy unitary, (4) Noisy solver
    """
    experiment_config = ExperimentConfiguration(
        qubits=[qubit_inforamtion],
        expectation_values_order=get_complete_expectation_values(1),
        parameter_structure=control_sequence.get_structure(),
        backend_name="stardust",
        sample_size=sample_size,
        shots=shots,
        EXPERIMENT_IDENTIFIER="0001",
        EXPERIMENT_TAGS=["test", "test2"],
        description="This is a test experiment",
        device_cycle_time_ns=2 / 9,
        sequence_duration_dt=control_sequence.total_dt,
    )

    # Generate mock expectation value
    key, exp_key = jax.random.split(key)

    dt = experiment_config.device_cycle_time_ns

    if method == WhiteboxStrategy.TROTTER:
        noisy_simulator = jax.jit(
            make_trotterization_solver(
                hamiltonian=hamiltonian,
                total_dt=control_sequence.total_dt,
                dt=dt,
                trotter_steps=trotter_steps,
                y0=jnp.eye(2, dtype=jnp.complex128),
            )
        )
    else:
        t_eval = jnp.linspace(
            0, control_sequence.total_dt * dt, control_sequence.total_dt
        )
        noisy_simulator = jax.jit(
            partial(
                solver,
                t_eval=t_eval,
                hamiltonian=hamiltonian,
                y0=jnp.eye(2, dtype=jnp.complex64),
                t0=0,
                t1=control_sequence.total_dt * dt,
                max_steps=max_steps,
            )
        )

    key, sample_key = jax.random.split(key)

    ravel_fn, _ = ravel_unravel_fn(control_sequence.get_structure())
    # Sample the parameter by vectorization.
    params_dict = jax.vmap(control_sequence.sample_params)(
        jax.random.split(sample_key, experiment_config.sample_size)
    )
    # Prepare parameter in single line
    control_params = jax.vmap(ravel_fn)(params_dict)

    unitaries = jax.vmap(noisy_simulator)(control_params)
    SHOTS = experiment_config.shots

    # Calculate the expectation values depending on the strategy
    unitaries_f = jnp.asarray(unitaries)[:, -1, :, :]

    assert unitaries_f.shape == (
        sample_size,
        2,
        2,
    ), f"Final unitaries shape is {unitaries_f.shape}"

    if strategy == SimulationStrategy.RANDOM:
        # Just random expectation values with key
        expectation_values = 2 * (
            jax.random.uniform(exp_key, shape=(experiment_config.sample_size, 18))
            - (1 / 2)
        )
    elif strategy == SimulationStrategy.IDEAL:
        expectation_values = calculate_expectation_values(unitaries_f)

    elif strategy == SimulationStrategy.SHOT:
        key, sample_key = jax.random.split(key)
        # The `shot_quantum_device` function will re-calculate the unitary
        expectation_values = single_qubit_shot_quantum_device(
            sample_key,
            control_params,
            noisy_simulator,
            SHOTS,
            expectation_value_receipt,
        )
    else:
        raise NotImplementedError

    assert expectation_values.shape == (
        sample_size,
        18,
    ), f"Expectation values shape is {expectation_values.shape}"

    param_df = pl.DataFrame(
        jax.tree.map(lambda x: np.array(x), flatten_dict(params_dict, sep="/"))
    ).with_row_index("parameter_id")

    obs_df = pl.DataFrame(
        jax.tree.map(
            lambda x: np.array(x),
            flatten_dict(
                dictorization(
                    expectation_values.T, order=get_complete_expectation_values(1)
                ),
                sep="/",
            ),
        )
    ).with_row_index("parameter_id")

    exp_data = ExperimentalData(experiment_config, param_df, obs_df)

    return (
        exp_data,
        control_sequence,
        jnp.array(unitaries),
        noisy_simulator,
    )

inspeqtor.data.library.get_mock_qubit_information

get_mock_qubit_information() -> QubitInformation
Source code in src/inspeqtor/v1/predefined.py
544
545
546
547
548
549
550
551
def get_mock_qubit_information() -> QubitInformation:
    return QubitInformation(
        unit="GHz",
        qubit_idx=0,
        anharmonicity=-0.2,
        frequency=5.0,
        drive_strength=0.1,
    )