v1 API
BOED
src.inspeqtor.v1.boed
AuxEntry
The auxillary entry returned by loss function
Source code in src/inspeqtor/v1/boed.py
107 108 109 110 111 | |
safe_shape
safe_shape(a: Any) -> tuple[int, ...] | str
Safely get the shape of the object
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Any
|
Expect the object to be jnp.ndarray |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, ...] | str
|
tuple[int, ...] | str: Either return the shape of |
tuple[int, ...] | str
|
or string representation of the type |
Source code in src/inspeqtor/v1/boed.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
report_shape
report_shape(a: PyTree) -> PyTree
Report the shape of pytree
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
PyTree
|
The pytree to be report. |
required |
Returns:
| Type | Description |
|---|---|
PyTree
|
jaxtyping.PyTree: The shape of pytree. |
Source code in src/inspeqtor/v1/boed.py
31 32 33 34 35 36 37 38 39 40 | |
lexpand
lexpand(a: ndarray, *dimensions: int) -> ndarray
Expand tensor, adding new dimensions on left.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ndarray
|
expand the dimension on the left with given dimension arguments. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: New array with shape (*dimension + a.shape) |
Source code in src/inspeqtor/v1/boed.py
43 44 45 46 47 48 49 50 51 52 | |
random_split_index
random_split_index(
rng_key: ndarray, num_samples: int, test_size: int
) -> tuple[ndarray, ndarray]
Create the randomly spilt of indice to two set, with one of test_size and another as the rest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng_key
|
ndarray
|
The random key |
required |
num_samples
|
int
|
The size of total sample size |
required |
test_size
|
int
|
The size of test set |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
tuple[jnp.ndarray, jnp.ndarray]: Array of train indice and array of test indice. |
Source code in src/inspeqtor/v1/boed.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | |
marginal_loss
marginal_loss(
model: Callable,
marginal_guide: Callable,
design: ndarray,
*args,
observation_labels: list[str],
target_labels: list[str],
num_particles: int,
evaluation: bool = False,
) -> Callable[
[ArrayTree, ndarray], tuple[ndarray, AuxEntry]
]
The marginal loss implemented following https://docs.pyro.ai/en/dev/contrib.oed.html#pyro.contrib.oed.eig.marginal_eig
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Callable
|
The probabilistic model |
required |
marginal_guide
|
Callable
|
The custom guide |
required |
design
|
ndarray
|
Possible designs of the experiment |
required |
observation_labels
|
list[str]
|
The list of string of observations |
required |
target_labels
|
list[str]
|
The target latent parameters to be optimized for |
required |
num_particles
|
int
|
The number of independent trials |
required |
evaluation
|
bool
|
True for actual evalution of the EIG. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[ArrayTree, ndarray], tuple[ndarray, AuxEntry]]
|
typing.Callable[ [chex.ArrayTree, jnp.ndarray], tuple[jnp.ndarray, AuxEntry] ]: Loss function that return tuple of (1) Total loss, (2.1) Each terms without the average, (2.2) The EIG |
Source code in src/inspeqtor/v1/boed.py
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 | |
vnmc_eig_loss
vnmc_eig_loss(
model: Callable,
marginal_guide: Callable,
design: ndarray,
*args,
observation_labels: list[str],
target_labels: list[str],
num_particles: tuple[int, int],
evaluation: bool = False,
) -> Callable[
[ArrayTree, ndarray], tuple[ndarray, AuxEntry]
]
The VNMC loss implemented following https://docs.pyro.ai/en/dev/_modules/pyro/contrib/oed/eig.html#vnmc_eig
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Callable
|
The probabilistic model |
required |
marginal_guide
|
Callable
|
The custom guide |
required |
design
|
ndarray
|
Possible designs of the experiment |
required |
observation_labels
|
list[str]
|
The list of string of observations |
required |
target_labels
|
list[str]
|
The target latent parameters to be optimized for |
required |
num_particles
|
int
|
The number of independent trials |
required |
evaluation
|
bool
|
True for actual evalution of the EIG. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[ArrayTree, ndarray], tuple[ndarray, AuxEntry]]
|
typing.Callable[ [chex.ArrayTree, jnp.ndarray], tuple[jnp.ndarray, AuxEntry] ]: Loss function that return tuple of (1) Total loss, (2.1) Each terms without the average, (2.2) The EIG |
Source code in src/inspeqtor/v1/boed.py
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 | |
init_params_from_guide
init_params_from_guide(
marginal_guide: Callable,
*args,
key: ndarray,
design: ndarray,
) -> ArrayTree
Initlalize parameters of marginal guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
marginal_guide
|
Callable
|
Marginal guide to be used with marginal eig |
required |
key
|
ndarray
|
Random Key |
required |
design
|
ndarray
|
Example of the designs of the experiment |
required |
Returns:
| Type | Description |
|---|---|
ArrayTree
|
chex.ArrayTree: Random parameters for marginal guide to be optimized. |
Source code in src/inspeqtor/v1/boed.py
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 | |
opt_eig_ape_loss
opt_eig_ape_loss(
loss_fn: Callable[
[ArrayTree, ndarray], tuple[ndarray, AuxEntry]
],
params: ArrayTree,
num_steps: int,
optim: GradientTransformation,
key: ndarray,
callbacks: list = [],
) -> ArrayTree
Optimize the EIG loss function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_fn
|
Callable[[ArrayTree, ndarray], tuple[ndarray, AuxEntry]]
|
Loss function |
required |
params
|
ArrayTree
|
Initial parameter |
required |
num_steps
|
int
|
Number of optimization step |
required |
optim
|
GradientTransformation
|
Optax Optimizer |
required |
key
|
ndarray
|
Random key |
required |
Returns:
| Type | Description |
|---|---|
ArrayTree
|
tuple[chex.ArrayTree, list[typing.Any]]: Optimized parameters, and optimization history. |
Source code in src/inspeqtor/v1/boed.py
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 | |
estimate_eig
estimate_eig(
key: ndarray,
model: Callable,
marginal_guide: Callable,
design: ndarray,
*args,
optimizer: GradientTransformation,
num_optimization_steps: int,
observation_labels: list[str],
target_labels: list[str],
num_particles: tuple[int, int] | int,
final_num_particles: tuple[int, int]
| int
| None = None,
loss_fn: Callable = marginal_loss,
callbacks: list = [],
) -> tuple[ndarray, dict[str, Any]]
Optimize for marginal EIG
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
Random key |
required |
model
|
Callable
|
Probabilistic model of the experiment |
required |
marginal_guide
|
Callable
|
The marginal guide of the experiment |
required |
design
|
ndarray
|
Possible designs of the experiment |
required |
optimizer
|
GradientTransformation
|
Optax optimizer |
required |
num_optimization_steps
|
int
|
Number of the optimization step |
required |
observation_labels
|
list[str]
|
The list of string of observations |
required |
target_labels
|
list[str]
|
The target latent parameters to be optimized for |
required |
num_particles
|
int
|
The number of independent trials |
required |
final_num_particles
|
int | None
|
Final independent trials to calculate marginal EIG. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, dict[str, Any]]
|
tuple[jnp.ndarray, dict[str, typing.Any]]: EIG, and tuple of optimized parameters and optimization history. |
Source code in src/inspeqtor/v1/boed.py
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 | |
vectorized_for_eig
vectorized_for_eig(model)
Vectorization function for the EIG function
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Probabilistic model. |
required |
Source code in src/inspeqtor/v1/boed.py
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
Constant
src.inspeqtor.v1.constant
Control
src.inspeqtor.v1.control
BaseControl
dataclass
Source code in src/inspeqtor/v1/control.py
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 | |
to_dict
to_dict() -> dict[str, Union[int, float, str]]
Convert the control configuration to dictionary
Returns:
| Type | Description |
|---|---|
dict[str, Union[int, float, str]]
|
dict[str, typing.Union[int, float, str]]: Configuration of the control |
Source code in src/inspeqtor/v1/control.py
90 91 92 93 94 95 96 | |
from_dict
classmethod
from_dict(data)
Construct the control instace from the dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary for construction of the control instance. |
required |
Returns:
| Type | Description |
|---|---|
|
The instance of the control. |
Source code in src/inspeqtor/v1/control.py
98 99 100 101 102 103 104 105 106 107 108 | |
ControlSequenceProtocol
Protocol defining the interface for control sequences.
Source code in src/inspeqtor/v1/control.py
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 | |
get_structure
get_structure() -> list[tuple[str, str]]
Get the structure/order of control parameters.
Source code in src/inspeqtor/v1/control.py
118 119 120 | |
sample_params
sample_params(key: Array) -> dict[str, ParametersDictType]
Sample control parameters using a random key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Random key for sampling |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ParametersDictType]
|
Dictionary of sampled control parameters |
Source code in src/inspeqtor/v1/control.py
122 123 124 125 126 127 128 129 130 131 | |
get_bounds
get_bounds() -> tuple[
dict[str, ParametersDictType],
dict[str, ParametersDictType],
]
Get the bounds of the controls.
Returns:
| Type | Description |
|---|---|
tuple[dict[str, ParametersDictType], dict[str, ParametersDictType]]
|
Tuple of lower and upper bounds dictionaries |
Source code in src/inspeqtor/v1/control.py
133 134 135 136 137 138 139 140 141 | |
get_envelope
get_envelope(
params_dict: dict[str, ParametersDictType],
) -> Callable
Create envelope function with given control parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params_dict
|
dict[str, ParametersDictType]
|
Control parameters to be used |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
Envelope function |
Source code in src/inspeqtor/v1/control.py
143 144 145 146 147 148 149 150 151 152 153 154 | |
to_dict
to_dict() -> dict[str, str | dict[str, str | float]]
Convert the control sequence to a dictionary representation.
Source code in src/inspeqtor/v1/control.py
156 157 158 | |
from_dict
classmethod
from_dict(
data: dict[str, str | dict[str, str | float]],
controls: dict[str, type[BaseControl]],
) -> Self
Create a control sequence from dictionary data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, str | dict[str, str | float]]
|
Dictionary containing control sequence data |
required |
controls
|
dict[str, type[BaseControl]]
|
Dictionary mapping control names to control classes |
required |
Returns:
| Type | Description |
|---|---|
Self
|
New control sequence instance |
Source code in src/inspeqtor/v1/control.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
to_file
to_file(path: str | Path) -> None
Save configuration to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to save the sequence configuration |
required |
Source code in src/inspeqtor/v1/control.py
177 178 179 180 181 182 183 | |
from_file
classmethod
from_file(
path: str | Path, controls: dict[str, type[BaseControl]]
) -> Self
Load control sequence from file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to load the sequence configuration from |
required |
controls
|
dict[str, type[BaseControl]]
|
Dictionary mapping control names to control classes |
required |
Returns:
| Type | Description |
|---|---|
Self
|
New control sequence instance |
Source code in src/inspeqtor/v1/control.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | |
ControlSequence
dataclass
Control sequence, expect to be sum of atomic control.
Source code in src/inspeqtor/v1/control.py
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 | |
sample_params
sample_params(key: Array) -> list[ParametersDictType]
Sample control parameter
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
Random key |
required |
Returns:
| Type | Description |
|---|---|
list[ParametersDictType]
|
list[ParametersDictType]: control parameters |
Source code in src/inspeqtor/v1/control.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
get_envelope
get_envelope(
params_list: list[ParametersDictType],
) -> Callable
Create envelope function with given control parameters
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params_list
|
list[ParametersDictType]
|
control parameter to be used |
required |
Returns:
| Type | Description |
|---|---|
Callable
|
typing.Callable: Envelope function |
Source code in src/inspeqtor/v1/control.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
get_bounds
get_bounds() -> tuple[
list[ParametersDictType], list[ParametersDictType]
]
Get the bounds of the controls
Returns:
| Type | Description |
|---|---|
tuple[list[ParametersDictType], list[ParametersDictType]]
|
tuple[list[ParametersDictType], list[ParametersDictType]]: tuple of list of lower and upper bounds. |
Source code in src/inspeqtor/v1/control.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
get_parameter_names
get_parameter_names() -> list[list[str]]
Get the name of the control parameters in the control sequence.
Returns:
| Type | Description |
|---|---|
list[list[str]]
|
list[list[str]]: Structured name of control parameters. |
Source code in src/inspeqtor/v1/control.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
to_dict
to_dict() -> dict[str, Any]
Convert control sequence to dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, typing.Any]: Control sequence configuration dict. |
Source code in src/inspeqtor/v1/control.py
335 336 337 338 339 340 341 342 343 344 345 346 347 | |
from_dict
classmethod
from_dict(
data: dict[str, Any],
controls: Sequence[type[BaseControl]],
) -> ControlSequence
Construct the control sequence from dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict contain information for sequence construction |
required |
control
|
Sequence[type[BasePulse]]
|
Constructor of the controls |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ControlSequence |
ControlSequence
|
Instance of the control sequence. |
Source code in src/inspeqtor/v1/control.py
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 | |
to_file
to_file(path: Union[str, Path])
Save configuration of the pulse to file given folder path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to the folder to save sequence, will be created if not existed. |
required |
Source code in src/inspeqtor/v1/control.py
375 376 377 378 379 380 381 382 383 384 385 386 | |
from_file
classmethod
from_file(
path: Union[str, Path],
controls: Sequence[type[BaseControl]],
) -> ControlSequence
Construct control seqence from path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to configuration of control sequence. |
required |
controls
|
Sequence[type[BasePulse]]
|
Constructor of the control in the sequence. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ControlSequence |
ControlSequence
|
Control sequence instance. |
Source code in src/inspeqtor/v1/control.py
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
sample_params
sample_params(
key: ndarray,
lower: ParametersDictType,
upper: ParametersDictType,
) -> ParametersDictType
Sample parameters with the same shape with given lower and upper bounds
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
Random key |
required |
lower
|
ParametersDictType
|
Lower bound |
required |
upper
|
ParametersDictType
|
Upper bound |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ParametersDictType |
ParametersDictType
|
Dict of the sampled parameters |
Source code in src/inspeqtor/v1/control.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 | |
array_to_list_of_params
array_to_list_of_params(
array: ndarray, parameter_structure: list[list[str]]
) -> list[ParametersDictType]
Convert the array of control parameter to the list form
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
ndarray
|
Control parameter array |
required |
parameter_structure
|
list[list[str]]
|
The structure of the control sequence |
required |
Returns:
| Type | Description |
|---|---|
list[ParametersDictType]
|
list[ParametersDictType]: Control parameter in the list form. |
Source code in src/inspeqtor/v1/control.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
list_of_params_to_array
list_of_params_to_array(
params: list[ParametersDictType],
parameter_structure: list[list[str]],
) -> ndarray
Convert the control parameter in the list form to flatten array form
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
list[ParametersDictType]
|
Control parameter in the list form |
required |
parameter_structure
|
list[list[str]]
|
The structure of the control sequence |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Control parameters array |
Source code in src/inspeqtor/v1/control.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 | |
get_param_array_converter
get_param_array_converter(
control_sequence: ControlSequence,
)
This function returns two functions that can convert between a list of parameter dictionaries and a flat array.
array_to_list_of_params_fn, list_of_params_to_array_fn = get_param_array_converter(control_sequence)
Args:
control_sequence (ControlSequence): The pulse sequence object.
Returns:
| Type | Description |
|---|---|
|
typing.Any: A tuple containing two functions. The first function converts an array to a list of parameter dictionaries, and the second function converts a list of parameter dictionaries to an array. |
Source code in src/inspeqtor/v1/control.py
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
construct_control_sequence_reader
construct_control_sequence_reader(
controls: list[type[BaseControl]] = [],
) -> Callable[[Union[str, Path]], ControlSequence]
Construct the control sequence reader
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
controls
|
list[type[BasePulse]]
|
List of control constructor. Defaults to []. |
[]
|
Returns:
| Type | Description |
|---|---|
Callable[[Union[str, Path]], ControlSequence]
|
typing.Callable[[typing.Union[str, pathlib.Path]], controlsequence]: Control sequence reader that will automatically contruct control sequence from path. |
Source code in src/inspeqtor/v1/control.py
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 | |
get_envelope_transformer
get_envelope_transformer(control_sequence: ControlSequence)
Generate get_envelope function with control parameter array as an input instead of list form
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
control_sequence
|
ControlSequence
|
Control seqence instance |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Callable[[jnp.ndarray], typing.Any]: Transformed get envelope function |
Source code in src/inspeqtor/v1/control.py
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | |
Data
src.inspeqtor.v1.data
Operator
dataclass
Dataclass for accessing qubit operators. Support X, Y, Z, Hadamard, S, Sdg, and I gate.
Raises:
| Type | Description |
|---|---|
ValueError
|
Provided operator is not supperted |
Source code in src/inspeqtor/v1/data.py
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 | |
from_label
classmethod
from_label(op: str) -> ndarray
Initialize the operator from the label
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
str
|
The label of the operator |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Operator not supported |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The operator |
Source code in src/inspeqtor/v1/data.py
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 | |
to_qutrit
classmethod
to_qutrit(op: ndarray, value: float = 1.0) -> ndarray
Add extra dimension to the operator
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
ndarray
|
Qubit operator |
required |
value
|
float
|
Value to be add at the extra dimension diagonal entry. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: New operator for qutrit space. |
Source code in src/inspeqtor/v1/data.py
88 89 90 91 92 93 94 95 96 97 98 99 | |
State
dataclass
Dataclass for accessing eigenvector corresponded to eigenvalue of Pauli operator X, Y, and Z.
Raises:
| Type | Description |
|---|---|
ValueError
|
Provided state is not supported |
ValueError
|
Provided state is not qubit |
Source code in src/inspeqtor/v1/data.py
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 | |
from_label
classmethod
from_label(state: str, dm: bool = False) -> ndarray
Initialize the state from the label
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
str
|
The label of the state |
required |
dm
|
bool
|
Initialized as statevector or density matrix. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
State not supported |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The state |
Source code in src/inspeqtor/v1/data.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 145 146 147 148 149 150 | |
to_qutrit
classmethod
to_qutrit(state: ndarray) -> ndarray
Promote qubit state to qutrit with zero probability
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
ndarray
|
Density matrix of 2 x 2 qubit state. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Provided state is not qubit |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Qutrit density matrix |
Source code in src/inspeqtor/v1/data.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
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 | |
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 | |
ExpectationValue
dataclass
Dataclass to store expectation value information
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state
|
str
|
String representation of inital state. Currently support "+", "-", "r", "l", "0", "1". |
required |
observable
|
str
|
String representation of quantum observable. Currently support "X", "Y", "Z". |
required |
expectation_value
|
None | float
|
the expectation value. Default to None |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Not support initial state |
ValueError
|
Not support observable |
ValueError
|
Not support initial state |
ValueError
|
Not support observable |
Source code in src/inspeqtor/v1/data.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 | |
ExperimentConfiguration
dataclass
Experiment configuration dataclass
Source code in src/inspeqtor/v1/data.py
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 | |
ExperimentData
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
experiment_config
|
ExperimentConfiguration
|
Experiment configuration |
required |
preprocess_data
|
DataFrame
|
Pandas dataframe containing the preprocess dataset |
required |
_postprocessed_data
|
DataFrame | None
|
(pd.DataFrame): Provide this optional argument to skip dataset postprocessing. |
None
|
keep_decimal
|
int
|
the precision of floating point to keep. |
10
|
Source code in src/inspeqtor/v1/data.py
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 | |
validate_preprocess_data
validate_preprocess_data()
Validate that the preprocess_data have all the required columns.
Required columns
- EXPECTATION_VALUE
- INITIAL_STATE
- OBSERVABLE
- PARAMETERS_ID
Source code in src/inspeqtor/v1/data.py
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | |
validate_postprocess_data
validate_postprocess_data(post_data: DataFrame)
Validate postprocess dataset, by check the requirements given by PredefinedCol instance of each column
that required in the postprocessed dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
post_data
|
DataFrame
|
Postprocessed dataset to be validated. |
required |
Source code in src/inspeqtor/v1/data.py
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 | |
transform_preprocess_data_to_postprocess_data
transform_preprocess_data_to_postprocess_data() -> (
DataFrame
)
Internal method to post process the dataset.
Todo
Use new experimental implementation from_long to wide dataframe
Raises:
| Type | Description |
|---|---|
ValueError
|
There is duplicate entry of the expectation value. |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Postprocessed experiment dataset. |
Source code in src/inspeqtor/v1/data.py
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 | |
get_parameters_dataframe
get_parameters_dataframe() -> DataFrame
Get dataframe with only the columns of control parameters.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Dataframe with only the columns of control parameters. |
Source code in src/inspeqtor/v1/data.py
709 710 711 712 713 714 715 | |
get_expectation_values
get_expectation_values() -> ndarray
Get the expectation value of the shape (sample_size, num_expectation_value)
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: expectation value of the shape (sample_size, num_expectation_value) |
Source code in src/inspeqtor/v1/data.py
717 718 719 720 721 722 723 724 725 726 727 728 729 730 | |
get_parameters_dict_list
get_parameters_dict_list() -> list[
list[ParametersDictType]
]
Get the list, where each element is list of dict of the control parameters of the dataset.
Returns:
| Type | Description |
|---|---|
list[list[ParametersDictType]]
|
list[list[ParametersDictType]]: The list of list of dict of parameter. |
Source code in src/inspeqtor/v1/data.py
732 733 734 735 736 737 738 739 740 741 742 743 744 745 | |
save_to_folder
save_to_folder(path: Union[Path, str])
Save the experiment data to given folder
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[Path, str]
|
Path of the folder for experiment data to be saved. |
required |
Source code in src/inspeqtor/v1/data.py
747 748 749 750 751 752 753 754 755 756 757 758 759 760 | |
from_folder
classmethod
from_folder(path: Union[Path, str]) -> ExperimentData
Read the experiment data from path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[Path, str]
|
path to the folder contain experiment data. Expected to be used with |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ExperimentData |
ExperimentData
|
Intance of |
Source code in src/inspeqtor/v1/data.py
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 | |
add_hilbert_level
add_hilbert_level(op: ndarray, x: ndarray) -> ndarray
Add a level to the operator or state
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
ndarray
|
The qubit operator or state |
required |
is_state
|
bool
|
True if the operator is a state, False if the operator is an operator |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The qutrit operator or state |
Source code in src/inspeqtor/v1/data.py
25 26 27 28 29 30 31 32 33 34 35 | |
flatten_parameter_name_with_prefix
flatten_parameter_name_with_prefix(
parameter_names: Sequence[Sequence[str]],
) -> list[str]
Create a flatten list of parameter names with prefix parameter/{i}/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter_names
|
Sequence[Sequence[str]]
|
The list of parameter names from the pulse sequence or the experiment configuration |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The flatten list of parameter names with prefix parameter/{i}/ |
Source code in src/inspeqtor/v1/data.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | |
transform_parameter_name
transform_parameter_name(name: str) -> str
Remove "parameter/{i}/" from provided name
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the control parameters |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Name that have "parameter/{i}/" strip. |
Source code in src/inspeqtor/v1/data.py
454 455 456 457 458 459 460 461 462 463 464 465 466 | |
get_parameters_dict_list
get_parameters_dict_list(
parameters_name: Sequence[Sequence[str]],
parameters_row: Series,
) -> list[ParametersDictType]
Get the list of dict containing name and value of each control in the sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters_name
|
Sequence[Sequence[str]]
|
description |
required |
parameters_row
|
Series
|
description |
required |
Returns:
| Type | Description |
|---|---|
list[ParametersDictType]
|
list[ParametersDictType]: description |
Source code in src/inspeqtor/v1/data.py
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 | |
save_to_json
save_to_json(data: dict, path: Union[str, Path])
Save the dictionary as json to the path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dict to be save to file |
required |
path
|
Union[str, Path]
|
Path to save file. |
required |
Source code in src/inspeqtor/v1/data.py
817 818 819 820 821 822 823 824 825 826 827 828 829 | |
read_from_json
read_from_json(
path: Union[str, Path],
dataclass: Union[None, type[DataclassVar]] = None,
) -> Union[dict, DataclassVar]
Construct provided dataclass instance with json file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to json file |
required |
dataclass
|
Union[None, type[DataclassVar]]
|
The constructor of the dataclass. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Union[dict, DataclassVar]
|
typing.Union[dict, DataclassVar]: Dataclass instance, if dataclass is not provideded, return dict instead. |
Source code in src/inspeqtor/v1/data.py
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 | |
load_pytree_from_json
load_pytree_from_json(
path: str | Path, parse_fn=default_parse_fn
)
Load pytree from json
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to JSON file containing pytree |
required |
array_keys
|
list[str]
|
list of key to convert to jnp.numpy. Defaults to []. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Provided path is not point to .json file |
Returns:
| Type | Description |
|---|---|
|
typing.Any: Pytree loaded from JSON |
Source code in src/inspeqtor/v1/data.py
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 | |
save_pytree_to_json
save_pytree_to_json(pytree, path: str | Path)
Save given pytree to json file, the path must end with extension of .json
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pytree
|
Any
|
The pytree to save |
required |
path
|
str | Path
|
File path to save |
required |
Source code in src/inspeqtor/v1/data.py
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 | |
from_long_to_wide
from_long_to_wide(preprocessed_df: DataFrame)
An experimental function to transform preprocess dataframe to postprocess dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
preprocessed_df
|
DataFrame
|
The preprocess dataframe |
required |
Returns:
| Type | Description |
|---|---|
|
pd.DataFrame: The postprocessed dataframe |
Source code in src/inspeqtor/v1/data.py
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 | |
from_wide_to_long_simple
from_wide_to_long_simple(wide_df: DataFrame)
A more concise version to convert a wide DataFrame back to the long format.
Source code in src/inspeqtor/v1/data.py
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 | |
Linen
src.inspeqtor.v1.models.linen
loss_fn
loss_fn(
params: VariableDict,
control_parameters: ndarray,
unitaries: ndarray,
expectation_values: ndarray,
model: Module,
predictive_fn: Callable,
loss_metric: LossMetric,
calculate_metric_fn: Callable = calculate_metric,
**model_kwargs,
) -> tuple[ndarray, dict[str, ndarray]]
This function implement a unified interface for nn.Module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
VariableDict
|
Model parameters to be optimized |
required |
control_parameters
|
ndarray
|
Control parameters parametrized Hamiltonian |
required |
unitaries
|
ndarray
|
The Ideal unitary operators corresponding to the control parameters |
required |
expectation_values
|
ndarray
|
Experimental expectation values to calculate the loss value |
required |
model
|
Module
|
Flax linen Blackbox part of the graybox model. |
required |
predictive_fn
|
Callable
|
Function for calculating expectation value from the model |
required |
loss_metric
|
LossMetric
|
The choice of loss value to be minimized. |
required |
calculate_metric_fn
|
Callable
|
Function for metrics calculation from prediction and experimental value. Defaults to calculate_metric |
calculate_metric
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, dict[str, ndarray]]
|
tuple[jnp.ndarray, dict[str, jnp.ndarray]]: The loss value and other metrics. |
Source code in src/inspeqtor/v1/models/linen.py
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 | |
wo_predictive_fn
wo_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: Module,
model_params: VariableDict,
**model_kwargs,
)
To Calculate the metrics of the model 1. MSE Loss between the predicted expectation values and the experimental expectation values 2. Average Gate Fidelity between the Pauli matrices to the Wo_model matrices 3. AGF Loss between the prediction from model and the experimental expectation values
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The model to be used for prediction |
required |
model_params
|
VariableDict
|
The model parameters |
required |
control_parameters
|
ndarray
|
The pulse parameters |
required |
unitaries
|
ndarray
|
Ideal unitaries |
required |
expectation_values
|
ndarray
|
Experimental expectation values |
required |
model_kwargs
|
dict
|
Model keyword arguments |
{}
|
Source code in src/inspeqtor/v1/models/linen.py
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 | |
noisy_unitary_predictive_fn
noisy_unitary_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: UnitaryModel,
model_params: VariableDict,
**model_kwargs,
)
Caculate for unitary-based Blackbox model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The model to be used for prediction |
required |
model_params
|
VariableDict
|
The model parameters |
required |
control_parameters
|
ndarray
|
The pulse parameters |
required |
unitaries
|
ndarray
|
Ideal unitaries |
required |
expectation_values
|
ndarray
|
Experimental expectation values |
required |
model_kwargs
|
dict
|
Model keyword arguments |
{}
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/models/linen.py
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 | |
toggling_unitary_predictive_fn
toggling_unitary_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: UnitaryModel,
model_params: VariableDict,
ignore_spam: bool = False,
**model_kwargs,
)
Calcuate for unitary-based Blackbox model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The model to be used for prediction |
required |
model_params
|
VariableDict
|
The model parameters |
required |
control_parameters
|
ndarray
|
The pulse parameters |
required |
unitaries
|
ndarray
|
Ideal unitaries |
required |
expectation_values
|
ndarray
|
Experimental expectation values |
required |
model_kwargs
|
dict
|
Model keyword arguments |
{}
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/models/linen.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
make_loss_fn_old
make_loss_fn_old(
predictive_fn: Callable,
model: Module,
calculate_metric_fn: Callable = calculate_metric,
loss_metric: LossMetric = MSEE,
)
summary
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Callable
|
Function for calculating expectation value from the model |
required |
model
|
Module
|
Flax linen Blackbox part of the graybox model. |
required |
loss_metric
|
LossMetric
|
The choice of loss value to be minimized. Defaults to LossMetric.MSEE. |
MSEE
|
calculate_metric_fn
|
Callable
|
Function for metrics calculation from prediction and experimental value. Defaults to calculate_metric. |
calculate_metric
|
Source code in src/inspeqtor/v1/models/linen.py
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 | |
make_loss_fn_oldv2
make_loss_fn_oldv2(
adapter_fn: Callable,
model: Module,
calculate_metric_fn: Callable = calculate_metric,
loss_metric: LossMetric = MSEE,
)
summary
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Callable
|
Function for calculating expectation value from the model |
required |
model
|
Module
|
Flax linen Blackbox part of the graybox model. |
required |
loss_metric
|
LossMetric
|
The choice of loss value to be minimized. Defaults to LossMetric.MSEE. |
MSEE
|
calculate_metric_fn
|
Callable
|
Function for metrics calculation from prediction and experimental value. Defaults to calculate_metric. |
calculate_metric
|
Source code in src/inspeqtor/v1/models/linen.py
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 | |
make_loss_fn
make_loss_fn(
adapter_fn: Callable,
model: Module,
evaluate_fn: Callable[
[ndarray, ndarray, ndarray], ndarray
],
)
summary
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Callable
|
Function for calculating expectation value from the model |
required |
model
|
Module
|
Flax linen Blackbox part of the graybox model. |
required |
evaluate_fn
|
Callable[[ndarray, ndarray], ndarray, ndarray]
|
Take in predicted and experimental expectation values and ideal unitary and return loss value |
required |
Source code in src/inspeqtor/v1/models/linen.py
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 | |
create_step
create_step(
optimizer: GradientTransformation,
loss_fn: Callable[..., ndarray]
| Callable[..., Tuple[ndarray, Any]],
has_aux: bool = False,
)
The create_step function creates a training step function and a test step function.
loss_fn should have the following signature:
def loss_fn(params: jaxtyping.PyTree, *args) -> jnp.ndarray:
...
return loss_value
params is the parameters to be optimized, and args are the inputs for the loss function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
GradientTransformation
|
|
required |
loss_fn
|
Callable[[PyTree, ...], ndarray]
|
Loss function, which takes in the model parameters, inputs, and targets, and returns the loss value. |
required |
has_aux
|
bool
|
Whether the loss function return aux data or not. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: train_step, test_step |
Source code in src/inspeqtor/v1/models/linen.py
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 | |
train_model
train_model(
key: ndarray,
train_data: DataBundled,
val_data: DataBundled,
test_data: DataBundled,
model: Module,
optimizer: GradientTransformation,
loss_fn: Callable,
callbacks: list[Callable] = [],
NUM_EPOCH: int = 1000,
model_params: VariableDict | None = None,
opt_state: OptState | None = None,
)
Train the BlackBox model
Examples:
>>> # The number of epochs break down
... NUM_EPOCH = 150
... # Total number of iterations as 90% of data is used for training
... # 10% of the data is used for testing
... total_iterations = 9 * NUM_EPOCH
... # The step for optimizer if set to 8 * NUM_EPOCH (should be less than total_iterations)
... step_for_optimizer = 8 * NUM_EPOCH
... optimizer = get_default_optimizer(step_for_optimizer)
... # The warmup steps for the optimizer
... warmup_steps = 0.1 * step_for_optimizer
... # The cool down steps for the optimizer
... cool_down_steps = total_iterations - step_for_optimizer
... total_iterations, step_for_optimizer, warmup_steps, cool_down_steps
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
Random key |
required |
model
|
Module
|
The model to be used for training |
required |
optimizer
|
GradientTransformation
|
The optimizer to be used for training |
required |
loss_fn
|
Callable
|
The loss function to be used for training |
required |
callbacks
|
list[Callable]
|
list of callback functions. Defaults to []. |
[]
|
NUM_EPOCH
|
int
|
The number of epochs. Defaults to 1_000. |
1000
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
The model parameters, optimizer state, and the histories |
Source code in src/inspeqtor/v1/models/linen.py
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | |
NNX
src.inspeqtor.v1.models.nnx
Blackbox
The abstract class for interfacing the Blackbox model of the Graybox
Source code in src/inspeqtor/v1/models/nnx.py
22 23 24 25 26 27 28 29 | |
WoModel
\(\hat{W}_{O}\) based blackbox model.
Source code in src/inspeqtor/v1/models/nnx.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 | |
__init__
__init__(
shared_layers: list[int],
pauli_layers: list[int],
*,
rngs: Rngs,
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shared_layers
|
list[int]
|
Each integer in the list is a size of the width of each hidden layer in the shared layers. |
required |
pauli_layers
|
list[int]
|
Each integer in the list is a size of the width of each hidden layer in the Pauli layers. |
required |
rngs
|
Rngs
|
Random number generator of |
required |
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
UnitaryModel
Unitary-based model, predicting parameters parametrized unitary operator in range \([0, 2\pi]\).
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
__init__
__init__(hidden_sizes: list[int], *, rngs: Rngs) -> None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_sizes
|
list[int]
|
Each integer in the list is a size of the width of each hidden layer in the shared layers |
required |
rngs
|
Rngs
|
Random number generator of |
required |
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
UnitarySPAMModel
Composite class of unitary-based model and the SPAM model.
Source code in src/inspeqtor/v1/models/nnx.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | |
__init__
__init__(
unitary_model: UnitaryModel, spam_params, *, rngs: Rngs
) -> None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unitary_model
|
UnitaryModel
|
Unitary-based model that have already initialized. |
required |
rngs
|
Rngs
|
Random number generator of |
required |
Source code in src/inspeqtor/v1/models/nnx.py
169 170 171 172 173 174 175 176 177 178 179 | |
wo_predictive_fn
wo_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: WoModel,
) -> ndarray
Adapter function for \(\hat{W}_{O}\) based model to be used with make_loss_fn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
WoModel
|
\(\hat{W}_{O}\) based model |
required |
data
|
DataBundled
|
A bundled of data for the predictive model training. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Predicted expectation values. |
Source code in src/inspeqtor/v1/models/nnx.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
noisy_unitary_predictive_fn
noisy_unitary_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: UnitaryModel,
) -> ndarray
Adapter function for unitary-based model to be used with make_loss_fn
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
UnitaryModel
|
Unitary-based model. |
required |
data
|
DataBundled
|
A bundled of data for the predictive model training. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Predicted expectation values. |
Source code in src/inspeqtor/v1/models/nnx.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
toggling_unitary_predictive_fn
toggling_unitary_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: UnitaryModel,
) -> ndarray
Adapter function for rotating toggling frame unitary based model to be used with make_loss_fn
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
UnitaryModel
|
Unitary-based model. |
required |
data
|
DataBundled
|
A bundled of data for the predictive model training. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Predicted expectation values. |
Source code in src/inspeqtor/v1/models/nnx.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
toggling_unitary_with_spam_predictive_fn
toggling_unitary_with_spam_predictive_fn(
control_parameters: ndarray,
unitaries: ndarray,
model: UnitarySPAMModel,
) -> ndarray
Adapter function for a composite rotating toggling
frame unitary based model to be used with make_loss_fn
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
UnitaryModel
|
Unitary-based SPAM model. |
required |
data
|
DataBundled
|
A bundled of data for the predictive model training. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Predicted expectation values. |
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
make_loss_fn_old
make_loss_fn_old(
predictive_fn,
calculate_metric_fn=calculate_metric,
loss_metric: LossMetric = MSEE,
)
A function for preparing loss function to be used for model training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Any
|
Adaptor function specifically for each model. |
required |
calculate_metric_fn
|
Any
|
Function for calculating metrics. Defaults to calculate_metric. |
calculate_metric
|
loss_metric
|
LossMetric
|
The chosen loss function to be optimized. Defaults to LossMetric.MSEE. |
MSEE
|
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
make_loss_fn_oldv2
make_loss_fn_oldv2(
adapter_fn,
calculate_metric_fn=calculate_metric,
loss_metric: LossMetric = MSEE,
)
A function for preparing loss function to be used for model training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Any
|
Adaptor function specifically for each model. |
required |
calculate_metric_fn
|
Any
|
Function for calculating metrics. Defaults to calculate_metric. |
calculate_metric
|
loss_metric
|
LossMetric
|
The chosen loss function to be optimized. Defaults to LossMetric.MSEE. |
MSEE
|
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
make_loss_fn
make_loss_fn(adapter_fn, evaluate_fn)
A function for preparing loss function to be used for model training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Any
|
Adaptor function specifically for each model. |
required |
evaluate_fn
|
Callable[[ndarray, ndarray], ndarray, ndarray]
|
Take in predicted and experimental expectation values and ideal unitary and return loss value |
required |
Source code in src/inspeqtor/v1/models/nnx.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
create_step
create_step(
loss_fn: Callable[
[Blackbox, DataBundled], tuple[ndarray, Any]
],
)
A function to create the traning and evaluating step for model. The train step will update the model parameters and optimizer parameters inplace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_fn
|
Callable[[Blackbox, DataBundled], tuple[ndarray, Any]]
|
Loss function returned from |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: The tuple of training and eval step functions. |
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
reconstruct_model
reconstruct_model(
model_params, config, Model: type[T]
) -> T
Reconstruct the model from the model parameters, config, and model initializer.
Examples:
>>> _, state = nnx.split(blackbox)
>>> model_params = nnx.to_pure_dict(state)
>>> config = {
... "shared_layers": [8],
... "pauli_layers": [8]
... }
>>> model_data = sq.model.ModelData(params=model_params, config=config)
# save and load to and from disk!
>>> blackbox = sq.models.nnx.reconstruct_model(model_data.params, model_data.config, sq.models.nnx.WoModel)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_params
|
Any
|
The pytree containing model parameters. |
required |
config
|
Any
|
The model configuration for model initialization. |
required |
Model
|
type[T]
|
The model initializer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
description |
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
train_model
train_model(
key: ndarray,
train_data: DataBundled,
val_data: DataBundled,
test_data: DataBundled,
model: Blackbox,
optimizer: GradientTransformation,
loss_fn: Callable,
callbacks: list[Callable] = [],
NUM_EPOCH: int = 1000,
_optimizer: Optimizer | None = None,
)
Train the BlackBox model
Examples:
>>> # The number of epochs break down
... NUM_EPOCH = 150
... # Total number of iterations as 90% of data is used for training
... # 10% of the data is used for testing
... total_iterations = 9 * NUM_EPOCH
... # The step for optimizer if set to 8 * NUM_EPOCH (should be less than total_iterations)
... step_for_optimizer = 8 * NUM_EPOCH
... optimizer = get_default_optimizer(step_for_optimizer)
... # The warmup steps for the optimizer
... warmup_steps = 0.1 * step_for_optimizer
... # The cool down steps for the optimizer
... cool_down_steps = total_iterations - step_for_optimizer
... total_iterations, step_for_optimizer, warmup_steps, cool_down_steps
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
Random key |
required |
model
|
Module
|
The model to be used for training |
required |
optimizer
|
GradientTransformation
|
The optimizer to be used for training |
required |
loss_fn
|
Callable
|
The loss function to be used for training |
required |
callbacks
|
list[Callable]
|
list of callback functions. Defaults to []. |
[]
|
NUM_EPOCH
|
int
|
The number of epochs. Defaults to 1_000. |
1000
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
The model parameters, optimizer state, and the histories |
Source code in src/inspeqtor/v1/models/nnx.py
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 | |
Optimize
src.inspeqtor.v1.optimize
get_default_optimizer
get_default_optimizer(
n_iterations: int,
) -> GradientTransformation
Generate present optimizer from number of training iteration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_iterations
|
int
|
Training iteration |
required |
Returns:
| Type | Description |
|---|---|
GradientTransformation
|
optax.GradientTransformation: Optax optimizer. |
Source code in src/inspeqtor/v1/optimize.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
minimize
minimize(
params: ArrayTree,
func: Callable[[ndarray], tuple[ndarray, Any]],
optimizer: GradientTransformation,
lower: ArrayTree | None = None,
upper: ArrayTree | None = None,
maxiter: int = 1000,
callbacks: list[Callable] = [],
) -> tuple[ArrayTree, list[Any]]
Optimize the loss function with bounded parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
ArrayTree
|
Intiial parameters to be optimized |
required |
lower
|
ArrayTree
|
Lower bound of the parameters |
None
|
upper
|
ArrayTree
|
Upper bound of the parameters |
None
|
func
|
Callable[[ndarray], tuple[ndarray, Any]]
|
Loss function |
required |
optimizer
|
GradientTransformation
|
Instance of optax optimizer |
required |
maxiter
|
int
|
Number of optimization step. Defaults to 1000. |
1000
|
Returns:
| Type | Description |
|---|---|
tuple[ArrayTree, list[Any]]
|
tuple[chex.ArrayTree, list[typing.Any]]: Tuple of parameters and optimization history |
Source code in src/inspeqtor/v1/optimize.py
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 | |
stochastic_minimize
stochastic_minimize(
key: ndarray,
params: ArrayTree,
func: Callable[[ndarray, ndarray], tuple[ndarray, Any]],
optimizer: GradientTransformation,
lower: ArrayTree | None = None,
upper: ArrayTree | None = None,
maxiter: int = 1000,
callbacks: list[Callable] = [],
) -> tuple[ArrayTree, list[Any]]
Optimize the loss function with bounded parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
ArrayTree
|
Intiial parameters to be optimized |
required |
lower
|
ArrayTree
|
Lower bound of the parameters |
None
|
upper
|
ArrayTree
|
Upper bound of the parameters |
None
|
func
|
Callable[[ndarray], tuple[ndarray, Any]]
|
Loss function |
required |
optimizer
|
GradientTransformation
|
Instance of optax optimizer |
required |
maxiter
|
int
|
Number of optimization step. Defaults to 1000. |
1000
|
Returns:
| Type | Description |
|---|---|
tuple[ArrayTree, list[Any]]
|
tuple[chex.ArrayTree, list[typing.Any]]: Tuple of parameters and optimization history |
Source code in src/inspeqtor/v1/optimize.py
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 | |
Physics
src.inspeqtor.v1.physics
normalizer
normalizer(matrix: ndarray) -> ndarray
Normalize the given matrix with QR decomposition and return matrix Q which is unitary
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
The matrix to normalize to unitary matrix |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The unitary matrix |
Source code in src/inspeqtor/v1/physics.py
81 82 83 84 85 86 87 88 89 90 91 | |
solver
solver(
args: HamiltonianArgs,
t_eval: ndarray,
hamiltonian: Callable[
[HamiltonianArgs, ndarray], ndarray
],
y0: ndarray,
t0: float,
t1: float,
rtol: float = 1e-07,
atol: float = 1e-07,
max_steps: int = int(2**16),
) -> ndarray
Solve the Schrodinger equation using the given Hamiltonian
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
HamiltonianArgs
|
The arguments for the Hamiltonian |
required |
t_eval
|
ndarray
|
The time points to evaluate the solution |
required |
hamiltonian
|
Callable[[HamiltonianArgs, ndarray], ndarray]
|
The Hamiltonian function |
required |
y0
|
ndarray
|
The initial state, set to jnp.eye(2, dtype=jnp.complex128) for unitary matrix |
required |
t0
|
float
|
The initial time |
required |
t1
|
float
|
The final time |
required |
rtol
|
float
|
description. Defaults to 1e-7. |
1e-07
|
atol
|
float
|
description. Defaults to 1e-7. |
1e-07
|
max_steps
|
int
|
The maxmimum step of evalution of solver. Defaults to int(2**16). |
int(2 ** 16)
|
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The solution of the Schrodinger equation at the given time points |
Source code in src/inspeqtor/v1/physics.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
auto_rotating_frame_hamiltonian
auto_rotating_frame_hamiltonian(
hamiltonian: Callable[
[HamiltonianArgs, ndarray], ndarray
],
frame: ndarray,
explicit_deriv: bool = False,
)
Implement the Hamiltonian in the rotating frame with H_I = U(t) @ H @ U^dagger(t) + i * U(t) @ dU^dagger(t)/dt
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hamiltonian
|
Callable
|
The hamiltonian function |
required |
frame
|
ndarray
|
The frame matrix |
required |
Source code in src/inspeqtor/v1/physics.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
explicit_auto_rotating_frame_hamiltonian
explicit_auto_rotating_frame_hamiltonian(
hamiltonian: Callable[
[HamiltonianArgs, ndarray], ndarray
],
frame: ndarray,
)
Implement the Hamiltonian in the rotating frame with H_I = U(t) @ H @ U^dagger(t) + i * U(t) @ dU^dagger(t)/dt
Note
This is the implementation of auto_rotating_frame_hamiltonian
that perform explicit derivative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hamiltonian
|
Callable
|
The hamiltonian function |
required |
frame
|
ndarray
|
The frame matrix |
required |
Source code in src/inspeqtor/v1/physics.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
a
a(dims: int) -> ndarray
Annihilation operator of given dims
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
int
|
Number of states |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Annihilation operator |
Source code in src/inspeqtor/v1/physics.py
242 243 244 245 246 247 248 249 250 251 | |
a_dag
a_dag(dims: int) -> ndarray
Creation operator of given dims
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
int
|
Number of states |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Creation operator |
Source code in src/inspeqtor/v1/physics.py
254 255 256 257 258 259 260 261 262 263 | |
N
N(dims: int) -> ndarray
Number operator of given dims
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
int
|
Number of states |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Number operator |
Source code in src/inspeqtor/v1/physics.py
266 267 268 269 270 271 272 273 274 275 | |
gen_hamiltonian_from
gen_hamiltonian_from(
qubit_informations: list[QubitInformation],
coupling_constants: list[CouplingInformation],
dims: int = 2,
) -> dict[str, HamiltonianTerm]
Generate dict of Hamiltonian from given qubits and coupling information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qubit_informations
|
list[QubitInformation]
|
Qubit information |
required |
coupling_constants
|
list[CouplingInformation]
|
Coupling information |
required |
dims
|
int
|
The level of the quantum system. Defaults to 2, i.e. qubit system. |
2
|
Returns:
| Type | Description |
|---|---|
dict[str, HamiltonianTerm]
|
dict[str, HamiltonianTerm]: description |
Source code in src/inspeqtor/v1/physics.py
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 | |
hamiltonian_fn
hamiltonian_fn(
args: dict[str, SignalParameters],
t: ndarray,
signals: dict[
str, Callable[[SignalParameters, ndarray], ndarray]
],
hamiltonian_terms: dict[str, HamiltonianTerm],
static_terms: list[str],
) -> ndarray
Hamiltonian function to be used whitebox.
Expect to be used in partial form, i.e. making signals, hamiltonian_terms, and static_terms static arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
dict[str, SignalParameters]
|
Control parameter |
required |
t
|
ndarray
|
Time to evaluate |
required |
signals
|
dict[str, Callable[[SignalParameters, ndarray], ndarray]]
|
Signal function of the control |
required |
hamiltonian_terms
|
dict[str, HamiltonianTerm]
|
Dict of Hamiltonian terms, where key is channel |
required |
static_terms
|
list[str]
|
list of channel id specifing the static term. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: description |
Source code in src/inspeqtor/v1/physics.py
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 | |
signal_func_v3
signal_func_v3(
get_envelope: Callable,
drive_frequency: float,
dt: float,
)
Make the envelope function into signal with drive frequency
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
get_envelope
|
Callable
|
The envelope function in unit of dt |
required |
drive_frequency
|
float
|
drive freuqency in unit of GHz |
required |
dt
|
float
|
The dt provived will be used to convert envelope unit to ns, set to 1 if the envelope function is already in unit of ns |
required |
Source code in src/inspeqtor/v1/physics.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 | |
signal_func_v4
signal_func_v4(
get_envelope: Callable,
drive_frequency: float,
dt: float,
)
Make the envelope function into signal with drive frequency
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
get_envelope
|
Callable
|
The envelope function in unit of dt |
required |
drive_frequency
|
float
|
drive freuqency in unit of GHz |
required |
dt
|
float
|
The dt provived will be used to convert envelope unit to ns, set to 1 if the envelope function is already in unit of ns |
required |
Source code in src/inspeqtor/v1/physics.py
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
make_signal_fn
make_signal_fn(
get_envelope: Callable[
[ControlParam], Callable[[ndarray], ndarray]
],
drive_frequency: float,
dt: float,
)
Make the envelope function into signal with drive frequency
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
get_envelope
|
Callable
|
The envelope function in unit of dt |
required |
drive_frequency
|
float
|
drive freuqency in unit of GHz |
required |
dt
|
float
|
The dt provived will be used to convert envelope unit to ns, set to 1 if the envelope function is already in unit of ns |
required |
Source code in src/inspeqtor/v1/physics.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | |
gate_fidelity
gate_fidelity(U: ndarray, V: ndarray) -> ndarray
Calculate the gate fidelity between U and V
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
U
|
ndarray
|
Unitary operator to be targetted |
required |
V
|
ndarray
|
Unitary operator to be compared |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Gate fidelity |
Source code in src/inspeqtor/v1/physics.py
493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
check_valid_density_matrix
check_valid_density_matrix(rho: ndarray)
Check if the provided matrix is valid density matrix
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rho
|
ndarray
|
description |
required |
Source code in src/inspeqtor/v1/physics.py
532 533 534 535 536 537 538 539 540 | |
check_hermitian
check_hermitian(op: ndarray)
Check if the provided matrix is Hermitian
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
ndarray
|
Matrix to be assert |
required |
Source code in src/inspeqtor/v1/physics.py
543 544 545 546 547 548 549 | |
direct_AFG_estimation
direct_AFG_estimation(
coefficients: ndarray, expectation_values: ndarray
) -> ndarray
Calculate single qubit average gate fidelity from expectation value
This function should be used with direct_AFG_estimation_coefficients
Examples:
>>> coefficients = direct_AFG_estimation_coefficients(unitary)
... agf = direct_AFG_estimation(coefficients, expectation_value)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficients
|
ndarray
|
The coefficients return from |
required |
expectation_values
|
ndarray
|
The expectation values assume to be shape of (..., 18) with order of |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Average Gate Fidelity |
Source code in src/inspeqtor/v1/physics.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | |
direct_AFG_estimation_coefficients
direct_AFG_estimation_coefficients(
target_unitary: ndarray,
) -> ndarray
Compute the expected coefficients to be used for AGF calculation using direct_AFG_estimation.
The order of coefficients is the same as sq.constant.default_expectation_values_order
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_unitary
|
ndarray
|
Target unitary to be computed for coefficient |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Coefficients for AGF calculation. |
Source code in src/inspeqtor/v1/physics.py
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 | |
calculate_exp
calculate_exp(
unitary: ndarray,
operator: ndarray,
density_matrix: ndarray,
) -> ndarray
Calculate the expectation value for given unitary, observable (operator), initial state (density_matrix). Shape of all arguments must be boardcastable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unitary
|
ndarray
|
Unitary operator |
required |
operator
|
ndarray
|
Quantum Observable |
required |
density_matrix
|
ndarray
|
Intial state in form of density matrix. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Expectation value of quantum observable. |
Source code in src/inspeqtor/v1/physics.py
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 | |
unitaries_prod
unitaries_prod(
prev_unitary: ndarray, curr_unitary: ndarray
) -> tuple[ndarray, ndarray]
Function to be used for trotterization Whitebox
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prev_unitary
|
ndarray
|
Product of cummulate Unitary operator. |
required |
curr_unitary
|
ndarray
|
The next Unitary operator to be multiply. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
tuple[jnp.ndarray, jnp.ndarray]: Product of previous unitart and current unitary. |
Source code in src/inspeqtor/v1/physics.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |
make_trotterization_solver
make_trotterization_solver(
hamiltonian: Callable[..., ndarray],
total_dt: int,
dt: float,
trotter_steps: int,
y0: ndarray,
)
Retutn whitebox function compute using Trotterization strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hamiltonian
|
Callable[..., ndarray]
|
The Hamiltonian function of the system |
required |
total_dt
|
int
|
The total duration of control sequence |
required |
dt
|
float
|
The duration of time step in nanosecond. |
required |
trotter_steps
|
int
|
The number of trotterization step. |
required |
y0
|
ndarray
|
The initial unitary state. Defaults to jnp.eye(2, dtype=jnp.complex128) |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Callable[..., jnp.ndarray]: Trotterization Whitebox function |
Source code in src/inspeqtor/v1/physics.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 | |
lindblad_solver
lindblad_solver(
args: HamiltonianArgs,
t_eval: ndarray,
hamiltonian: Callable[
[HamiltonianArgs, ndarray], ndarray
],
lindblad_ops: list[ndarray],
rho0: ndarray,
t0: float,
t1: float,
rtol: float = 1e-07,
atol: float = 1e-07,
max_steps: int = int(2**16),
) -> ndarray
Solve the Lindblad Master equation without flattening matrices
Source code in src/inspeqtor/v1/physics.py
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 | |
Predefined
src.inspeqtor.v1.predefined
HamiltonianSpec
dataclass
Source code in src/inspeqtor/v1/predefined.py
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 | |
get_solver
get_solver(
control_sequence: ControlSequence,
qubit_info: QubitInformation,
dt: float,
get_envelope_transformer=get_envelope_transformer,
)
Return Unitary solver from the given specification of the Hamiltonian and solver
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
control_sequence
|
ControlSequence
|
The control sequence object |
required |
qubit_info
|
QubitInformation
|
The qubit information object |
required |
dt
|
float
|
The time step size of the device |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Unsupport Solver method |
Returns:
| Type | Description |
|---|---|
|
typing.Any: The unitary solver |
Source code in src/inspeqtor/v1/predefined.py
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 | |
rotating_transmon_hamiltonian
rotating_transmon_hamiltonian(
params: HamiltonianArgs,
t: ndarray,
qubit_info: QubitInformation,
signal: Callable[[HamiltonianArgs, ndarray], ndarray],
) -> ndarray
Rotating frame hamiltonian of the transmon model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
HamiltonianParameters
|
The parameter of the pulse for hamiltonian |
required |
t
|
ndarray
|
The time to evaluate the Hamiltonian |
required |
qubit_info
|
QubitInformation
|
The information of qubit |
required |
signal
|
Callable[..., ndarray]
|
The pulse signal |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The Hamiltonian |
Source code in src/inspeqtor/v1/predefined.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
transmon_hamiltonian
transmon_hamiltonian(
params: HamiltonianArgs,
t: ndarray,
qubit_info: QubitInformation,
signal: Callable[[HamiltonianArgs, ndarray], ndarray],
) -> ndarray
Lab frame hamiltonian of the transmon model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
HamiltonianParameters
|
The parameter of the pulse for hamiltonian |
required |
t
|
ndarray
|
The time to evaluate the Hamiltonian |
required |
qubit_info
|
QubitInformation
|
The information of qubit |
required |
signal
|
Callable[..., ndarray]
|
The pulse signal |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The Hamiltonian |
Source code in src/inspeqtor/v1/predefined.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
get_gaussian_control_sequence
get_gaussian_control_sequence(
qubit_info: QubitInformation, max_amp: float = 0.5
)
Get predefined Gaussian control sequence with single Gaussian pulse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qubit_info
|
QubitInformation
|
Qubit information |
required |
max_amp
|
float
|
The maximum amplitude. Defaults to 0.5. |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
ControlSequence |
Control sequence instance |
Source code in src/inspeqtor/v1/predefined.py
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 | |
get_two_axis_gaussian_control_sequence
get_two_axis_gaussian_control_sequence(
qubit_info: QubitInformation, max_amp: float = 0.5
)
Get predefined two-axis Gaussian control sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qubit_info
|
QubitInformation
|
Qubit information |
required |
max_amp
|
float
|
The maximum amplitude. Defaults to 0.5. |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
ControlSequence |
Control sequence instance |
Source code in src/inspeqtor/v1/predefined.py
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 | |
get_drag_pulse_v2_sequence
get_drag_pulse_v2_sequence(
qubit_info_drive_strength: float,
max_amp: float = 0.5,
min_theta=0.0,
max_theta=2 * pi,
min_beta=-2.0,
max_beta=2.0,
dt=2 / 9,
)
Get predefined DRAG control sequence with single DRAG pulse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qubit_info
|
QubitInformation
|
Qubit information |
required |
max_amp
|
float
|
The maximum amplitude. Defaults to 0.5. |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
ControlSequence |
Control sequence instance |
Source code in src/inspeqtor/v1/predefined.py
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 | |
generate_experimental_data
generate_experimental_data(
key: ndarray,
hamiltonian: Callable[..., ndarray],
sample_size: int = 10,
shots: int = 1000,
strategy: SimulationStrategy = RANDOM,
get_qubit_information_fn: Callable[
[], QubitInformation
] = get_mock_qubit_information,
get_control_sequence_fn: Callable[
[], ControlSequence
] = get_multi_drag_control_sequence_v3,
max_steps: int = int(2**16),
method: WhiteboxStrategy = ODE,
trotter_steps: int = 1000,
expectation_value_receipt: list[
ExpectationValue
] = default_expectation_values_order,
) -> tuple[
ExperimentData,
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 |
1000
|
strategy
|
SimulationStrategy
|
Simulation strategy. Defaults to SimulationStrategy.RANDOM. |
RANDOM
|
get_qubit_information_fn
|
Callable[[], QubitInformation]
|
Function that return qubit information. Defaults to get_mock_qubit_information. |
get_mock_qubit_information
|
get_control_sequence_fn
|
Callable[[], ControlSequence]
|
Function that return control sequence. Defaults to get_multi_drag_control_sequence_v3. |
get_multi_drag_control_sequence_v3
|
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
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Not support strategy |
Returns:
| Type | Description |
|---|---|
tuple[ExperimentData, 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/v1/predefined.py
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 | |
get_single_qubit_whitebox
get_single_qubit_whitebox(
hamiltonian: Callable[..., ndarray],
control_sequence: ControlSequence,
qubit_info: QubitInformation,
dt: float,
max_steps: int = int(2**16),
get_envelope_transformer=get_envelope_transformer,
) -> Callable[[ndarray], ndarray]
Generate single qubit whitebox
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hamiltonian
|
Callable[..., ndarray]
|
Hamiltonian |
required |
control_sequence
|
ControlSequence
|
Control sequence instance |
required |
qubit_info
|
QubitInformation
|
Qubit information |
required |
dt
|
float
|
Duration of 1 timestep in nanosecond |
required |
max_steps
|
int
|
Maximum steps of solver. Defaults to int(2**16). |
int(2 ** 16)
|
Returns:
| Type | Description |
|---|---|
Callable[[ndarray], ndarray]
|
typing.Callable[[jnp.ndarray], jnp.ndarray]: Whitebox with ODE solver |
Source code in src/inspeqtor/v1/predefined.py
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 | |
load_data_from_path
load_data_from_path(
path: str | Path,
hamiltonian_spec: HamiltonianSpec,
pulse_reader=default_pulse_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 |
pulse_reader
|
Any
|
description. Defaults to default_pulse_reader. |
default_pulse_reader
|
Returns:
| Name | Type | Description |
|---|---|---|
LoadedData |
LoadedData
|
The object contatin necessary information for device characterization. |
Source code in src/inspeqtor/v1/predefined.py
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 | |
save_data_to_path
save_data_to_path(
path: str | Path,
experiment_data: ExperimentData,
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/v1/predefined.py
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 | |
Probabilistic
src.inspeqtor.v1.probabilistic
LearningModel
The learning model.
Source code in src/inspeqtor/v1/probabilistic.py
363 364 365 366 367 | |
make_probabilistic_model
make_probabilistic_model(
predictive_model: Callable[..., ndarray],
shots: int = 1,
block_graybox: bool = False,
separate_observables: bool = False,
log_expectation_values: bool = False,
)
Make probabilistic model from the Statistical model with priors
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_model
|
Module
|
The statistical based model, currently only support flax.linen module |
required |
model_prediction_to_expvals_fn
|
Callable[..., ndarray]
|
Function to convert output from model to expectation values array |
required |
bnn_prior
|
dict[str, Distribution] | Distribution
|
The priors of BNN. Defaults to dist.Normal(0.0, 1.0). |
required |
shots
|
int
|
The number of shots forcing PGM to sample. Defaults to 1. |
1
|
block_graybox
|
bool
|
If true, the latent variables in Graybox model will be hidden, i.e. not traced by |
False
|
enable_bnn
|
bool
|
If true, the statistical model will be convert to probabilistic model. Defaults to True. |
required |
separate_observables
|
bool
|
If true, the observable will be separate into dict form. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
|
typing.Callable: Probabilistic Graybox Model |
Source code in src/inspeqtor/v1/probabilistic.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 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 | |
get_args_of_distribution
get_args_of_distribution(x)
Get the arguments used to construct Distribution, if the provided parameter is not Distribution, return it.
So that the function can be used with jax.tree.map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
Maybe Distribution |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: Argument of Distribution if Distribution is provided. |
Source code in src/inspeqtor/v1/probabilistic.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
construct_normal_priors
construct_normal_priors(posterior)
Construct a dict of Normal Distributions with posterior
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posterior
|
Any
|
Dict of Normal distribution arguments |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: dict of Normal distributions |
Source code in src/inspeqtor/v1/probabilistic.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | |
construct_normal_prior_from_samples
construct_normal_prior_from_samples(
posterior_samples: dict[str, ndarray],
) -> dict[str, Distribution]
Construct a dict of Normal Distributions with posterior sample
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posterior_samples
|
dict[str, ndarray]
|
Posterior sample |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Distribution]
|
dict[str, dist.Distribution]: dict of Normal Distributions |
Source code in src/inspeqtor/v1/probabilistic.py
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
make_normal_posterior_dist_fn_from_svi_result
make_normal_posterior_dist_fn_from_svi_result(
key: ndarray,
guide: Callable,
params: dict[str, ndarray],
num_samples: int,
prefix: str,
) -> Callable[[str, tuple[int, ...]], Distribution]
This function create a get posterior function to be used with numpyro.contrib.module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
The random key |
required |
guide
|
Callable
|
The guide (variational distribution) |
required |
params
|
dict[str, ndarray]
|
The variational parameters |
required |
num_samples
|
int
|
The number of sample for approxiatation the posterior distributions |
required |
Examples:
prefix = "graybox"
prior_fn = make_normal_posterior_dist_fn_from_svi_result(
jax.random.key(0), guide, result.params, 10_000, prefix
)
graybox_model = sq.probabilistic.make_flax_probabilistic_graybox_model(
name=prefix,
base_model=base_model,
adapter_fn=sq.probabilistic.observable_to_expvals,
prior=prior_fn,
)
posterior_model = sq.probabilistic.make_probabilistic_model(
predictive_model=graybox_model, log_expectation_values=True
)
Returns:
| Type | Description |
|---|---|
Callable[[str, tuple[int, ...]], Distribution]
|
typing.Callable[[str, tuple[int, ...]], dist.Distribution]: The function that return posterior distribution |
Source code in src/inspeqtor/v1/probabilistic.py
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 | |
make_predictive_fn
make_predictive_fn(
posterior_model, learning_model: LearningModel
)
Construct predictive model from the probabilsitic model. This function does not relied on guide and the variational parameters
Examples:
characterized_result = sq.probabilistic.SVIResult.from_file(
PGM_model_path / "model.json"
)
base_model = sq.models.library.linen.WoModel(
shared_layers=characterized_result.config["model_config"]["hidden_sizes"][0],
pauli_layers=characterized_result.config["model_config"]["hidden_sizes"][1],
)
graybox_model = sq.probabilistic.make_flax_probabilistic_graybox_model(
name="graybox",
base_model=base_model,
adapter_fn=sq.probabilistic.observable_to_expvals,
prior=dist.Normal(0, 1),
)
model = sq.probabilistic.make_probabilistic_model(
graybox_probabilistic_model=graybox_model,
)
# initialize guide
guide = sq.probabilistic.auto_diagonal_normal_guide(
model,
ml.custom_feature_map(loaded_data.control_parameters),
loaded_data.unitaries,
jnp.zeros(shape=(shots, loaded_data.control_parameters.shape[0], 18)),
)
priors = {
k.strip("graybox/"): v
for k, v in make_prior_from_params(guide, characterized_result.params).items()
}
graybox_model = sq.probabilistic.make_flax_probabilistic_graybox_model(
name="graybox",
base_model=base_model,
adapter_fn=sq.probabilistic.observable_to_expvals,
prior=priors,
)
posterior_model = sq.probabilistic.make_probabilistic_model(
graybox_probabilistic_model=graybox_model,
shots=shots,
block_graybox=True,
log_expectation_values=True,
)
predicetive_fn = sq.probabilistic.make_predictive_fn(
posterior_model, sq.probabilistic.LearningModel.BernoulliProbs
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posterior_model
|
Any
|
probabilsitic model |
required |
learning_model
|
LearningModel
|
description |
required |
Source code in src/inspeqtor/v1/probabilistic.py
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 | |
make_pdf
make_pdf(sample: ndarray, bins: int, srange=(-1, 1))
Make the numberical PDF from given sample using histogram method
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
ndarray
|
Sample to make PDF. |
required |
bins
|
int
|
The number of interval bin. |
required |
srange
|
tuple
|
The range of the pdf. Defaults to (-1, 1). |
(-1, 1)
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: The approximated numerical PDF |
Source code in src/inspeqtor/v1/probabilistic.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | |
safe_kl_divergence
safe_kl_divergence(p: ndarray, q: ndarray)
Calculate the KL divergence where the infinity is converted to zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
ndarray
|
The left PDF |
required |
q
|
ndarray
|
The right PDF |
required |
Returns:
| Type | Description |
|---|---|
|
jnp.ndarray: The KL divergence |
Source code in src/inspeqtor/v1/probabilistic.py
476 477 478 479 480 481 482 483 484 485 486 | |
kl_divergence
kl_divergence(p: ndarray, q: ndarray)
Calculate the KL divergence
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
ndarray
|
The left PDF |
required |
q
|
ndarray
|
The right PDF |
required |
Returns:
| Type | Description |
|---|---|
|
jnp.ndarray: The KL divergence |
Source code in src/inspeqtor/v1/probabilistic.py
489 490 491 492 493 494 495 496 497 498 499 | |
safe_jensenshannon_divergence
safe_jensenshannon_divergence(p: ndarray, q: ndarray)
Calculate Jensen-Shannon Divergnece using KL divergence. Implement following: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.jensenshannon.html
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
ndarray
|
The left PDF |
required |
q
|
ndarray
|
The right PDF |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/probabilistic.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 | |
jensenshannon_divergence_from_pmf
jensenshannon_divergence_from_pmf(p: ndarray, q: ndarray)
Calculate the Jensen-Shannon Divergence from PMF
Example
key = jax.random.key(0)
key_1, key_2 = jax.random.split(key)
sample_1 = jax.random.normal(key_1, shape=(10000, ))
sample_2 = jax.random.normal(key_2, shape=(10000, ))
# Determine srange from sample
merged_sample = jnp.concat([sample_1, sample_2])
srange = jnp.min(merged_sample), jnp.max(merged_sample)
# https://stats.stackexchange.com/questions/510699/discrete-kl-divergence-with-decreasing-bin-width
# Recommend this book: https://catalog.lib.uchicago.edu/vufind/Record/6093380/TOC
bins = int(2 * (sample_2.shape[0]) ** (1/3))
# bins = 10
dis_1 = sq.probabilistic.make_pdf(sample_1, bins=bins, srange=srange)
dis_2 = sq.probabilistic.make_pdf(sample_2, bins=bins, srange=srange)
jsd = sq.probabilistic.jensenshannon_divergence_from_pdf(dis_1, dis_2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
ndarray
|
The 1st probability mass function |
required |
q
|
ndarray
|
The 1st probability mass function |
required |
Returns:
| Type | Description |
|---|---|
|
jnp.ndarray: The Jensen-Shannon Divergence of p and q |
Source code in src/inspeqtor/v1/probabilistic.py
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 | |
jensenshannon_divergence_from_sample
jensenshannon_divergence_from_sample(
sample_1: ndarray, sample_2: ndarray
) -> ndarray
Calculate the Jensen-Shannon Divergence from sample
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_1
|
ndarray
|
The left PDF |
required |
sample_2
|
ndarray
|
The right PDF |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The Jensen-Shannon Divergence of p and q |
Source code in src/inspeqtor/v1/probabilistic.py
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 | |
batched_matmul
batched_matmul(x, w, b)
A specialized batched matrix multiplication of weight and input x, then add the bias.
This function is intended to be used in dense_layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
The input x |
required |
w
|
ndarray
|
The weight to multiply to x |
required |
b
|
ndarray
|
The bias |
required |
Returns:
| Type | Description |
|---|---|
|
jnp.ndarray: Output of the operations. |
Source code in src/inspeqtor/v1/probabilistic.py
579 580 581 582 583 584 585 586 587 588 589 590 591 | |
get_trace
get_trace(fn, key=key(0))
Convinent function to get a trace of the probabilistic model in numpyro.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
function
|
The probabilistic model in numpyro. |
required |
key
|
ndarray
|
The random key. Defaults to jax.random.key(0). |
key(0)
|
Source code in src/inspeqtor/v1/probabilistic.py
594 595 596 597 598 599 600 601 602 603 604 605 | |
default_priors_fn
default_priors_fn(
name: str, shape: tuple[int, ...]
) -> Distribution
This is a default prior function for the dense_layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The site name of the parameters, if end with |
required |
Returns:
| Type | Description |
|---|---|
Distribution
|
typing.Any: description |
Source code in src/inspeqtor/v1/probabilistic.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 | |
dense_layer
dense_layer(
x: ndarray,
name: str,
in_features: int,
out_features: int,
priors_fn: Callable[
[str, tuple[int, ...]], Distribution
] = default_priors_fn,
)
A custom probabilistic dense layer for neural network model.
This function intended to be used with numpyro
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
The input x |
required |
name
|
str
|
Site name of the layer |
required |
in_features
|
int
|
The size of the feature. |
required |
out_features
|
int
|
The desired size of the output feature. |
required |
priors_fn
|
Callable[[str], Distribution]
|
The prior function to be used for initializing prior distribution. Defaults to default_priors_fn. |
default_priors_fn
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: Output of the layer given x. |
Source code in src/inspeqtor/v1/probabilistic.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 | |
init_default
init_default(params_name: str)
The initialization function for deterministic dense layer
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params_name
|
str
|
The site name |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Unsupport site name |
Returns:
| Type | Description |
|---|---|
|
typing.Any: The function to be used for parameters init given site name. |
Source code in src/inspeqtor/v1/probabilistic.py
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 | |
dense_deterministic_layer
dense_deterministic_layer(
x,
name: str,
in_features: int,
out_features: int,
batch_shape: tuple[int, ...] = (),
init_fn=init_default,
)
The deterministic dense layer, to be used with SVI optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The input feature |
required |
name
|
str
|
The site name |
required |
in_features
|
int
|
The size of the input features |
required |
out_features
|
int
|
The desired size of the output features. |
required |
batch_shape
|
tuple[int, ...]
|
The batch size of the x. Defaults to (). |
()
|
init_fn
|
Any
|
Initilization function of the model parameters. Defaults to init_default. |
init_default
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: The output of the layer given x. |
Source code in src/inspeqtor/v1/probabilistic.py
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 | |
make_posteriors_fn
make_posteriors_fn(
key: ndarray, guide, params, num_samples=10000
)
Make the posterior distribution function that will return the posterior of parameter of the given name, from guide and parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guide
|
Any
|
The guide function |
required |
params
|
Any
|
The parameters of the guide |
required |
num_samples
|
int
|
The sample size. Defaults to 10000. |
10000
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: A function of parameter name that return the sample from the posterior distribution of the parameters. |
Source code in src/inspeqtor/v1/probabilistic.py
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
auto_diagonal_normal_guide
auto_diagonal_normal_guide(
model,
*args,
block_sample: bool = False,
init_loc_fn=zeros,
key: ndarray = key(0),
)
Automatically generate guide from given model. Expected to be initialized with the example input of the model. The given input should also including the observed site. The blocking capability is intended to be used in the when the guide will be used with its corresponding model in anothe model. This is the avoid site name duplication, while allows for model to use newly sample from the guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
The probabilistic model. |
required |
block_sample
|
bool
|
Flag to block the sample site. Defaults to False. |
False
|
init_loc_fn
|
Any
|
Initialization of guide parameters function. Defaults to jnp.zeros. |
zeros
|
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/probabilistic.py
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 | |
auto_diagonal_normal_guide_v2
auto_diagonal_normal_guide_v2(
model,
*args,
init_dist_fn=init_normal_dist_fn,
init_params_fn=init_params_fn,
block_sample: bool = False,
key: ndarray = key(0),
)
Automatically generate guide from given model. Expected to be initialized with the example input of the model. The given input should also including the observed site. The blocking capability is intended to be used in the when the guide will be used with its corresponding model in anothe model. This is the avoid site name duplication, while allows for model to use newly sample from the guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
The probabilistic model. |
required |
block_sample
|
bool
|
Flag to block the sample site. Defaults to False. |
False
|
init_loc_fn
|
Any
|
Initialization of guide parameters function. Defaults to jnp.zeros. |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/probabilistic.py
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 | |
make_predictive_fn_v2
make_predictive_fn_v2(model, guide, params, shots: int)
Make a postirior predictive model function from model, guide, SVI parameters, and the number of shots. This version relied explicitly on the guide and variational parameters. It might be slow than the first version.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Probabilistic model. |
required |
guide
|
Any
|
Gudie corresponded to the model |
required |
params
|
Any
|
SVI parameters of the guide |
required |
shots
|
int
|
The number of shots |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: The posterior predictive model. |
Source code in src/inspeqtor/v1/probabilistic.py
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 | |
make_predictive_SGM_model
make_predictive_SGM_model(
model: Module,
model_params,
output_to_expectation_values_fn,
shots: int,
)
Make a predictive model from given SGM model, the model parameters, and number of shots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Flax model |
required |
model_params
|
Any
|
The model parameters. |
required |
shots
|
int
|
The number of shots. |
required |
Source code in src/inspeqtor/v1/probabilistic.py
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 | |
make_predictive_MCDGM_model
make_predictive_MCDGM_model(model: Module, model_params)
Make a predictive model from given Monte-Carlo Dropout Graybox model, and the model parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Monte-Carlo Dropout Graybox model |
required |
model_params
|
Any
|
The model parameters |
required |
Source code in src/inspeqtor/v1/probabilistic.py
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | |
make_predictive_resampling_model
make_predictive_resampling_model(
predictive_fn: Callable[[ndarray, ndarray], ndarray],
shots: int,
) -> Callable[[ndarray, ndarray, ndarray], ndarray]
Make a binary predictive model from given SGM model, the model parameters, and number of shots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive_fn
|
Callable[[ndarray, ndarray], ndarray]
|
The predictive_fn embeded with the SGM model. |
required |
shots
|
int
|
The number of shots. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[ndarray, ndarray, ndarray], ndarray]
|
typing.Callable[[jnp.ndarray, jnp.ndarray, jnp.ndarray], jnp.ndarray]: Binary predictive model. |
Source code in src/inspeqtor/v1/probabilistic.py
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 | |
make_probabilistic_graybox_model
make_probabilistic_graybox_model(model, adapter_fn)
This function make a probabilistic graybox model using custom numpyro BNN model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_type_
|
description |
required |
adapter_fn
|
_type_
|
description |
required |
Source code in src/inspeqtor/v1/probabilistic.py
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 | |
auto_diagonal_normal_guide_v3
auto_diagonal_normal_guide_v3(
model,
*args,
init_dist_fn=bnn_init_dist_fn,
init_params_fn=bnn_init_params_fn,
dist_transform_fn=default_transform_dist_fn,
block_sample: bool = False,
key: ndarray = key(0),
)
Automatically generate guide from given model. Expected to be initialized with the example input of the model. The given input should also including the observed site. The blocking capability is intended to be used in the when the guide will be used with its corresponding model in anothe model. This is the avoid site name duplication, while allows for model to use newly sample from the guide.
Notes
This version enable even more flexible initialization strategy. This function intended to be able to be compatible with auto marginal guide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
The probabilistic model. |
required |
block_sample
|
bool
|
Flag to block the sample site. Defaults to False. |
False
|
init_loc_fn
|
Any
|
Initialization of guide parameters function. Defaults to jnp.zeros. |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/probabilistic.py
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 | |
make_posterior_fn
make_posterior_fn(
params, get_dist_fn: Callable[[str], Any]
)
This function create a posterior function to make a posterior predictive model
Examples:
posterior_model = sq.probabilistic.make_probabilistic_model(
predictive_model=partial(
probabilistic_graybox_model,
priors_fn=make_posterior_fn(result.params, init_bnn_dist_fn),
),
log_expectation_values=True,
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
_type_
|
The variational parameters from SVI |
required |
get_dist_fn
|
Callable[[str], Distribution]
|
The function that return function given name |
required |
Source code in src/inspeqtor/v1/probabilistic.py
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 | |
Utilities
src.inspeqtor.v1.utils
center_location
center_location(
num_of_pulse: int, total_time_dt: int | float
) -> ndarray
Create an array of location equally that centered each pulse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_of_pulse
|
int
|
The number of the pulse in the sequence to be equally center. |
required |
total_time_dt
|
int | float
|
The total bins of the sequence. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The array of location equally that centered each pulse. |
Source code in src/inspeqtor/v1/utils.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
drag_envelope_v2
drag_envelope_v2(
amp: float | ndarray,
sigma: float | ndarray,
beta: float | ndarray,
center: float | ndarray,
final_amp: float | ndarray = 1.0,
)
Drag pulse following: https://docs.quantum.ibm.com/api/qiskit/qiskit.pulse.library.Drag_class.rst#drag
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amp
|
float | ndarray
|
The amplitude of the pulse |
required |
sigma
|
float | ndarray
|
The standard deviation of the pulse |
required |
beta
|
float | ndarray
|
DRAG coefficient. |
required |
center
|
float | ndarray
|
Center location of the pulse |
required |
final_amp
|
float | ndarray
|
Final amplitude of the control. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
|
typing.Callable: DRAG envelope function |
Source code in src/inspeqtor/v1/utils.py
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 | |
detune_hamiltonian
detune_hamiltonian(
hamiltonian: Callable[
[HamiltonianArgs, ndarray], ndarray
],
detune: float,
) -> Callable[[HamiltonianArgs, ndarray], ndarray]
Detune the Hamiltonian in Z-axis with detuning coefficient
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hamiltonian
|
Callable[[HamiltonianArgs, ndarray], ndarray]
|
Hamiltonian function to be detuned |
required |
detune
|
float
|
Detuning coefficient |
required |
Returns:
| Type | Description |
|---|---|
Callable[[HamiltonianArgs, ndarray], ndarray]
|
typing.Callable: Detuned Hamiltonian. |
Source code in src/inspeqtor/v1/utils.py
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 | |
prepare_data
prepare_data(
exp_data: ExperimentData,
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
|
|
required |
control_sequence
|
ControlSequence
|
Control sequence of the experiment |
required |
whitebox
|
Callable
|
Ideal unitary solver. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
LoadedData |
LoadedData
|
|
Source code in src/inspeqtor/v1/utils.py
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 | |
random_split
random_split(
key: ndarray, test_size: int, *data_arrays: ndarray
)
The random_split function splits the data into training and testing sets.
Examples:
>>> key = jax.random.key(0)
>>> x = jnp.arange(10)
>>> y = jnp.arange(10)
>>> x_train, y_train, x_test, y_test = random_split(key, 2, x, y)
>>> assert x_train.shape[0] == 8 and y_train.shape[0] == 8
>>> assert x_test.shape[0] == 2 and y_test.shape[0] == 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
Random key. |
required |
test_size
|
int
|
The size of the test set. Must be less than the size of the data. |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Sequence[jnp.ndarray]: The training and testing sets in the same order. |
Source code in src/inspeqtor/v1/utils.py
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 | |
dataloader
dataloader(
arrays: Sequence[ndarray],
batch_size: int,
num_epochs: int,
*,
key: ndarray,
)
The dataloader function creates a generator that yields batches of data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arrays
|
Sequence[ndarray]
|
The list or tuple of arrays to be batched. |
required |
batch_size
|
int
|
The size of the batch. |
required |
num_epochs
|
int
|
The number of epochs. If set to -1, the generator will run indefinitely. |
required |
key
|
ndarray
|
The random key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
None |
stop the generator. |
Yields:
| Type | Description |
|---|---|
|
typing.Any: (step, batch_idx, is_last_batch, epoch_idx), (array_batch, ...) |
Source code in src/inspeqtor/v1/utils.py
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 | |
expectation_value_to_prob_plus
expectation_value_to_prob_plus(
expectation_value: ndarray,
) -> ndarray
Calculate the probability of -1 and 1 for the given expectation value E[O] = -1 * P[O = -1] + 1 * P[O = 1], where P[O = -1] + P[O = 1] = 1 Thus, E[O] = -1 * (1 - P[O = 1]) + 1 * P[O = 1] E[O] = 2 * P[O = 1] - 1 -> P[O = 1] = (E[O] + 1) / 2 Args: expectation_value (jnp.ndarray): Expectation value of quantum observable
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Probability of measuring plus eigenvector |
Source code in src/inspeqtor/v1/utils.py
269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
expectation_value_to_prob_minus
expectation_value_to_prob_minus(
expectation_value: ndarray,
) -> ndarray
Convert quantum observable expectation value to probability of measuring -1.
For a binary quantum observable \(\hat{O}\) with eigenvalues \(b = \{-1, 1\}\), this function calculates the probability of measuring the eigenvalue -1 given its expectation value.
Derivation: $$ \langle \hat{O} \rangle = -1 \cdot \Pr(b=-1) + 1 \cdot \Pr(b = 1) $$ With the constraint \(\Pr(b = -1) + \Pr(b = 1) = 1\):
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expectation_value
|
ndarray
|
Expectation value of the quantum observable, must be in range [-1, 1]. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Probability of measuring the -1 eigenvalue. |
Source code in src/inspeqtor/v1/utils.py
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 | |
expectation_value_to_eigenvalue
expectation_value_to_eigenvalue(
expectation_value: ndarray, SHOTS: int
) -> ndarray
Convert expectation value to eigenvalue
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expectation_value
|
ndarray
|
Expectation value of quantum observable |
required |
SHOTS
|
int
|
The number of shots used to produce expectation value |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Array of eigenvalues |
Source code in src/inspeqtor/v1/utils.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
eigenvalue_to_binary
eigenvalue_to_binary(eigenvalue: ndarray) -> ndarray
Convert -1 to 1, and 0 to 1 This implementation should be differentiable
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eigenvalue
|
ndarray
|
Eigenvalue to convert to bit value |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Binary array |
Source code in src/inspeqtor/v1/utils.py
339 340 341 342 343 344 345 346 347 348 349 350 | |
binary_to_eigenvalue
binary_to_eigenvalue(binary: ndarray) -> ndarray
Convert 1 to -1, and 0 to 1 This implementation should be differentiable
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary
|
ndarray
|
Bit value to convert to eigenvalue |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Eigenvalue array |
Source code in src/inspeqtor/v1/utils.py
353 354 355 356 357 358 359 360 361 362 363 364 | |
recursive_vmap
recursive_vmap(func, in_axes)
Perform recursive vmap on the given axis
Note
def func(x):
assert x.ndim == 1
return x ** 2
x = jnp.arange(10)
x_test = jnp.broadcast_to(x, (2, 3, 4,) + x.shape)
x_test.shape, recursive_vmap(func, (0,) * (x_test.ndim - 1))(x_test).shape
((2, 3, 4, 10), (2, 3, 4, 10))
Examples:
>>> def func(x):
... assert x.ndim == 1
... return x ** 2
>>> x = jnp.arange(10)
>>> x_test = jnp.broadcast_to(x, (2, 3, 4,) + x.shape)
>>> x_test.shape, recursive_vmap(func, (0,) * (x_test.ndim - 1))(x_test).shape
((2, 3, 4, 10), (2, 3, 4, 10))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Any
|
The function for vmap |
required |
in_axes
|
Any
|
The axes for vmap |
required |
Returns:
| Type | Description |
|---|---|
|
typing.Any: description |
Source code in src/inspeqtor/v1/utils.py
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 | |
calculate_shots_expectation_value
calculate_shots_expectation_value(
key: ndarray,
initial_state: ndarray,
unitary: ndarray,
operator: ndarray,
shots: int,
) -> ndarray
Calculate finite-shots estimate of expectation value
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
ndarray
|
Random key |
required |
initial_state
|
ndarray
|
Inital state |
required |
unitary
|
ndarray
|
Unitary operator |
required |
plus_projector
|
ndarray
|
The eigenvector corresponded to +1 eigenvalue of Pauli observable. |
required |
shots
|
int
|
Number of shot to be used in estimation of expectation value |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: Finite-shot estimate expectation value |
Source code in src/inspeqtor/v1/utils.py
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 | |
shot_quantum_device
shot_quantum_device(
key: ndarray,
control_parameters: ndarray,
solver: Callable[[ndarray], ndarray],
SHOTS: int,
expectation_value_receipt: Sequence[
ExpectationValue
] = default_expectation_values_order,
) -> ndarray
This is the shot estimate expectation value quantum device
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
control_parameters
|
ndarray
|
The control parameter to be feed to simlulator |
required |
key
|
ndarray
|
Random key |
required |
solver
|
Callable[[ndarray], ndarray]
|
The ODE solver for propagator |
required |
SHOTS
|
int
|
The number of shots used to estimate expectation values |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
jnp.ndarray: The expectation value of shape (control_parameters.shape[0], 18) |
Source code in src/inspeqtor/v1/utils.py
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 | |
Visualization
src.inspeqtor.v1.visualization
format_expectation_values
format_expectation_values(
expvals: ndarray,
) -> dict[str, dict[str, ndarray]]
This function formats expectation values of shape (18, N) to a dictionary with the initial state as outer key and the observable as inner key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expvals
|
ndarray
|
Expectation values of shape (18, N). Assumes that order is as in default_expectation_values_order. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, ndarray]]
|
dict[str, dict[str, jnp.ndarray]]: A dictionary with the initial state as outer key and the observable as inner key. |
Source code in src/inspeqtor/v1/visualization.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
plot_loss_with_moving_average
plot_loss_with_moving_average(
x: ndarray | ndarray,
y: ndarray | ndarray,
ax: Axes,
window: int = 50,
annotate_at: list[float] = [0.2, 0.4, 0.6, 0.8, 1.0],
**kwargs,
) -> Axes
Plot the moving average of the given argument y
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | ndarray
|
The horizontal axis |
required |
y
|
ndarray | ndarray
|
The vertical axis |
required |
ax
|
Axes
|
Axes object |
required |
window
|
int
|
The moving average window. Defaults to 50. |
50
|
annotate_at
|
list[int]
|
The list of x positions to annotate the y value. Defaults to [2000, 4000, 6000, 8000, 10000]. |
[0.2, 0.4, 0.6, 0.8, 1.0]
|
Returns:
| Name | Type | Description |
|---|---|---|
Axes |
Axes
|
Axes object. |
Source code in src/inspeqtor/v1/visualization.py
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 | |
assert_list_of_axes
assert_list_of_axes(axes) -> list[Axes]
Assert the provide object that they are a list of Axes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
Any
|
Expected to be numpy array of Axes |
required |
Returns:
| Type | Description |
|---|---|
list[Axes]
|
list[Axes]: The list of Axes |
Source code in src/inspeqtor/v1/visualization.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
set_fontsize
set_fontsize(ax: Axes, fontsize: float | int)
Set all fontsize of the Axes object
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
The Axes object which fontsize to be changed. |
required |
fontsize
|
float | int
|
The fontsize. |
required |
Source code in src/inspeqtor/v1/visualization.py
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |