QuaCCAToo modules

qsys

This module contains the plot_energy_B0 function, compose_sys function and the QSys class.

class quaccatoo.qsys.qsys.QSys(H0: Qobj | ndarray, *, rho0: Qobj | ndarray | int | None = None, c_ops: Qobj | list[Qobj] | None = None, observable: Qobj | list[Qobj] | None = None, units_H0: str | None = None)[source]

The QSys class defines a general quantum system and contains a method for plotting the energy levels of the Hamiltonian.

Attributes:
H0Qobj or numpy.ndarray

Time-independent internal Hamiltonian of the system.

rho0Qobj, numpy.ndarray, or int

Initial state of the system.

c_opsQobj or list of Qobj

List of collapse operators.

observableQobj or list of Qobj

Observable to be measured.

units_H0str

Units of the Hamiltonian.

energy_levelsnumpy.ndarray

Energy levels of the Hamiltonian.

eigenstatesnumpy.ndarray of Qobj

Eigenstates of the Hamiltonian.

dim_add_spinint

Dimension of the added spin if the add_spin method is used.

Methods

_get_energy_levels()

Calculates the eigenenergies of the Hamiltonian and subtract the ground state energy from all of them to get the lowest level at 0.

plot_energy([figsize, energy_lim])

Plots the energy levels of the Hamiltonian defined in the system.

add_spin(H_spin)

Adds another spin to the system's Hamiltonian, given a Hamiltonian for the new spin.

truncate(indexes)

Truncantes the quantum system by removing the states specified by the indexes from the Hamiltonian, the initial state, the observable and the collapse operators.

_check_B0(B0, units_B0)

Internal function for checking if external magnetic field B0 is correctly defined.

_check_angles(theta, phi_r, units_angles)

Internal function for checking if the angles with external magnetic field theta and phi_r are correctly defined.

_check_temp(temp, units_temp)

Internal function for checking if the temperature is correctly defined, converting it to Kelvin if it was given in Celsius.

_tensor_product_N(H, N)

Performs a tensor product of the provided Hamiltonian with the identity operator corresponding to the dimension of the nitrogen isoptope

Construct the QSys class. It initializes the system with the Hamiltonian, the initial state, the collapse operators and the observable. Checking all inputs and calculating the energy levels of the Hamiltonian.

Parameters:
H0Qobj | array

Time-independent internal Hamiltonian of the system

rho0Qobj | array | int

Initial state of the system. Can be a Qobj, an array or an index number indicating the system eigenstates

c_opsQobj | list(Qobj)

List of collapse operators

observableQobj | list(Qobj)

Observable to be measured

units_H0str

Units of the Hamiltonian

Methods

add_spin(H_spin)

Adds another spin to the system's Hamiltonian, given a Hamiltonian for the new spin.

plot_energy([figsize, energy_lim])

Plots the energy levels of the Hamiltonian defined in the system.

truncate(indexes)

Truncantes the quantum system by removing the states specified by the indexes from the Hamiltonian, the initial state, the observable and the collapse operators.

add_spin(H_spin: Qobj) None[source]

Adds another spin to the system’s Hamiltonian, given a Hamiltonian for the new spin. Updates the time-independent Hamiltonian, the energy levels, the initial state, the observable and the collapse operators accordingly.

Parameters:
H_spinQobj

Hamiltonian of the new spin

plot_energy(figsize: tuple[int, int] = (2, 6), energy_lim: tuple[int | float, int | float] | None = None) None[source]

Plots the energy levels of the Hamiltonian defined in the system.

Parameters:
figsizetuple

Size of the figure

energy_limtuple

Limits of the energy levels

truncate(indexes: int | list[int]) None[source]

Truncantes the quantum system by removing the states specified by the indexes from the Hamiltonian, the initial state, the observable and the collapse operators. For example, if S=1 and the user wants to remove the ms=-1 state, the indexes is set to 0 and the qsys is truncated to the ms=0 and ms=+1 subspace. The method uses the numpy.delete function to remove the specified indexes from the Hamiltonian and the initial state.

Parameters:
indexesint or list of int

Index or list of indexes to be removed from the system.

quaccatoo.qsys.qsys.compose_sys(qsys1: QSys, qsys2: QSys) QSys[source]

Takes two quantum systems and returns the composed system by performing tensor products of the two, after checking if all parameters are valid.

Parameters:
qsys1QSys

First quantum system.

qsys2QSys

Second quantum system.

Returns:
qsys1 X qsys2QSys

Composed quantum system.

quaccatoo.qsys.qsys.plot_energy_B0(B0: ndarray | list[float], H0: Qobj | list[Qobj], figsize: tuple[int, int] = (6, 4), energy_lim: tuple[int | float, int | float] | None = None, xlabel: str = 'Magnetic Field', ylabel: str = 'Energy (MHz)') None[source]

Plots the energy levels of a Hamiltonian as a function of a magnetic field B0.

Parameters:
B0list or numpy.ndarray

List of magnetic fields.

H0list of Qobj

List of Hamiltonians.

figsizetuple

Size of the figure.

energy_limtuple

Limits of the energy levels.

xlabelstr

Label of the x-axis.

ylabelstr

Label of the y-axis.

NV_sys

This module contains NV class, which is a subclass of QSys.

class quaccatoo.qsys.NV_sys.NV(B0: float, *, N: Literal[0, 14, 15] | None, c_ops: Qobj | list[Qobj] | None = None, units_B0: Literal['T', 'mT', 'G'] = 'mT', theta: float = 0.0, phi_r: float = 0.0, units_angles: Literal['rad', 'deg'] = 'deg', temp: float | None = None, units_temp: Literal['C', 'K'] = 'K', E: float = 0)[source]

NV class contains attributes and methods to simulate the nitrogen vacancy center in diamond.

Attributes:
B0float

Magnetic field

N15, 14, 0 or None

Nitrogen isotope, or 0 for no nuclear spin

units_B0str

Units of the magnetic field (T, mT or G)

thetafloat

Angle of the magnetic field with respect to the NV axis

phi_rfloat

Azimutal angle of the magnetic field with the NV axis

units_anglesstr

Units of the angles (deg or rad)

tempfloat or None

Temperature

energy_levelslist

List of energy levels of the Hamiltonian

MW_freqsnumpy.ndarray

Microwave frequencies

RF_freqsnumpy.ndarray

RF frequencies

MW_h1Qobj

Microwave Hamiltonian

RF_h1Qobj

RF Hamiltonian

Methods

_rho0_T()

Calculates the initial state of the system at low temperatures using the Boltzmann distribution.

_set_MW()

Sets the standard microwave Hamiltonian for the NV center corresponding to the electronic spin transitions.

_set_RF()

Sets the standard RF Hamiltonian for the NV center corresponding to the nuclear spin transitions.

zero_field()

Get the NV Hamiltonian term accounting for the zero field splitting.

electron_zeeman()

Get the NV hamiltonian term accounting for the electron Zeeman effect.

nuclear_zeeman()

Get the NV hamiltonian term accounting for the nuclear (Nitrogen) Zeeman effect.

hyperfine_N()

Get the NV hamiltonian term accounting for the hyperfine coupling with Nitrogen.

quadrupole()

Get the quadrupole term

add_spin(H_spin)

Overwrites the parent class method by calling it and updating MW_h1 and RF_h1 attributes

truncate([indexes, mS, mI])

Overwrites the parent class method by calling it and updating MW_h1 and RF_h1 attributes.

Notes

The NV class inherits the methods and attributes from the QSys class.

Constructor for the NV class. Takes the nitrogen isotope, the magnetic field intensity and angles with the quantization axis as inputs and calculates the Hamiltonian with all relevant attributes.

Parameters:
B0float

Magnetic field

N15 | 14 | 0 | None

Nitrogen isotope, or 0 for no nuclear spin

c_opslist(Qobj)

List of collapse operators

units_B0str

Units of the magnetic field (T, mT or G)

thetafloat

Angle of the magnetic field with respect to the NV axis

phi_rfloat

Angle of the magnetic field in the xy plane

units_anglesstr

Units of the angles (deg or rad)

tempfloat

Temperature

units_tempstr

Temperature units (‘C’/’K’)

Efloat

Perpedicular component of the zero field splitting

Methods

add_spin(H_spin)

Overwrites the parent class method by calling it and updating MW_h1 and RF_h1 attributes

electron_zeeman()

Get the NV hamiltonian term accounting for the electron Zeeman effect.

hyperfine_N()

Get the NV hamiltonian term accounting for the hyperfine coupling with Nitrogen.

nuclear_zeeman()

Get the NV hamiltonian term accounting for the nuclear (Nitrogen) Zeeman effect.

plot_energy([figsize, energy_lim])

Plots the energy levels of the Hamiltonian defined in the system.

quadrupole()

Get the quadrupole term

truncate([indexes, mS, mI])

Overwrites the parent class method by calling it and updating MW_h1 and RF_h1 attributes.

zero_field()

Get the NV Hamiltonian term accounting for the zero field splitting.

add_spin(H_spin: Qobj) None[source]

Overwrites the parent class method by calling it and updating MW_h1 and RF_h1 attributes

Parameters:
H_spinQobj

Hamiltonian of the extra spin

electron_zeeman() Qobj[source]

Get the NV hamiltonian term accounting for the electron Zeeman effect.

Returns:
Electron Zeeman HamiltonianQobj
hyperfine_N() Qobj | int[source]

Get the NV hamiltonian term accounting for the hyperfine coupling with Nitrogen.

Returns:
Hyperfine HamiltonianQobj
nuclear_zeeman() Qobj | int[source]

Get the NV hamiltonian term accounting for the nuclear (Nitrogen) Zeeman effect.

Returns:
Nuclear Zeeman HamiltonianQobj
quadrupole() Qobj | int[source]

Get the quadrupole term

Returns:
quadrupole HamiltonianQobj
truncate(indexes: int | list[int] | None = None, mS: Literal[1, 0, -1] | None = None, mI: Literal[1, 0, -1] | None = None) None[source]

Overwrites the parent class method by calling it and updating MW_h1 and RF_h1 attributes. The indexes to be removed are calculated according to the mS and mI parameters.

Parameters:
mS‘1’, ‘0’, ‘-1’, None

Electronic level to be excluded

mI‘1’, ‘0’, ‘-1’, None

Electronic level to be excluded

zero_field() Qobj[source]

Get the NV Hamiltonian term accounting for the zero field splitting. If the temperature attribute is set to a value below 295 K, the D parameter is calculated using a 5th order polynomial function from X. D. Chen et al. Appl. Phys. Lett. 99, 161903 (2011). Otherwise, if the temperature is above 295 K, a 3rd order polynomial function from D. M. Toyli et al. Phys. Rev. X 2, 031001 (2012) is used.

Returns:
Zero Field HamiltonianQobj

P1_sys

This module contains P1 class for simulating P1 centers in diamond, being a subclass of QSys.

class quaccatoo.qsys.P1_sys.P1(B0: float, *, rot_index: Literal[0, 1, 2, 3], N: Literal[0, 14, 15] | None = None, rho0: Qobj | ndarray | None = None, c_ops: Qobj | list[Qobj] | None = None, observable: Qobj | list[Qobj] | None = None, units_B0: Literal['T', 'mT', 'G'] = 'mT', theta: float = 0.0, phi_r: float = 0.0, theta_1: float = 90.0, phi_r_1: float = 0.0, units_angles: Literal['rad', 'deg'] = 'deg')[source]

P1 class contains attributes and methods to simulate the neutral substitutional nitrogen center in diamond. Due to Jahn-Teller effect this defect has a C_{3v} point symmetry, which means there are four isolated orientation families of P1 centers in diamond. In simulations the lab reference frame is chosen in such a way that it is a principal axis system (PAS) for one of the four families (rotation index 0). Hamiltonians of other orientation families are obtained by the transition from PAS to the corresponding orientation using rotation matrices.

Attributes:
B0float

Magnetic field intensity.

rot_indexint

Rotation index, integer between 0 and 3.

Rlist

List of rotation matrices to go from the PAS (principal axis system) frame to the lab frame.

Nint

Nitrogen isotope, or 0 for no nuclear spin.

units_B0str

Units of the magnetic field (T, mT or G)

thetafloat

Angle of the static magnetic field vector with respect to the z axis

phi_rfloat

Azimutal angle of the static magnetic field vector within the xy plane

theta_1float

Angle of the MW magnetic field vector with respect to the z axis

phi_r_1float

Azimutal angle of the MW magnetic field vector within the xy plane

units_anglesstr

Units of the angles (deg or rad)

B0_vectornp.ndarray

Unit vector of the static magnetic field in the lab frame

B1_vectornp.ndarray

Unit vector of the MW magnetic field in the lab frame

h1Qobj

Standard microwave Hamiltonian for the P1 center corresponding to the electronic spin transitions.

eigenstatesnp.ndarray

Array containing the eigenstates of the Hamiltonian.

dim_add_spinint

Dimension of the added spin, if any.

Methods

_rot_pas_to_lab()

Defines the rotation matrices to go from the PAS (principal axis system) frame to the lab frame.

electron_zeeman()

Electron Zeeman Hamiltonian term, rotated according to the rotation index r.

hyperfine()

Get the hyperfine term

quadrupole()

Get the quadrupole term

nuclear_zeeman()

Nuclear Zeeman Hamiltonian term

_set_h1()

Sets the standard control Hamiltonian for the P1 center corresponding to the electronic spin transitions.

add_spin(H_spin)

Overwrites the parent class method by calling it and updating the h1 attribute

Notes

The P1 class inherits the methods and attributes from the QSys class.

Constructor for the P1 class. Takes the nitrogen isotope, the rotation index, the magnetic field intensity as inputs and calculates the Hamiltonian with all relevant attributes.

Parameters:
B0float

Magnetic field intensity.

rot_indexint

Rotation index, integer between 0 and 3.

N15 | 14 | 0 | None

Nitrogen isotope, or 0 for no nuclear spin

rho0Qobj | array

Initial state of the system. Can be a Qobj, an array or an index number indicating the system eigenstates

c_opsQobj | list(Qobj)

List of collapse operators

observableQobj | list(Qobj)

Observable to be measured

units_B0str

Units of the magnetic field (T, mT or G)

thetafloat

Angle of the static magnetic field vector with respect to the z axis

phi_rfloat

Azimutal angle of the static magnetic field vector within the xy plane

theta_1float

Angle of the MW magnetic field vector with respect to the z axis

phi_r_1float

Azimutal angle of the MW magnetic field vector within the xy plane

units_anglesstr

Units of the angles (deg or rad)

Methods

add_spin(H_spin)

Overwrites the parent class method by calling it and updating the h1 attribute

electron_zeeman()

Electron Zeeman Hamiltonian term, rotated according to the rotation index r.

hyperfine()

Get the hyperfine term

nuclear_zeeman()

Nuclear Zeeman Hamiltonian term

plot_energy([figsize, energy_lim])

Plots the energy levels of the Hamiltonian defined in the system.

quadrupole()

Get the quadrupole term

truncate(indexes)

Truncantes the quantum system by removing the states specified by the indexes from the Hamiltonian, the initial state, the observable and the collapse operators.

add_spin(H_spin: Qobj) None[source]

Overwrites the parent class method by calling it and updating the h1 attribute

Parameters:
H_spinQobj

Hamiltonian of the extra spin

electron_zeeman() Qobj[source]

Electron Zeeman Hamiltonian term, rotated according to the rotation index r.

Returns:
Zeeman HamiltonianQobj
hyperfine() Qobj[source]

Get the hyperfine term

Returns:
Hyperfine HamiltonianQobj
nuclear_zeeman() Qobj | None[source]

Nuclear Zeeman Hamiltonian term

Returns:
Zeeman HamiltonianQobj
quadrupole() Qobj | int[source]

Get the quadrupole term

Returns:
Quadrupole HamiltonianQobj

SiBi_flux_sys

This module contains a class for modelling a Bismuth atom coupled to a flux superconducting qubit being a subclass of QSys.

This system is the same as used in Tikai Chang et al. ‘Strong coupling of a superconducting flux qubit to single bismuth donors’, Nature Communications 10.1038/s41467-025-64757-5.

class quaccatoo.qsys.SiBi_flux_sys.SiBiFlux(*, rho0: Qobj | None, c_ops: Qobj | list[Qobj] | None = None, observable: Qobj | list[Qobj] | None, flux: bool = True, spin: bool = True, N: bool = False, Delta: float = 0.0, epsilon: float = 0.0, g: float = 0.0, B0: float = 0.0, units_B0: Literal['T', 'mT', 'G'] = 'mT', theta: float = 0.0, phi_r: float = 0.0, units_angles: Literal['rad', 'deg'] = 'deg')[source]

Class for modelling a Bismuth atom coupled to a flux superconducting qubit being a subclass of QSys.

This system is the same as used in Tikai Chang et al. ‘Strong coupling of a superconducting flux qubit to single bismuth donors’, Nature Communications 10.1038/s41467-025-64757-5.

Attributes:
B0float

Intensity of the static magnetic field. Only set if spin is True.

units_B0str

Units of the static magnetic field (T, mT or G). Only set if spin is True.

thetafloat

Polar angle of the static magnetic field vector with respect to the z axis. Only set if spin is True.

phi_rfloat

Azimuthal angle of the static magnetic field vector within the xy plane. Only set if spin is True.

units_anglesstr

Units of the angles (deg or rad). Only set if spin is True.

Nbool

Whether the bismuth nuclear spin (I=9/2) is included in the Hilbert space. Only set if spin is True.

Methods

_get_H_flux(Delta, epsilon)

Calculates and returns the superconducting flux qubit hamiltonian

electron_zeeman()

Calculates and returns the hamiltonian for the electron Zeeman interaction.

nuclear_zeeman()

Calculates the nuclear Zeeman Hamiltonian of the bismuth nuclear Zeeman interaction, with the field orientation set by theta and phi_r, embedded in the electron-nucleus product space through a tensor product with the identity on the electron.

hyperfine()

Calculates the hyperine Hamiltonian of the isotropic contact hyperfine interaction between the donor electron and the bismuth nucleus, acting on the electron-nucleus product space.

Notes

The SiBiFlux class inherits the methods and attributes from the QSys class.

The composite Hilbert space is ordered as flux qubit (dim 2), donor electron spin (dim 2) and, if N is True, bismuth nuclear spin (dim 10). Subsystems absent from the model are omitted from the tensor product instead of being traced over, such that the dimension of H0 depends on the flux, spin and N flags.

Constructor for the SiBiFlux class. Takes the flux qubit parameters and/or the spin.

Parameters:
rho0Qobj or None

Initial state of the system, passed to the QSys constructor.

c_opsQobj or list[Qobj] or None

Collapse operators for the Lindblad master equation, passed to the QSys constructor.

observableQobj or list[Qobj] or None

Observable or list of observables to be measured, passed to the QSys constructor.

fluxbool

Whether the superconducting flux qubit is included in the system.

spinbool

Whether the bismuth donor spin is included in the system.

Nbool

Whether the bismuth nuclear spin (I=9/2) is included, adding the nuclear Zeeman and hyperfine terms to the Hamiltonian. Only used if spin is True.

Deltafloat

Coefficient of the sigma_z term of the flux qubit Hamiltonian, in MHz. Only used if flux is True.

epsilonfloat

Coefficient of the sigma_x term of the flux qubit Hamiltonian, in MHz. Only used if flux is True.

gfloat

Transverse coupling strength between the flux qubit and the donor electron spin, in MHz. Only used if both flux and spin are True.

B0float

Intensity of the static magnetic field. Only used if spin is True.

units_B0str

Units of the static magnetic field (T, mT or G). Only used if spin is True.

thetafloat

Polar angle of the static magnetic field vector with respect to the z axis. Only used if spin is True.

phi_rfloat

Azimuthal angle of the static magnetic field vector within the xy plane. Only used if spin is True.

units_anglesstr

Units of the angles (deg or rad). Only used if spin is True.

Methods

add_spin(H_spin)

Adds another spin to the system's Hamiltonian, given a Hamiltonian for the new spin.

electron_zeeman()

Calculates and returns the hamiltonian for the electron Zeeman interaction.

hyperfine()

Calculates the hyperine Hamiltonian of the isotropic contact hyperfine interaction between the donor electron and the bismuth nucleus, acting on the electron-nucleus product space.

nuclear_zeeman()

Calculates the nuclear Zeeman Hamiltonian of the bismuth nuclear Zeeman interaction, with the field orientation set by theta and phi_r, embedded in the electron-nucleus product space through a tensor product with the identity on the electron.

plot_energy([figsize, energy_lim])

Plots the energy levels of the Hamiltonian defined in the system.

truncate(indexes)

Truncantes the quantum system by removing the states specified by the indexes from the Hamiltonian, the initial state, the observable and the collapse operators.

electron_zeeman() Qobj[source]

Calculates and returns the hamiltonian for the electron Zeeman interaction. If the nuclear spin is present, it performs a tensor product with nuclear spin space.

Returns:
H_ezQobj

Electron Zeeman Hamiltonian

hyperfine() Qobj[source]

Calculates the hyperine Hamiltonian of the isotropic contact hyperfine interaction between the donor electron and the bismuth nucleus, acting on the electron-nucleus product space. The coupling constant A_Bi is 1475.4 MHz, giving the well known 7.377 GHz zero field splitting between the F=4 and F=5 manifolds.

Returns:
H_hfQobj

Hyperfine Hamiltonina

nuclear_zeeman() Qobj[source]

Calculates the nuclear Zeeman Hamiltonian of the bismuth nuclear Zeeman interaction, with the field orientation set by theta and phi_r, embedded in the electron-nucleus product space through a tensor product with the identity on the electron.

Returns:
H_nzQobj

Nuclear Zeeman Hamiltonian

constants

This module collects the physical constants shared by the predefined quantum systems.

All gyromagnetic ratios are given in MHz/mT and all couplings in MHz, matching the default units of the Hamiltonians in QuaCCAToo.

pulsed_sim

This module contains the PulsedSim class that is used to define a general pulsed experiment with a sequence of pulses and free evolution operations, part of the QuaCAAToo package.

class quaccatoo.pulsed_sim.pulsed_sim.PulsedSim(system: QSys, *, H2: tuple[Qobj, Callable] | None = None)[source]

The PulsedSim class is used to define a general pulsed experiment with a sequence of pulses and free evolution operations. The class contains methods to add pulses and free evolution operations to the sequence of operations, run the experiment, plot the pulse profiles and results of the experiment. By default the Hamiltonian is in frequency units and the time is in time units.

Attributes:
systemQSys

Quantum system object representing the quantum system

H2list(Qobj, function)

Time dependent sensing Hamiltonian of the system in the form [Qobj, function]

H0_H2list

List of Hamiltonians for the pulse operation in the form [H0, H2]

total_timefloat

Total time of the experiment

variablenp.array

Variable of the experiment which the results depend on

variable_namestr

Name of the variable

pulse_profiles :list

List of pulse profiles for plotting purposes, where each element is a list [h1, tarray, pulse_shape, pulse_params]

resultslist

Results of the experiment to be later generated in the run method

sequencecallable

Parallel sequence of operations to be overwritten in predef_seqs and predef_dd_seqs, or defined by the user

time_stepsint

Number of time steps for the pulses

rhoQobj

Density matrix of the system

Mint

Order of the sequence, if applicable

pi_pulse_durationfloat

Duration of the pi pulse, if applicable

free_durationnp.array

Free evolution times of the sequence, if applicable

pulse_shapecallable or list(callable)

Pulse shape function or list of pulse shape functions representing the time modulation of h1

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions

optionsdict

Options for the Qutip solver, such as ‘nsteps’, ‘atol’, ‘rtol’, ‘order’

h1Qobj or list(Qobj)

Control Hamiltonian of the system, which can be a single Qobj or a list of Qobjs

Htlist

List of Hamiltonians for the pulse operation in the form [H0, [h1, pulse_shape], H2]

time_stepsint

Number of time steps for the pulses, if applicable

Methods

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

_free_evolution(duration, options)

Updates the total time of the experiment and applies the time-evolution operator to the initial state.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

_delta_pulse(R)

Applies the delta pulse operation to the initial state by multiplying the rho attribute with the rotation operator R.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

_get_results()

Gets the results of the experiment from the calculated rho, based on the observable of the system.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, title])

Plots the pulse profiles of the experiment by iterating over the pulse_profiles list and plotting each pulse profile and free evolution.

_check_attr_predef_seqs(h1, Rx, Ry, ...)

Checks the commom attributes of the PulsedSim object for the predefined sequences and sets them accordingly.

_check_tau(tau)

Check if tau is correctly defined and if it's None, assign to the largest value of the variable attribute

_reset_sequence()

Resets the density matrix to the initial state of the system and the clock of the sequence to zero.

pulse

Updates the total time of the experiment, sets the phase for the pulse and calls mesolve from QuTip to perform the pulse operation

_append_pulse_to_profiles

Appends the pulse profile to the pulse_profiles list, which is used for plotting purposes.

Initializes a general PulsedSim object with a quantum system, time dependent Hamiltonian and collapse operators.

Parameters:
systemQSys

Quantum system object representing the quantum system

H2[Qobj, callable]

Time dependent sensing Hamiltonian of the system

Methods

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, title])

Plots the pulse profiles of the experiment by iterating over the pulse_profiles list and plotting each pulse profile and free evolution.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

add_delta_pulse(R: Qobj) None[source]

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method. For adding a realistic finite length pulse, check add_pulse method.

Parameters:
RQobj

Rotation operator of the delta pulse

add_free_evolution(duration: float, options: dict | None = None) None[source]

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

Parameters:
durationfloat or int

Duration of the free evolution

optionsdict

Options for the Qutip solver

add_pulse(duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj], pulse_shape: ~collections.abc.Callable | list[~collections.abc.Callable] = <function square_pulse>, pulse_params: dict[str, float | int] | None = None, time_steps: int = 100, options: dict | None = None) None[source]

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

Parameters:
durationfloat

Duration of the pulse

h1Qobj or list(Qobj)

Control Hamiltonian of the system

pulse_shapecallable or list(callable)

Pulse shape function or list of pulse shape functions representing the time modulation of t h1

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions

time_stepsint

Number of time steps for the pulses

optionsdict

Options for the Qutip solver

measure_qsys(observable: Qobj | None = None, tol: float | None = None) float | list[float][source]

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable. If no observable is given, the observable of the qsys is used. The rho attribute needs to be normalized before the measurement is performed, in order to avoid numerical errors within the measure_observable method.

Parameters:
observableQobj

Observable to be measured after the sequence of operations

tolfloat

Tolerance for the measurement, smallest value for the probabilities

Returns:
resultsfloat or list

Measurement outcome of the observable, which can be a float or a list of floats if the observable is a list of Qobjs

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str | None = None, ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles') None[source]

Plots the pulse profiles of the experiment by iterating over the pulse_profiles list and plotting each pulse profile and free evolution.

Parameters:
figsizetuple

Size of the figure to be passed to matplotlib.pyplot

xlabelstr

Label of the x-axis

ylabelstr

Label of the y-axis

titlestr

Title of the plot

run(variable: ndarray | list[float | int] | None = None, sequence: Callable | None = None, sequence_kwargs: dict[str, Any] | None = None, map_kw: dict[str, Any] | None = None) None[source]

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute. The rho attribute is updated.

Parameters:
variablenp.array

xaxis variable of the plot representing the parameter being changed in the experiment

sequencecallable

Sequence of operations to be performed in the experiment

sequence_kwargsdict

Dictionary of arguments to be passed to the sequence function

map_kwdict

Dictionary of options for the parallel_map function from QuTip

predef_seqs

This module contains predefined basic pulsed experiments inheriting from the PulsedSim class as part of the QuaCCAToo package.

Classes

  • Rabi: resonant pulse of varying duration, such that the quantum system will undergo periodical transitions between the excited and ground states.

  • PMR: Pulsed Magnetic Resonance (PMR) experiment, composed by a single pulse where the frequency is changed such that when it corresponds to a transition in the Hamiltonian of the system, the observable will be affected.

  • Ramsey: Ramsey experiment, consisting of a free evolution that causes a phase accumulation between states in the system which can be used for interferometry.

  • Hahn: Hahn echo experiment, consisting of two free evolutions with a pi pulse in the middle, in order to cancel out dephasings. The Hahn echo is usually used to measure the coherence time of a quantum system, however it can also be used to sense coupled spins.

  • SpinLocking: spin locking experiment, composed by a pi/2-y pulse to drive the spin to the +X state followed by a pulse along x of varying duration. During the driving, the system is usually in an eigenstate of the driving Hamiltonian.

class quaccatoo.pulsed_sim.predef_seqs.Hahn(free_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, pi_pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj] | None = None, Rx: ~qutip.core.qobj.Qobj | None = None, H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, projection_pulse: bool = True, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None)[source]

A class containing Hahn echo experiments.

The Hahn echo sequence consists of two free evolutions with a pi pulse in the middle, in order to cancel out dephasings. The Hahn echo is usually used to measure the coherence time of a quantum system, however it can also be used to sense coupled spins.

Methods

hahn_sequence(tau)

Defines the Hahn echo sequence for a given free evolution time tau and the set of attributes defined in the constructor.

_get_pulse_profiles([tau])

Generates the pulse profiles for the Hahn echo sequence for a given tau.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the Hahn echo sequence for a given tau and then plot them.

Notes

The Hahn echo sequence inherits the methods and attributes from the PulsedSim class.

Constructor for the Hahn echo pulsed experiment class, taking a specific free_duration to run the simulation.

Parameters:
free_durationnumpy.ndarray

Time array for the simulation representing the free evolution time to be used as the variable attribute for the simulation.

systemQSys

Quantum system object containing the initial state, internal Hamiltonian and collapse operators.

pi_pulse_durationfloat, int or 0

Duration of the pi pulse. If set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator.

h1Qobj or list of Qobj

Control Hamiltonian of the system.

RxQobj or None

Rotation operator around the x-axis, used only if the pi_pulse_duration is set to 0.

H2Qobj or list of Qobj

Time dependent sensing Hamiltonian of the system.

projection_pulsebool

Boolean to determine if the measurement is to be performed in the Sz basis or not. If True, a final pi/2 pulse is included in order to project the result into the Sz basis, as done for the most color centers.

pulse_shapeFunctionType or list of FunctionType

Pulse shape function or list of pulse shape functions representing the time modulation of h1.

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions.

time_stepsint

Number of time steps in the pulses for the simulation.

optionsdict

Dictionary of solver options from Qutip.

Methods

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

hahn_sequence(tau)

Defines the Hahn echo sequence for a given free evolution time tau and the set of attributes defined in the constructor.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the Hahn echo sequence for a given tau and then plot them.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

hahn_sequence(tau: float) Qobj[source]

Defines the Hahn echo sequence for a given free evolution time tau and the set of attributes defined in the constructor. The sequence consists of a pi/2 pulse, a free evolution time tau, a pi pulse and another free evolution time tau followed by a pi/2 pulse, if the projection pulse is set to True. If the pi_pulse_duration is set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator. The sequence is to be called by the parallel_map method of QuTip.

Parameters:
taufloat or int

Free evolution time.

Returns:
rhoQobj

Final state.

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles of Hahn Echo Sequence', tau: float | None = None) None[source]

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the Hahn echo sequence for a given tau and then plot them.

Parameters:
taufloat

Free evolution time for the Hahn echo sequence. Contrary to the run method, the free evolution must be a single number in order to plot the pulse profiles.

class quaccatoo.pulsed_sim.predef_seqs.PMR(frequencies: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj], H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None)[source]

A class containing Pulsed Magnetic Resonance (PMR) experiments where the frequency is the variable being changed.

The PMR consists of a single pulse of fixed length and changing frequency. If the frequency matches a resonance of the system, it will undergo some transition which will affect the observable. This way, the differences between energy levels can be determined with the linewidth usually limited by the pulse length. Here we make reference to optical detection as it is the most common detection scheme of pulsed magnetic resonance in color centers, however the method can be more general.

Attributes:
frequenciesnumpy.ndarray

Array of frequencies to run the simulation.

Methods

PMR_sequence(f)

Defines the Pulsed Magnetic Resonance (PMR) sequence for a given frequency of the pulse.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first define a pulse frequency to be plotted.

Notes

The PMR sequence inherits the methods and attributes from the PulsedSim class.

Constructor for the PMR pulsed experiment class.

Parameters:
frequenciesnumpy.ndarray

Array of frequencies to run the simulation.

systemQSys

Quantum system object containing the initial state, internal Hamiltonian and collapse operators.

pulse_durationfloat or int

Duration of the pulse.

h1Qobj or list(Qobj)

Control Hamiltonian of the system.

H2Qobj or list(Qobj)

Time-dependent sensing Hamiltonian of the system.

pulse_shapeFunctionType or list(FunctionType)

Pulse shape function or list of pulse shape functions representing the time modulation of h1.

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions.

time_stepsint

Number of time steps in the pulses for the simulation.

optionsdict

Dictionary of solver options from Qutip.

Methods

PMR_sequence(f)

Defines the Pulsed Magnetic Resonance (PMR) sequence for a given frequency of the pulse.

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first define a pulse frequency to be plotted.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

PMR_sequence(f: float) Qobj[source]

Defines the Pulsed Magnetic Resonance (PMR) sequence for a given frequency of the pulse. To be called by the parallel_map in run method.

Parameters:
ffloat or int

Frequency of the pulse.

Returns:
rhoQobj

Final state.

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles', f_pulse: float | None = None)[source]

Overwrites the plot_pulses method of the parent class in order to first define a pulse frequency to be plotted.

Parameters:
f_pulsefloat or int

Frequency of the pulse to be plotted.

class quaccatoo.pulsed_sim.predef_seqs.Rabi(pulse_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj], H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, pulse_shape: ~collections.abc.Callable | list[~collections.abc.Callable] = <function square_pulse>, pulse_params: dict[str, float] | None = None, options: dict | None = None)[source]

A class containing Rabi experiments.

A Rabi sequence is composed of a resonant pulse of varying duration, such that the quantum system will undergo periodical transitions between the excited and ground states.

Methods

run()

Overwrites the run method of the parent class.

Notes

The Rabi sequence inherits the methods and attributes from the PulsedSim class.

Constructor for the Rabi pulsed experiment class.

Parameters:
pulse_durationnumpy.ndarray

Time array for the simulation representing the pulse duration to be used as the variable for the simulation.

systemQSys

Quantum system object containing the initial state, internal Hamiltonian and collapse operators.

h1Qobj or list(Qobj)

Control Hamiltonian of the system.

H2Qobj or list(Qobj)

Time-dependent sensing Hamiltonian of the system.

pulse_shapeFunctionType or list(FunctionType)

Pulse shape function or list of pulse shape functions representing the time modulation of h1.

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions.

optionsdict

Dictionary of solver options from Qutip.

Methods

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, title])

Plots the pulse profiles of the experiment by iterating over the pulse_profiles list and plotting each pulse profile and free evolution.

run()

Overwrites the run method of the parent class.

run() None[source]

Overwrites the run method of the parent class. Runs the simulation and stores the results in the results attribute. If the system has no initial state, the propagator is calcualated. If an observable is given, the expectation values are stored in the results attribute. For the Rabi sequence, the calculation is optimally performed sequentially instead of in parallel over the pulse lengths, thus the run method from the parent class is overwritten.

class quaccatoo.pulsed_sim.predef_seqs.Ramsey(free_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, pi_pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj] | None = None, Rx: ~qutip.core.qobj.Qobj | None = None, H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, projection_pulse: bool = True, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None)[source]

A class containing Ramsey experiments.

The Ramsey sequence consists of a free evolution in the plane perpendicular to the quantization axis, which causes a phase accumulation between states in the system which can be used for sensing.

Methods

ramsey_sequence(tau)

Defines the Ramsey sequence for a given free evolution time tau and the set of attributes defined in the constructor.

_get_pulse_profiles([tau])

Generates the pulse profiles for the Ramsey sequence for a given tau.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the Ramsey sequence for a given tau and then plot them.

Notes

The Ramsey sequence inherits the methods and attributes from the PulsedSim class.

Class constructor for the Ramsey pulsed experiment class.

Parameters:
free_durationnumpy.ndarray

Time array for the simulation representing the free evolution time to be used as the variable attribute for the simulation.

systemQSys

Quantum system object containing the initial state, internal Hamiltonian and collapse operators.

pi_pulse_durationfloat, int or 0

Duration of the pi pulse. If set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator.

h1Qobj or list(Qobj)

Control Hamiltonian of the system.

RxQobj or None

Rotation operator around the x-axis, used only if the pi_pulse_duration is set to 0.

pi_pulse_durationfloat or int

Duration of the pi pulse.

H2Qobj or list(Qobj)

Time-dependent sensing Hamiltonian of the system.

projection_pulsebool

Boolean to determine if the measurement is to be performed in the Sz basis or not. If True, a final pi/2 pulse is included in order to project the result into the Sz basis, as for most color centers.

pulse_shapeFunctionType or list(FunctionType)

Pulse shape function or list of pulse shape functions representing the time modulation of h1.

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions.

time_stepsint

Number of time steps in the pulses for the simulation.

optionsdict

Dictionary of solver options from Qutip.

Methods

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the Ramsey sequence for a given tau and then plot them.

ramsey_sequence(tau)

Defines the Ramsey sequence for a given free evolution time tau and the set of attributes defined in the constructor.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles of Ramsey Sequence', tau: float | None = None) None[source]

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the Ramsey sequence for a given tau and then plot them.

Parameters:
taufloat

Free evolution time for the Hahn echo sequence. Contrary to the run method, the free evolution must be a single number in order to plot the pulse profiles.

ramsey_sequence(tau: float) Qobj[source]

Defines the Ramsey sequence for a given free evolution time tau and the set of attributes defined in the constructor. The sequence consists of an initial pi/2 pulse and a single free evolution. If the projection_pulse is set to True, a final pi/2 pulse is included in order to project the result into the Sz basis. If the pi_pulse_duration is set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator. The sequence is to be called by the parallel_map method of QuTip.

Parameters:
taufloat or int

Free evolution time.

Returns:
rhoQobj

Final state.

class quaccatoo.pulsed_sim.predef_seqs.SpinLocking(pulse_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, pi_pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj] | None = None, Ry: ~qutip.core.qobj.Qobj | None = None, H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, projection_pulse: bool = True, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None)[source]

A class containing a spin locking experiment.

A spin locking is composed by a pi/2-y pulse to drive the spin to the +X state followed by a pulse along x of varying duration. During the driving, the system is usually in an eigenstate of the driving Hamiltonian.

Methods

spin_locking_sequence(tp)

Defines the spin locking sequence for a given pulse duration and the set of attributes defined in the constructor.

_get_pulse_profiles([tp])

Generates the pulse profiles for the spin locking sequence for a given pulse duration.

plot_pulses([figsize, xlabel, ylabel, title, tp])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the spin locking sequence for a given pulse duration and then plot them.

Notes

The SpinLocking class inherits the methods and attributes from the PulsedSim class.

Constructor for the spin locking pulsed experiment class, taking a specific pulse_duration to run the simulation.

Parameters:
pulse_durationnumpy.ndarray

Time array for the simulation representing the pulse duration to be used as the variable attribute for the simulation.

systemQSys

Quantum system object containing the initial state, internal Hamiltonian and collapse operators.

pi_pulse_durationfloat

Duration of the pi pulse. If set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator.

h1Qobj or list of Qobj

Control Hamiltonian of the system. Contrary to the other sequences, h1 is required even when pi_pulse_duration is 0, as it defines the locking Hamiltonian.

RyQobj or None

Rotation operator around the y-axis, used only if the pi_pulse_duration is set to 0.

H2Qobj or list of Qobj

Time dependent sensing Hamiltonian of the system.

projection_pulsebool

Boolean to determine if the measurement is to be performed in the Sz basis or not. If True, a final pi/2 pulse is included in order to project the result into the Sz basis, as done for the most color centers.

pulse_shapeFunctionType or list of FunctionType

Pulse shape function or list of pulse shape functions representing the time modulation of h1.

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions.

time_stepsint

Number of time steps in the pulses for the simulation.

optionsdict

Dictionary of solver options from Qutip.

Methods

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, title, tp])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the spin locking sequence for a given pulse duration and then plot them.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

spin_locking_sequence(tp)

Defines the spin locking sequence for a given pulse duration and the set of attributes defined in the constructor.

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles of the Spin Locking Sequence', tp: float | None = None) None[source]

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the spin locking sequence for a given pulse duration and then plot them.

Parameters:
tpfloat

Pulse duration. Contrary to the run method, the pulse duration must be a single number in order to plot the pulse profiles.

spin_locking_sequence(tp: float) Qobj[source]

Defines the spin locking sequence for a given pulse duration and the set of attributes defined in the constructor. The sequence consists of a pi/2-y pulse, a pulse of varying duration along x and a final pi/2-y pulse if the projection pulse is set to True. If the pi_pulse_duration is set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator. The sequence is to be called by the parallel_map method of QuTip.

Parameters:
tpfloat

Pulse duration.

Returns:
rhoQobj

Final state.

predef_dd_seqs

This module contains dynamical decoupling pulse sequences, used in quantum sensing and for extending coherence of quantum systems.

class quaccatoo.pulsed_sim.predef_dd_seqs.CPMG(free_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, M: int, pi_pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj] | None = None, Rx: ~qutip.core.qobj.Qobj | None = None, Ry: ~qutip.core.qobj.Qobj | None = None, H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, projection_pulse: bool = True, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None)[source]

This class contains a Carr-Purcell-Meiboom-Gill sequence used in quantum sensing experiments.

The CPMG sequence consists of a series of pi pulses and free evolution times, such that these periodicals inversions will cancel out oscillating noises except for frequencies corresponding to the pulse separation.

Methods

CPMG_sequence(tau)

Defines the CPMG sequence for a given free evolution time tau and the set of attributes defined in the constructor.

_get_pulse_profiles([tau])

Generates the pulse profiles for the CPMG sequence for a given tau.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the CPMG sequence for a given tau and then plot them.

Notes

The CPMG sequence inherits the methods and attributes from the PulsedSim class.

Class constructor for the Carr-Purcell-Meiboom-Gill sequence

Parameters:
free_durationnumpy array

Time array for the simulation representing the free evolution time to be used as the variable attribute for the simulation

systemQSys

Quantum system object containing the initial state, internal time independent Hamiltonian and collapse operators

Mint

Order of the CPMG sequence

pi_pulse_durationfloat, int or 0

Duration of the pi pulse. If set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator.

h1Qobj or list of Qobj

Control Hamiltonian of the system.

RxQobj or None

Rotation operator around the x-axis, used only if the pi_pulse_duration is set to 0.

RyQobj or None

Rotation operator around the y-axis, used only if the pi_pulse_duration is set to 0.

H2list(Qobj or function)

Time dependent sensing Hamiltonian of the system

projection_pulsebool

Boolean to determine if a final pi/2 pulse is to be included in order to project the measurement into the Sz basis

pulse_shapeFunctionType or list(FunctionType)

Pulse shape function or list of pulse shape functions representing the time modulation of h1

pulse_paramsdict

Dictionary of parameters for the pulse_shape functions

time_stepsint

Number of time steps in the pulses for the simulation

Methods

CPMG_sequence(tau)

Defines the CPMG sequence for a given free evolution time tau and the set of attributes defined in the constructor.

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the CPMG sequence for a given tau and then plot them.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

CPMG_sequence(tau: float) Qobj[source]

Defines the CPMG sequence for a given free evolution time tau and the set of attributes defined in the constructor. The sequence consists of an initial pi/2 pulse, and M pi-pulses separated by free evolution time tau. If projection_pulse is True, the sequence will include a final pi/2 pulse on Y axis to project the measurement into the Sz basis. If the pi_pulse_duration is set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator. The sequence is to be called by the parallel_map method of QuTip.

Parameters:
taufloat

Free evolution time

Returns:
rhoQobj

Final state

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles of XY8 Sequence', tau: float | None = None) None[source]

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the CPMG sequence for a given tau and then plot them.

Parameters:
taufloat

Free evolution time for the sequence. Contrary to the run method, tau must be a single number in order to plot the pulse profiles.

class quaccatoo.pulsed_sim.predef_dd_seqs.XY(free_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, M: int, pi_pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj] | None = None, Rx: ~qutip.core.qobj.Qobj | None = None, Ry: ~qutip.core.qobj.Qobj | None = None, H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, projection_pulse: bool = True, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None)[source]

This class contains the XY-M pulse sequence.

The sequence is composed of intercalated X and Y pi pulses and free evolutions repeated M times. It acts similar to the CPMG sequence, but the alternation of the pulse improves noise suppression on different axis. The initial and final pi/2 pulses are played on the Y axis, while the refocusing pi pulses alternate between X and Y.

Methods

XY_sequence(tau)

Defines the XY-M composed of intercalated pi pulses on X and Y axis with free evolutions of time tau repeated M times.

_get_pulse_profiles([tau])

Generates the pulse profiles for the XY-M sequence for a given tau.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the XY-M sequence for a given tau and then plot them.

Notes

The XY sequence inherits the methods and attributes from the PulsedSim class.

On the phase convention of the pi/2 pulses: contrary to the XY8 sequence implemented in this module, which prepares and projects along X, the XY-M sequence here prepares and projects along Y. This is deliberate and must not be “harmonized” with XY8. Differently from XY8, whose eight pulse phase pattern is reproduced consistently across the literature, the plain XY-M sequence is not standardized in the field, with the axis of the initial pi/2 pulse varying between references. The convention used here is the one of the experimental setup the sequence was written for, and published results were obtained with it. The choice is not merely cosmetic, as the phase of the preparation pulse relative to the refocusing pulses determines whether the prepared state is locked along a refocusing axis, which changes how sensitive the sequence is to pulse errors.

Class constructor for the XY sequence

Parameters:
free_durationnumpy array

Time array for the simulation representing the free evolution time to be used as the variable attribute for the simulation

systemQSys

Quantum system object containing the initial state, internal time independent Hamiltonian and collapse operators

Mint

Order of the XY sequence

pi_pulse_durationfloat, int or 0

Duration of the pi pulse. If set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator.

h1Qobj or list of Qobj

Control Hamiltonian of the system.

RxQobj or None

Rotation operator around the x-axis, used only if the pi_pulse_duration is set to 0.

RyQobj or None

Rotation operator around the y-axis, used only if the pi_pulse_duration is set to 0.

H2Qobj, list(Qobj), optional

Time dependent sensing Hamiltonian of the system

pulse_shapeFunctionType, list(FunctionType), optional

Pulse shape function or list of pulse shape functions representing the time modulation of h1

pulse_paramsdict, optional

Dictionary of parameters for the pulse_shape functions

time_stepsint, optional

Number of time steps in the pulses for the simulation

optionsdict, optional

Dictionary of solver options

Methods

XY_sequence(tau)

Defines the XY-M composed of intercalated pi pulses on X and Y axis with free evolutions of time tau repeated M times.

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the XY-M sequence for a given tau and then plot them.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

XY_sequence(tau: float) Qobj[source]

Defines the XY-M composed of intercalated pi pulses on X and Y axis with free evolutions of time tau repeated M times. The sequence starts with a pi/2 pulse on the Y axis, see the note on the phase convention in the class docstring. If projection_pulse is True, the sequence will include a final pi/2 pulse on Y axis to project the measurement into the Sz basis. If the pi_pulse_duration is set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator. The sequence is to be called by the parallel_map method of QuTip.

Parameters:
taufloat

Free evolution time

Returns:
rhoQobj

Final state

plot_pulses(figsize: tuple[int, int] = (6, 6), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles of XY8 Sequence', tau: float | None = None) None[source]

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the XY-M sequence for a given tau and then plot them.

Parameters:
taufloat

Free evolution time for the sequence. Contrary to the run method, tau must be a single number in order to plot the pulse profiles.

class quaccatoo.pulsed_sim.predef_dd_seqs.XY8(free_duration: ~numpy.ndarray | list[float], *, system: ~quaccatoo.qsys.qsys.QSys, M: int, pi_pulse_duration: float, h1: ~qutip.core.qobj.Qobj | list[~qutip.core.qobj.Qobj] | None = None, Rx: ~qutip.core.qobj.Qobj | None = None, Ry: ~qutip.core.qobj.Qobj | None = None, H2: tuple[~qutip.core.qobj.Qobj, ~collections.abc.Callable] | None = None, projection_pulse: bool = True, pulse_shape: ~collections.abc.Callable = <function square_pulse>, pulse_params: dict[str, float] | None = None, time_steps: int = 100, options: dict | None = None, RXY8: bool = False, seed: int | None = None)[source]

This contains the XY8-M sequence.

The XY8-M is a further improvement from the XY-M sequence, where the X and Y pulses are group antisymmetrically in pairs of 4 as X-Y-X-Y-Y-X-Y-X, in order to improve noise suppression and pulse errors.

Methods

_get_pulse_profiles([tau])

Generates the pulse profiles for the XY8-M sequence for a given tau.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the XY8-M sequence for a given tau and then plot them.

XY_sequence

Defines the XY8-M sequence for a given free evolution time tau and the set of attributes defined in the constructor, returning the final state. The sequence is to be called by the parallel_map method of QuTip.

Notes

The XY8 sequence inherits the methods and attributes from the PulsedSim class.

Class constructor for the XY8 sequence

Parameters:
free_durationnumpy array

Time array for the simulation representing the free evolution time to be used as the variable attribute for the simulation

systemQSys

Quantum system object containing the initial state, internal time independent Hamiltonian and collapse operators

Mint

Order of the XY sequence

pi_pulse_durationfloat, int or 0

Duration of the pi pulse. If set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator.

h1Qobj or list of Qobj

Control Hamiltonian of the system.

RxQobj or None

Rotation operator around the x-axis, used only if the pi_pulse_duration is set to 0.

RyQobj or None

Rotation operator around the y-axis, used only if the pi_pulse_duration is set to 0.

H2Qobj, list(Qobj), optional

Time dependent sensing Hamiltonian of the system

pulse_shapeFunctionType, list(FunctionType), optional

Pulse shape function or list of pulse shape functions representing the time modulation of h1

pulse_paramsdict, optional

Dictionary of parameters for the pulse_shape functions

time_stepsint, optional

Number of time steps in the pulses for the simulation

optionsdict, optional

Dictionary of solver options from Qutip

projection_pulsebool

Boolean to determine if a final pi/2 pulse is to be included in order to project the measurement into the Sz basis

RXY8bool

Boolen to determine if a random phase is to be added to each XY8 block

seedint or None

Seed for the random phases of the RXY8 sequence, so that the simulation is reproducible. Only used if RXY8 is True.

Methods

XY8_sequence(tau)

Defines the XY8-M composed of 8 intercalated pi pulses on X and Y axis with free evolutions of time tau repeated M times.

add_delta_pulse(R)

Adds a delta pulse with zero duration to the sequence of operations of the experiment by calling _delta_pulse method.

add_free_evolution(duration[, options])

Adds a free evolution operation to the sequence of operations of the experiment for a given duration of the free evolution by calling the _free_evolution method.

add_pulse(duration, h1, pulse_shape, ...)

Perform variables checks and adds a pulse operation to the sequence of operations of the experiment for a given duration of the pulse, control Hamiltonian h1, pulse phase, pulse shape function, pulse parameters and time steps by calling the pulse method.

measure_qsys([observable, tol])

Measures the observable over the system, storing the measurent outcome in the results attribute and collapsing rho in the corresponding eigenstate of the observable.

plot_pulses([figsize, xlabel, ylabel, ...])

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the XY8-M sequence for a given tau and then plot them.

run([variable, sequence, sequence_kwargs, ...])

Runs the pulsed experiment by calling the parallel_map function from QuTip over the variable attribute.

XY8_sequence(tau: float) Qobj[source]

Defines the XY8-M composed of 8 intercalated pi pulses on X and Y axis with free evolutions of time tau repeated M times. If random_phase is set to True, a random phase is added in each XY8 block. If projection_pulse is True, the sequence will include a final pi/2 pulse on X axis to project the measurement into the Sz basis. If the pi_pulse_duration is set to 0, the pulses are perfect delta pulses and the time-evolution is calculated with the rotation operator. The sequence is to be called by the parallel_map method of QuTip.

Parameters:
taufloat

Free evolution time

Returns:
rhoQobj

Final state

plot_pulses(figsize: tuple[int, int] = (6, 4), xlabel: str = 'Time', ylabel: str = 'Pulse Intensity', title: str = 'Pulse Profiles of XY8 Sequence', tau: float | None = None) None[source]

Overwrites the plot_pulses method of the parent class in order to first generate the pulse profiles for the XY8-M sequence for a given tau and then plot them.

Parameters:
taufloat

Free evolution time for the sequence. Contrary to the run method, tau must be a single number in order to plot the pulse profiles.

pulse_shapes

This module contains pulse shape functions to be used in the PulsedSim classes as part of the QuaCAAToo package.

quaccatoo.pulsed_sim.pulse_shapes.gaussian_pulse(t: ndarray, **pulse_params: dict[str, float]) ndarray[source]

Gaussian pulse envelope modulation

Parameters:
tarray_like

Time parameter

t_midfloat

Middle point of the pulse

sigmafloat

Width of the pulse

f_pulsefloat

Frequency of the pulse

phi_tfloat

Phase of the pulse

Returns:
float

Value of the Gaussian pulse at time t

quaccatoo.pulsed_sim.pulse_shapes.lorentzian_pulse(t: ndarray, **pulse_params: dict[str, float]) ndarray[source]

Lorentzian pulse envelope modulation

Parameters:
tarray_like

Time parameter

t_midfloat

Middle point of the pulse

gammafloat

Width of the pulse

f_pulsefloat

Frequency of the pulse

phi_tfloat

Phase of the pulse

Returns:
float

Value of the Lorentzian pulse at time t

quaccatoo.pulsed_sim.pulse_shapes.square_pulse(t: ndarray, **pulse_params: dict[str, float]) ndarray[source]

Square pulse envelope modulation

Parameters:
tarray_like

Time parameter

f_pulsefloat

Frequency of the pulse

phi_tfloat

Phase of the pulse

Returns:
float

Value of the square pulse at time t

analysis

This module contains the Analysis class and the plot_histogram method.

class quaccatoo.analysis.analysis.Analysis(experiment: ExpData | PulsedSim)[source]

The Analysis class contains several methods for data Analysis, such as FFT, fitting and plotting.

Attributes:
experimentPulsedSim or ExpData

Experiment object to be analyzed containing the results and variable attributes

FFT_valuestuple

Tuple with the frequency values and the FFT values

FFT_peaksarray

Array with the peaks of the FFT values

fit_modellmfit.Model or list(lmfit.Model)

List with the fitting model for each result

fit_paramslist

List with the fitted parameters for each result

fit_covlist

List with the covariance of the fitted parameters for each result

pearsonscipy result or None

Result of the linear regression or of the Pearson correlation between two experiments, as returned by scipy. None if compare_with was not run yet.

exp_comparisonPulsedSim or ExpData

Experiment to be compared with the first one. The object itself is never modified.

comparison_resultsnp.ndarray

Results of the comparison experiment, rescaled by the linear fit if one was performed

Methods

compare_with(exp_comparison[, ...])

Loads a second experiment to compare with the first one.

plot_comparison([figsize, xlabel, ylabel, title])

Plots the results of the experiment and the comparison experiment.

run_FFT()

Run the real fast Fourier transform for the results and variable attributes of the PulsedSimulation object.

get_peaks_FFT(**find_peaks_kwargs)

Find the peaks of the FFT values calculated by the run_FFT method.

plot_FFT([freq_lim, figsize, xlabel, ...])

Plots the FFT

run_fit(fit_model[, results_index, guess])

Run the fit method from lmfit to fit the results of the experiment with a given model, guess for the initial parameters.

plot_fit([figsize, xlabel, ylabel, title])

Plot the results of the experiment with the fitted function.

plot_results([figsize, xlabel, ylabel, title])

Plots the results of the experiment

plot_bloch([figsize])

Plot the results of the experiment in a Bloch sphere if the quantum system has dimension of two.

Class constructor for Analysis. It takes a PulsedSim or ExpData object as input and checks if the results and variable attributes are not empty and have the same length.

Parameters:
experimentPulsedSim or ExpData

Experiment object to be analyzed containing the results and variable attributes

Methods

compare_with(exp_comparison[, ...])

Loads a second experiment to compare with the first one.

get_peaks_FFT(**find_peaks_kwargs)

Find the peaks of the FFT values calculated by the run_FFT method.

plot_FFT([freq_lim, figsize, xlabel, ...])

Plots the FFT

plot_bloch([figsize])

Plot the results of the experiment in a Bloch sphere if the quantum system has dimension of two.

plot_comparison([figsize, xlabel, ylabel, title])

Plots the results of the experiment and the comparison experiment.

plot_fit([figsize, xlabel, ylabel, title])

Plot the results of the experiment with the fitted function.

plot_results([figsize, xlabel, ylabel, title])

Plots the results of the experiment

run_FFT()

Run the real fast Fourier transform for the results and variable attributes of the PulsedSimulation object.

run_fit(fit_model[, results_index, guess])

Run the fit method from lmfit to fit the results of the experiment with a given model, guess for the initial parameters.

compare_with(exp_comparison: ExpData | PulsedSim, results_index: int = 0, comparison_index: int = 0, linear_fit: bool = True) float[source]

Loads a second experiment to compare with the first one. If linear_fit is True, a linear fit is performed between the two data sets, which is common for optical experiments. Otherwise the Pearson correlation coefficient without linear fit is calculated between the two data sets.

Parameters:
exp_comparisonPulsedSim or ExpData

Experiment to be compared with the first one

results_indexint

Index of the results to be compared if the results attribute is a list

comparison_indexint

Index of the results to be compared if the results attribute of the exp_comparison is a list

linear_fitbool

Boolean indicating whether or not to perform a linear fit between the two data sets

Returns:
rfloat

Pearson correlation coefficient between the two experiments

get_peaks_FFT(**find_peaks_kwargs: Any) ndarray[source]

Find the peaks of the FFT values calculated by the run_FFT method.

Parameters:
find_peaks_kwargsdict

Dictionary with the arguments to be passed to the scipy.signal.find_peaks function

Returns:
FFT_peaksarray

Array with the peaks of the FFT values

plot_FFT(freq_lim: tuple[float, float] | None = None, figsize: tuple[int, int] = (6, 4), xlabel: str | None = None, ylabel: str = 'FFT Intensity', title: str = 'FFT of the Results') None[source]

Plots the FFT

Parameters:
figsizetuple

Size of the figure to be passed to matplotlib.pyplot

xlabelstr

Label of the x-axis

ylabelstr

Label of the y-axis

titlestr

Title of the plot

plot_bloch(figsize: tuple[int, int] = (6, 4)) None[source]

Plot the results of the experiment in a Bloch sphere if the quantum system has dimension of two.

Parameters:
figsizetuple

Size of the figure to be passed to matplotlib.pyplot

plot_comparison(figsize: tuple[int, int] = (6, 4), xlabel: str | None = None, ylabel: str = 'Observable', title: str = 'Results Comparisons') None[source]

Plots the results of the experiment and the comparison experiment.

Parameters:
figsizetuple

Size of the figure to be passed to matplotlib.pyplot

xlabelstr

Label of the x-axis

ylabelstr

Label of the y-axis

titlestr

Title of the plot

plot_fit(figsize: tuple[int, int] = (6, 4), xlabel: str | None = None, ylabel: str = 'Expectation Value', title: str = 'Pulsed Result') None[source]

Plot the results of the experiment with the fitted function.

Parameters:
figsizetuple

Size of the figure to be passed to matplotlib.pyplot

xlabelstr

Label of the x-axis

ylabelstr

Label of the y-axis

titlestr

Title of the plot

plot_results(figsize: tuple[int, int] = (6, 4), xlabel: str | None = None, ylabel: str = 'Observable', title: str = 'Results') None[source]

Plots the results of the experiment

Parameters:
figsizetuple

Size of the figure to be passed to matplotlib.pyplot

xlabelstr

Label of the x-axis

ylabelstr

Label of the y-axis

titlestr

Title of the plot

run_FFT() None[source]

Run the real fast Fourier transform for the results and variable attributes of the PulsedSimulation object. The results are centered around the mean value before the FFT is calculated in order to remove the DC component.

Returns:
FFT_valuestuple

Tuple with the frequency values and the FFT values

run_fit(fit_model: Model, results_index: int = 0, guess: dict | None = None) dict[source]

Run the fit method from lmfit to fit the results of the experiment with a given model, guess for the initial parameters.

Parameters:
fit_modellmfit.Model

Model to be used to fit the results

results_indexint

Index of the results to be fitted if the results attribute is a list

guessdict

Initial guess for the parameters of the model Takes a dictionary consisting of parameter names as the keys and their initial guess as the value. See the definitions of the models in the fit_functions.py file for details.

Returns:
fit_paramsdict

best fit parameter values of parameters as a dict with the parameter names as the keys

Examples

The typical usage scheme is to pass a model and optionally, a dictionary of initial values. The file fit_functions.py includes a bunch of predefined models and imports some commonly needed ones from lmfit which can be directly passed to the function and used. Alternatively, the Model function from lmfit takes a custom Python function and instantiates a model class object with it, which can then be used here.

>>> from lmfit import Model #needed for custom models
>>> # my_analysis_obj is an instance of the analysis class
>>> my_analysis_obj.run_fit(fit_model=RabiModel())
>>> my_analysis_obj.run_fit(
        fit_model=Model(fit_two_lorentz_sym),
        guess = {'A': 0.5, 'gamma': 0.2, 'f_mean':1749, 'f_delta':3,'C':1}
        )

In the snippet above, we showcase some ways to perform fits using this method. Using predefined models takes care of most of the stuff. One can still pass a guess dictionary to provide better initial values. The second example shows the usage with a custom model instantiated from a function along with user provided guesses. It’s important to note that the first parameter of these custom functions should be x. Moreover, the keys in the dictionary should correspond to the other parameters of the function (this holds true for the predefined models as well). The names of the parameters can be referred to from the source file (fit_functions.py).

quaccatoo.analysis.analysis.plot_histogram(rho: Qobj | ndarray, rho_comparison: Qobj | ndarray | None = None, component: Literal['real', 'imag', 'abs'] = 'real', figsize: tuple[int, int] = (5, 5), title: str = 'Matrix Histogram') None[source]

Plot a 3D histogram of the final density matrix of the simulation.

Parameters:
rhoQobj

A Qobj representing a density matrix to be plotted

rho_comparisonQobj, optional

A Qobj representing a density matrix to be compared with

componentstr

Component of the density matrix to be plotted. Can be ‘real’, ‘imag’, or ‘abs’.

figsizetuple

Size of the figure to be passed to matplotlib.pyplot

titlestr

Title of the plot

fit_functions

Collection of in built fit models and functions.

The predefined model classes take a (fit) function and implement a guess subroutine for intelligent initial values.

The general mechanism is the same as that of lmfit. So a lot of functions have been taken from there. To create additional fit models, simply instantiate an lmfit model with the target fit function.

Refer to the documentation of analysis.run_fit for usage details.

class quaccatoo.analysis.fit_functions.ConstantModel(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

Constant model, with a single Parameter: c.

Note that this is ‘constant’ in the sense of having no dependence on the independent variable x, not in the sense of being non-varying. To be clear, c will be a Parameter that will be varied in the fit (by default, of course).

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data[, x])

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Parameters:
independent_varslist of str, optional

Arguments to the model function that are independent variables default is [‘x’]).

prefixstr, optional

String to prepend to parameter names, needed to add two Models that have parameter names in common.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

How to handle NaN and missing values in data. See Notes below.

**kwargsoptional

Keyword arguments to pass to Model.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data[, x])

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Notes

1. nan_policy sets what to do when a NaN or missing value is seen in the data. Should be one of:

  • ‘raise’ : raise a ValueError (default)

  • ‘propagate’ : do nothing

  • ‘omit’ : drop missing data

guess(data, x=None, **kwargs)[source]

Guess starting values for the parameters of a model.

Parameters:
dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

Returns:
paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

class quaccatoo.analysis.fit_functions.ExpDecayModel(independent_vars: list[str] | None = None, prefix: str = '', nan_policy: str = 'raise', **kwargs: Any)[source]

Modified from lmfit’s ExponentialModel to include an offset as well

Takes the same parameters as the fit_exp_decay function.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

class quaccatoo.analysis.fit_functions.ExponentialModel(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

A model based on an exponential decay function.

The model has two Parameters: amplitude (\(A\)) and decay (\(\tau\)) and is defined as:

\[f(x; A, \tau) = A e^{-x/\tau}\]

For more information, see: https://en.wikipedia.org/wiki/Exponential_decay

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Parameters:
independent_varslist of str, optional

Arguments to the model function that are independent variables default is [‘x’]).

prefixstr, optional

String to prepend to parameter names, needed to add two Models that have parameter names in common.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

How to handle NaN and missing values in data. See Notes below.

**kwargsoptional

Keyword arguments to pass to Model.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Notes

1. nan_policy sets what to do when a NaN or missing value is seen in the data. Should be one of:

  • ‘raise’ : raise a ValueError (default)

  • ‘propagate’ : do nothing

  • ‘omit’ : drop missing data

guess(data, x, **kwargs)[source]

Guess starting values for the parameters of a model.

Parameters:
dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

Returns:
paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

class quaccatoo.analysis.fit_functions.GaussianModel(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

A model based on a Gaussian or normal distribution lineshape.

The model has three Parameters: amplitude, center, and sigma. In addition, parameters fwhm and height are included as constraints to report full width at half maximum and maximum peak height, respectively.

\[f(x; A, \mu, \sigma) = \frac{A}{\sigma\sqrt{2\pi}} e^{[{-{(x-\mu)^2}/{{2\sigma}^2}}]}\]

where the parameter amplitude corresponds to \(A\), center to \(\mu\), and sigma to \(\sigma\). The full width at half maximum is \(2\sigma\sqrt{2\ln{2}}\), approximately \(2.3548\sigma\).

For more information, see: https://en.wikipedia.org/wiki/Normal_distribution

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x[, negative])

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Parameters:
independent_varslist of str, optional

Arguments to the model function that are independent variables default is [‘x’]).

prefixstr, optional

String to prepend to parameter names, needed to add two Models that have parameter names in common.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

How to handle NaN and missing values in data. See Notes below.

**kwargsoptional

Keyword arguments to pass to Model.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x[, negative])

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Notes

1. nan_policy sets what to do when a NaN or missing value is seen in the data. Should be one of:

  • ‘raise’ : raise a ValueError (default)

  • ‘propagate’ : do nothing

  • ‘omit’ : drop missing data

fwhm_factor = np.float64(2.3548200450309493)
height_factor = np.float64(0.3989422804014327)
guess(data, x, negative=False, **kwargs)[source]

Guess starting values for the parameters of a model.

Parameters:
dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

Returns:
paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

class quaccatoo.analysis.fit_functions.LinearModel(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

Linear model, with two Parameters: intercept and slope.

Defined as:

\[f(x; m, b) = m x + b\]

with slope for \(m\) and intercept for \(b\).

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Parameters:
independent_varslist of str, optional

Arguments to the model function that are independent variables default is [‘x’]).

prefixstr, optional

String to prepend to parameter names, needed to add two Models that have parameter names in common.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

How to handle NaN and missing values in data. See Notes below.

**kwargsoptional

Keyword arguments to pass to Model.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Notes

1. nan_policy sets what to do when a NaN or missing value is seen in the data. Should be one of:

  • ‘raise’ : raise a ValueError (default)

  • ‘propagate’ : do nothing

  • ‘omit’ : drop missing data

guess(data, x, **kwargs)[source]

Guess starting values for the parameters of a model.

Parameters:
dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

Returns:
paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

class quaccatoo.analysis.fit_functions.LorentzianModel(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

A model based on a Lorentzian or Cauchy-Lorentz distribution function.

The model has three Parameters: amplitude, center, and sigma. In addition, parameters fwhm and height are included as constraints to report full width at half maximum and maximum peak height, respectively.

\[f(x; A, \mu, \sigma) = \frac{A}{\pi} \big[\frac{\sigma}{(x - \mu)^2 + \sigma^2}\big]\]

where the parameter amplitude corresponds to \(A\), center to \(\mu\), and sigma to \(\sigma\). The full width at half maximum is \(2\sigma\).

For more information, see: https://en.wikipedia.org/wiki/Cauchy_distribution

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x[, negative])

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Parameters:
independent_varslist of str, optional

Arguments to the model function that are independent variables default is [‘x’]).

prefixstr, optional

String to prepend to parameter names, needed to add two Models that have parameter names in common.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

How to handle NaN and missing values in data. See Notes below.

**kwargsoptional

Keyword arguments to pass to Model.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x[, negative])

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Notes

1. nan_policy sets what to do when a NaN or missing value is seen in the data. Should be one of:

  • ‘raise’ : raise a ValueError (default)

  • ‘propagate’ : do nothing

  • ‘omit’ : drop missing data

guess(data, x, negative=False, **kwargs)[source]

Guess starting values for the parameters of a model.

Parameters:
dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

Returns:
paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

class quaccatoo.analysis.fit_functions.RabiModel(independent_vars: list[str] | None = None, prefix: str = '', nan_policy: str = 'raise', **kwargs: Any)[source]

Modified from lmfit’s SineModel to include an offset as well

Takes the same parameters as the fit_rabi function.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

class quaccatoo.analysis.fit_functions.SineModel(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

A model based on a sinusoidal lineshape.

The model has three Parameters: amplitude, frequency, and shift.

\[f(x; A, \phi, f) = A \sin (f x + \phi)\]

where the parameter amplitude corresponds to \(A\), frequency to \(f\), and shift to \(\phi\). All are constrained to be non-negative, and shift additionally to be smaller than \(2\pi\).

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Parameters:
independent_varslist of str, optional

Arguments to the model function that are independent variables default is [‘x’]).

prefixstr, optional

String to prepend to parameter names, needed to add two Models that have parameter names in common.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

How to handle NaN and missing values in data. See Notes below.

**kwargsoptional

Keyword arguments to pass to Model.

Attributes:
components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

Methods

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

Load JSON representation of Model from a file-like object.

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Notes

1. nan_policy sets what to do when a NaN or missing value is seen in the data. Should be one of:

  • ‘raise’ : raise a ValueError (default)

  • ‘propagate’ : do nothing

  • ‘omit’ : drop missing data

guess(data, x, **kwargs)[source]

Guess starting values for the parameters of a model.

Parameters:
dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

Returns:
paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

quaccatoo.analysis.fit_functions.fit_exp_decay(x: ndarray, amp: float = 1, Tc: float = 1, offset: float = 0) ndarray[source]

Fit a simple exponential decay function.

Parameters:
xarray_like

Time values.

ampfloat

Amplitude of the exponential decay.

Tcfloat

Decay time constant.

offsetfloat

Offset of the exponential decay.

quaccatoo.analysis.fit_functions.fit_exp_decay_n(x: ndarray, A: float = 1, C: float = 0, Tc: float = 1, n: float = 1) ndarray[source]

Fit an exponential decay function with power n.

Parameters:
xarray_like

Time values.

Afloat

Amplitude of the exponential decay.

Cfloat

Offset of the exponential decay.

Tcfloat

Decay time constant.

nfloat

Power of the exponential decay.

quaccatoo.analysis.fit_functions.fit_five_sinc2(x: ndarray, A1: float, A2: float, A3: float, A4: float, A5: float, gamma1: float, gamma2: float, gamma3: float, gamma4: float, gamma5: float, f01: float, f02: float, f03: float, f04: float, f05: float, C: float) ndarray[source]

Fit two symmetric sinc functions.

Parameters:
xarray_like

Frequency values.

Afloat

Amplitude of the sinc functions.

gammafloat

Width of the sinc functions.

f_meanfloat

Mean frequency of the sinc functions.

f_deltafloat

Frequency difference between the sinc functions.

Cfloat

Offset of the sinc functions.

quaccatoo.analysis.fit_functions.fit_hahn_mod(x: ndarray, A: float, B: float, C: float, f1: float, f2: float) ndarray[source]

Fit a Hahn echo with modulation function with 2 frequencies.

Parameters:
xarray_like

Time values.

Afloat

Amplitude of the echo.

Bfloat

Amplitude of the modulation.

Cfloat

Offset of the echo.

f1float

First modulation frequency.

f2float

Second modulation frequency.

quaccatoo.analysis.fit_functions.fit_hahn_mod_decay(x: ndarray, A: float, B: float, C: float, f1: float, f2: float, Tc: float, n: float) ndarray[source]

Fit a Hahn echo with modulation function with 2 frequencies and exponential decay.

Parameters:
xarray_like

Time values.

Afloat

Amplitude of the echo.

Bfloat

Amplitude of the modulation.

Cfloat

Offset of the echo.

f1float

First modulation frequency.

f2float

Second modulation frequency.

Tcfloat

Decay time constant.

nfloat

Power of the exponential decay.

quaccatoo.analysis.fit_functions.fit_lorentz(x: ndarray, A: float, gamma: float, f0: float, C: float) ndarray[source]

Fit a Lorentzian peak.

Parameters:
xarray_like

Frequency values.

Afloat

Amplitude of the peak.

gammafloat

Width of the peak.

f0float

Central requency of the peak.

Cfloat

Offset of the peak.

quaccatoo.analysis.fit_functions.fit_rabi(x: ndarray, amp: float = 1, Tpi: float = 10, phi: float = 0, offset: float = 0) ndarray[source]

Fit a cosine function to Rabi oscillations.

Parameters:
xarray_like

Time values.

ampfloat

Amplitude of the cosine function.

Tpifloat

Pi-pulse duration (half the period of the cosine function).

phifloat

Phase of the cosine function.

offsetfloat

Offset of the cosine function.

quaccatoo.analysis.fit_functions.fit_rabi_decay(x: ndarray, amp: float = 1, Tpi: float = 10, phi: float = 0, offset: float = 0, Tc: float = 1) ndarray[source]

Fit a cosine function with exponential decay to Rabi oscillations.

Parameters:
xarray_like

Time values.

ampfloat

Amplitude of the cosine function.

Tpifloat

Pi-pulse duration (half the period of the cosine function).

phifloat

Phase of the cosine function.

offsetfloat

Offset of the cosine function.

Tcfloat

Decay time constant.

quaccatoo.analysis.fit_functions.fit_sinc2(x: ndarray, A: float = 1, gamma: float = 1, f0: float = 1, C: float = 1) ndarray[source]

Fit a sinc function.

Parameters:
xarray_like

Frequency values.

Afloat

Amplitude of the sinc function.

gammafloat

Width of the sinc function.

f0float

Central frequency of the sinc function.

Cfloat

Offset of the sinc function.

quaccatoo.analysis.fit_functions.fit_two_lorentz(x: ndarray, A1: float = 1, A2: float = 1, gamma1: float = 0.1, gamma2: float = 0.1, f01: float = 2870.0, f02: float = 2870.0, C: float = 0) ndarray[source]

Fit two symmetric Lorentzian peaks.

Parameters:
xarray_like

Frequency values.

A1float

Amplitude of the first peak.

A2float

Amplitude of the second peak.

gamma1float

Width of the first peak.

gamma2float

Width of the second peak.

f01float

Central frequency of the first peak.

f02float

Central frequency of the second peak.

Cfloat

Offset of the peaks.

quaccatoo.analysis.fit_functions.fit_two_lorentz_sym(x: ndarray, A: float = 1, gamma: float = 1, f_mean: float = 2870.0, f_delta: float = 1, C: float = 0) ndarray[source]

Fit two symmetric Lorentzian peaks.

Parameters:
xarray_like

Frquency values.

Afloat

Amplitude of the peaks.

gammafloat

Width of the peaks.

f_meanfloat

Mean frequency of the peaks.

f_deltafloat

Frequency difference between the peaks.

Cfloat

Offset of the peaks.

quaccatoo.analysis.fit_functions.fit_two_sinc2_sym(x: ndarray, A: float, gamma: float, f_mean: float, f_delta: float, C: float) ndarray[source]

Fit two symmetric sinc functions.

Parameters:
xarray_like

Frequency values.

Afloat

Amplitude of the sinc functions.

gammafloat

Width of the sinc functions.

f_meanfloat

Mean frequency of the sinc functions.

f_deltafloat

Frequency difference between the sinc functions.

Cfloat

Offset of the sinc functions.

exp_data

This module contains the ExpData class as part of the QuaCCAToo package.

class quaccatoo.exp_data.exp_data.ExpData(file_path: str, *, variable_column: int = 0, results_columns: int | list[int] = 1, yerr_columns: int | None = None, variable_name: str = 'Time', result_name: str = 'Expectation Value', plot: bool = False, figsize: tuple[int, int] = (6, 4), figtitle: str = 'Experimental Data', **loadtxt_kwargs: Any)[source]

Class to load experimental data and perform basic data processing.

Attributes:
variablenp.ndarray

Array containing the variable data

resultsnp.ndarray or list of np.ndarray

Array or list of arrays containing the results data

yerror: None, np.ndarray or list of np.ndarray

Array or list of arrays containing the uncertainty of the results

variable_namestr

Name of the variable

result_namestr

Name of the results

Methods

subtract_results_columns:

Subtracts the results of the negative column from the positive column

offset_correction:

Substracts a background value from the results

rescale_correction:

Multiplies the results by a rescale value

poly_baseline_correction:

Performs a polynomial baseline correction to the results

plot_exp_data:

Plots the experimental data

Constructor of the ExpData class. It loads experimental data from a file and sets the variable and results attributes according with the specified column arguments.

Parameters:
file_pathstr

Path to the file containing the experimental data

variable_columnint

Column index of the variable

results_columnsint or list of int

Column index of the results

yerr_columnsNone, int or list of int

Column index of the result uncertainty values

variable_namestr

Name of the variable

result_namestr

Name of the results

plotbool

Boolean indicating whether to plot the experimental data or not

figsizetuple

Size of the figure for the plot

figtitlestr

Title of the figure for the plot

**loadtxt_kwargsdict

Additional arguments for the np.loadtxt function

Methods

offset_correction(background_value[, plot, ...])

Overwrites the results attribute substracting the background value from the results.

plot_exp_data([figsize, figtitle])

Plots the experimental data.

poly_base_correction([x_start, x_end, ...])

Overwrites the results attribute performing a polynomial baseline correction.

rescale_correction(rescale_value[, plot, ...])

Overwrites the results attribute multiplying the results by the rescale value.

subtract_results_columns([pos_col, neg_col, ...])

Overwrites the results attribute substracting the results of the negative column from the positive column.

offset_correction(background_value: float, plot: bool = False, figsize: tuple[int, int] = (6, 4), figtitle: str = 'Expt. Data with Offset Correction') None[source]

Overwrites the results attribute substracting the background value from the results.

Parameters:
background_valuefloat

Value to be substracted from the results

plotbool

Boolean indicating whether to plot the experimental data or not

figsizetuple

Size of the figure for the plot

figtitlestr

Title of the figure for the plot

plot_exp_data(figsize: tuple[int, int] = (6, 4), figtitle: str = 'Experimental Data') None[source]

Plots the experimental data.

Parameters:
figsizetuple

Size of the figure for the plot

figtitlestr

Title of the figure for the plot

poly_base_correction(x_start: int | list[int] | None = None, x_end: int | list[int] | None = None, poly_order: int = 2, plot: bool = False, figsize: tuple[int, int] = (6, 4), figtitle: str = 'Expt. Data with Polynomial Baseline Correction') None[source]

Overwrites the results attribute performing a polynomial baseline correction. The baseline is fitted to the data between x_start and x_end, representing the start and end of the xaxis index.

Parameters:
x_startint or list of int

Start index of the x axis for the baseline fit

x_endint or list of int

End index of the x axis for the baseline fit

poly_orderint

Order of the polynomial to fit the baseline

plotbool

Boolean indicating whether to plot the experimental data or not

figsizetuple

Size of the figure for the plot

figtitlestr

Title of the figure for the plot

rescale_correction(rescale_value: float, plot: bool = False, figsize: tuple[int, int] = (6, 4), figtitle: str = 'Expt. Data with Rescale Correction') None[source]

Overwrites the results attribute multiplying the results by the rescale value.

Parameters:
rescale_valuefloat

Value to be multiplied by the results

plotbool

Boolean indicating whether to plot the experimental data or not

figsizetuple

Size of the figure for the plot

figtitlestr

Title of the figure for the plot

subtract_results_columns(pos_col: int = 0, neg_col: int = 1, plot: bool = False, figsize: tuple[int, int] = (6, 4), figtitle: str = 'Subtracted Expt. Data') None[source]

Overwrites the results attribute substracting the results of the negative column from the positive column.

Parameters:
pos_col: int

Index of the positive column

neg_col: int

Index of the negative column

plot: bool

Boolean indicating whether to plot the experimental data or not

figsize: tuple

Size of the figure for the plot

figtitle: str

Title of the figure for the plot

utils

This module provides functions to save and load quaccatoo objects, such as instances from QSys, ExpData, Analysis and PulsedSim. It also contains small internal helpers shared by the plotting methods of the other modules.

quaccatoo.utils.load_quaccatoo(file_path)[source]

Loads the attributes of an obj from a zip file, creates an instance of the obj, and sets the attributes.

Parameters:
file_pathstr

Path to the zip file where the attributes are saved.

Returns:
obj

The loaded obj.

quaccatoo.utils.save_quaccatoo(obj_save, file_path)[source]

Look for all the attributes of the obj, save Qobj attributes to separate files, and save the rest of the attributes to a pickle file. Finally, create a zip file containing all the files.

Parameters:
obj_savequaccatoo obj

The obj to be saved.

file_pathstr

Path to the file where the attributes will be saved.