Source_Doc package

Submodules

Source_Doc.PyOR_Basis module

PyOR Python On Resonance

Author: Vineeth Francis Thalakottoor Jose Chacko

Email: vineethfrancis.physics@gmail.com

Description:

This file contains the class Basis.

class Basis(class_QS)[source]

Bases: object

Adjoint(A)[source]

Compute the adjoint (Hermitian conjugate) of an operator.

Parameters

Andarray

Operator or state vector.

Returns

ndarray

Hermitian conjugate of the input.

BasisChange_HamiltonianEigenStates(H)[source]

Transform the basis to the eigenbasis of a given Hamiltonian.

This method computes the eigenvectors of the input Hamiltonian H and expresses them in the Zeeman basis. It stores the resulting transformation matrix in the quantum system, updates the operator basis, and returns the eigenvectors and their symbolic representations.

Parameters

HQunObj or np.ndarray

The Hamiltonian for which the eigenbasis should be computed.

Returns

eigenvectorsnp.ndarray

Eigenvectors of the Hamiltonian.

Diclist of str

Symbolic expressions of the eigenvectors in the Zeeman basis.

BasisChange_Operator(O, U)[source]

Transform an operator using the given transformation matrix.

Parameters

OQunObj

Operator in the original basis.

UQunObj

Transformation matrix.

Returns

QunObj

Operator in the new basis.

BasisChange_SpinOperators(Sop, U)[source]

Transform a list of spin operators using a transformation matrix.

Parameters

Soplist of QunObj

Spin operators in the original basis.

UQunObj

Transformation matrix.

Returns

list of QunObj

Transformed spin operators.

BasisChange_State(state, U)[source]

Transform a state vector using the given transformation matrix.

Parameters

stateQunObj

State in the original basis.

UQunObj

Transformation matrix.

Returns

QunObj

State in the new basis.

BasisChange_States(states, U)[source]

Transform one or more state vectors using the given transformation matrix.

Parameters

statesQunObj or list of QunObj

State(s) in the original basis.

UQunObj

Transformation matrix.

Returns

QunObj or list of QunObj

State(s) in the new basis.

BasisChange_TransformationMatrix(old, new)[source]

Compute the transformation matrix between two basis sets.

The transformation matrix \(U\) satisfies: \(| \text{new} \rangle = U | \text{old} \rangle\) and \(O_{\text{new}} = U O_{\text{old}} U^\dagger\)

Parameters

oldlist of QunObj

Old basis vectors.

newlist of QunObj

New basis vectors.

Returns

QunObj

Transformation matrix as a QunObj.

Basis_Ket_AngularMomentum_Array()[source]

Compute magnetic quantum numbers for each Zeeman state.

Returns

np.ndarray

Array of magnetic quantum numbers (diagonal of total Sz).

Basis_Ket_AngularMomentum_List()[source]

Compute magnetic quantum numbers for each Zeeman state as strings.

Returns

list of str

List of magnetic quantum numbers as fractions.

CG_Coefficient(j1, m1, j2, m2, J, M)[source]

Compute the Clebsch-Gordan coefficient ⟨j1 m1 j2 m2 | J M⟩.

Parameters

j1, m1, j2, m2, J, Mfloat or int

Quantum numbers for the Clebsch-Gordan coefficient.

Returns

float

Value of the Clebsch-Gordan coefficient.

InnerProduct(A, B)[source]

Compute inner product of two operators.

Parameters

A : ndarray B : ndarray

Returns

complex

Inner product Tr(A† B)

KetState_Components(ketQ, AQ=None, dic=None, ProjectionState=None, tol=1e-10, roundto=5)[source]

Decompose a ket (state vector) into a linear combination of basis vectors.

This method projects a given ket vector onto an orthonormal basis and prints the resulting decomposition in a readable form. Optionally, it can return the string representation of the decomposition if the instance attribute Return_KetState_Component is set to True.

Parameters

AQlist of QunObj

List of orthonormal basis vectors as QunObj instances.

dicdict

Dictionary mapping basis indices to readable basis labels.

ketQQunObj

The ket vector to decompose (must be a column vector).

tolfloat, optional

Numerical tolerance below which component values are considered zero. Default is 1.0e-10.

roundtoint, optional

Number of decimal places to round each component. Default is 5.

Raises

TypeError

If AQ is not a list or contains non-QunObj elements.

ValueError

If ketQ is not a column vector (i.e., shape mismatch).

Returns

None or str

Prints the decomposition of the ket. If self.Return_KetState_Component is True, also returns the string representation of the decomposition.

Normalize(A)[source]

Normalize an operator so its inner product with itself is 1.

Parameters

Andarray

Operator to normalize.

Returns

ndarray

Normalized operator.

ProductOperator(OP1, CO1, DIC1, OP2, CO2, DIC2, sort, indexing)[source]

Perform the Kronecker product of two sets of spherical basis operators.

Parameters

OP1, OP2list of QunObj

Basis operators of each subsystem.

CO1, CO2list of int

Coherence orders for each subsystem.

DIC1, DIC2list of str

Labels for each subsystem.

sortstr

Sorting method for coherence order.

indexingbool

Whether to append indices to the labels.

Returns

list of QunObj

Combined operator basis.

list of int

Combined coherence orders.

list of str

Combined operator labels.

ProductOperators_ConvertToLiouville(Basis_X)[source]

Convert product operator basis to Liouville space.

Parameters

Basis_Xlist of QunObj

Basis in Hilbert space.

Returns

list of QunObj

Basis in Liouville space.

ProductOperators_SphericalTensor(sort='negative to positive', Index=False)[source]

Generate spherical tensor basis for a multi-spin system.

Parameters

sortstr, optional

Sorting option for coherence order (‘normal’, ‘negative to positive’, ‘zero to high’).

Indexbool, optional

Whether to append index to labels.

Returns

list of QunObj

List of spherical tensor operators for the multi-spin system.

list of int

Corresponding coherence orders.

list of str

Labels of each basis operator in the form T(L,M).

ProductOperators_SphericalTensor_Test(sort='negative to positive', Index=False)[source]

Generate spherical tensor basis for a multi-spin system.

Parameters

sortstr, optional

Sorting option for coherence order (‘normal’, ‘negative to positive’, ‘zero to high’).

Indexbool, optional

Whether to append index to labels.

Returns

list of QunObj

List of spherical tensor operators for the multi-spin system.

list of int

Corresponding coherence orders.

list of str

Labels of each basis operator in the form SpinLabel(L,M).

ProductOperators_SpinHalf_Cartesian(Index=False, Normal=True)[source]

Generate product operator basis in the Cartesian basis for spin-1/2 systems.

Parameters

Indexbool, optional

Whether to include index in labels.

Normalbool, optional

Whether to normalize the operators.

Returns

list of QunObj

Product operators.

list of str

Corresponding labels.

ProductOperators_SpinHalf_Cartesian_Test(Index=False, Normal=True)[source]

Generate product operator basis in the Cartesian basis for spin-1/2 systems.

Parameters

Indexbool, optional

Whether to include index in labels.

Normalbool, optional

Whether to normalize the operators.

Returns

list of QunObj

Product operators.

list of str

Corresponding labels.

ProductOperators_SpinHalf_PMZ(sort='negative to positive', Index=False, Normal=True)[source]

Generate product operators for spin-1/2 systems in the PMZ basis.

Parameters

sortstr, optional

Sorting method for coherence order.

Indexbool, optional

Whether to include index in labels.

Normalbool, optional

Whether to normalize the operators.

Returns

list of QunObj

Product operators.

list of int

Coherence orders.

list of str

Operator labels.

ProductOperators_SpinHalf_PMZ_Test(sort='negative to positive', Index=False, Normal=True)[source]

Generate product operators for spin-1/2 systems in the PMZ basis.

Parameters

sortstr, optional

Sorting method for coherence order.

Indexbool, optional

Whether to include index in labels.

Normalbool, optional

Whether to normalize the operators.

Returns

list of QunObj

Product operators.

list of int

Coherence orders.

list of str

Operator labels.

ProductOperators_SpinHalf_SphericalTensor(sort='negative to positive', Index=False)[source]

Generate product operators for spin-1/2 systems in the spherical tensor basis.

Parameters

sortstr, optional

Sorting method for coherence order.

Indexbool, optional

Whether to include index in labels.

Returns

list of QunObj

Product operators.

list of int

Coherence orders.

list of str

Operator labels.

ProductOperators_SpinHalf_SphericalTensor_Test(sort='negative to positive', Index=False)[source]

Generate product operators for spin-1/2 systems in the spherical tensor basis.

Parameters

sortstr, optional

Sorting method for coherence order.

Indexbool, optional

Whether to include index in labels.

Returns

list of QunObj

Product operators.

list of int

Coherence orders.

list of str

Operator labels.

ProductOperators_Zeeman()[source]

Generate product operators in the Zeeman basis.

Returns

list of QunObj

Product operators in Zeeman basis.

list of str

Operator labels.

list of float

Coherence orders.

QunObj

Coherence order as a 2D matrix.

SingletTriplet_Basis(SINGTRIP=False)[source]

Generate singlet-triplet basis for two spin-1/2 particles.

Returns

list of QunObj

Singlet-triplet basis vectors.

list of str

Basis labels.

Notes

Only works for two spin-1/2 systems.

Spherical_OpBasis(S)[source]

Generate spherical tensor operator basis for a single spin.

Parameters

Sfloat

Spin quantum number.

Returns

list of QunObj

Spherical tensor operators.

list of int

Corresponding coherence orders.

list of tuple

List of (L, M) values.

Reference:

  1. Quantum Theory of Angular Momentum, D. A. Varshalovich, A. N. Moskalev and V. K. Khersonskii

String_to_Matrix(dic, Basis)[source]

Convert a dictionary of labels to a dictionary mapping labels to matrices.

Parameters

diclist of str

Dictionary labels for operator basis.

Basislist of QunObj

Corresponding list of operators.

Returns

dict

Dictionary mapping cleaned labels to QunObj instances.

Vector_L(X)[source]

Vectorize an operator into Liouville space form.

Parameters

Xndarray

Operator to vectorize.

Returns

ndarray

Vectorized operator.

Zeeman_Basis(ZEEMAN=False)[source]

Compute eigenbasis of the total Sz operator (Zeeman basis).

Returns

list of QunObj

Zeeman basis vectors.

list of str

Corresponding basis labels.

Source_Doc.PyOR_CoherenceFilters module

PyOR - Python On Resonance

Author: Vineeth Francis Thalakottoor Jose Chacko

Email: vineethfrancis.physics@gmail.com

Description:

This file contains the class CoherenceFilter.

class CoherenceFilter(class_QS)[source]

Bases: object

Filter_Coherence(rho, Allow_Coh)[source]

Filter to allow only selected coherence order. Operates on the density matrix in the Zeeman basis.

Parameters

rhondarray

Input density matrix.

Allow_Cohint

The allowed coherence order to retain.

Returns

tuple (coherence_mask, filtered_rho)

The coherence mask array and filtered density matrix.

Filter_T00(rho, index)[source]

T00 Filter: Extracts zero quantum coherence for selected spins. Works on the density matrix in the Zeeman basis.

Parameters

rhondarray

Input density matrix.

indexlist or tuple of int

Indices of the two spins to apply the filter on.

Returns

tuple (Filter_T00, filtered_rho)

Filter matrix and the filtered density matrix.

Source_Doc.PyOR_Commutators module

PyOR - Python On Resonance

Author: Vineeth Francis Thalakottoor Jose Chacko

Email: vineethfrancis.physics@gmail.com

Description:

This file contains the class Commutators.

class Commutators(class_QS=None)[source]

Bases: object

AntiCommutationSuperoperator(XQ)[source]

Construct the anti-commutation superoperator {X, •}.

Parameters

XQndarray or object with .data

Operator matrix.

Returns

ndarray or sparse matrix

Superoperator matrix.

AntiCommutator(AQ, BQ)[source]

Compute the anti-commutator {A, B}.

Parameters

AQ, BQndarray or object with .data

Input matrices.

Returns

ndarray

Anti-commutator {A, B} = AB + BA

CommutationSuperoperator(XQ)[source]

Construct the commutation superoperator [X, •].

Parameters

XQndarray or object with .data

Operator matrix.

Returns

ndarray or sparse matrix

Superoperator matrix.

Commutator(AQ, BQ)[source]

Compute the commutator [A, B].

Parameters

AQ, BQndarray or object with .data

Input matrices.

Returns

ndarray

Commutator [A, B] = AB - BA

DoubleCommutationSuperoperator(XQ, YQ)[source]

Construct the double commutation superoperator: [X, [Y, •]].

Parameters

XQ, YQndarray or object with .data

Operator matrices.

Returns

ndarray or sparse matrix

Superoperator representing [X, [Y, ρ]].

DoubleCommutator(AQ, BQ, rhoQ)[source]

Compute the double commutator [A, [B, ρ]].

Parameters

AQ, BQ, rhoQndarray or object with .data

Input matrices.

Returns

ndarray

Double commutator result.

Left_Superoperator(XQ)[source]

Construct the left multiplication superoperator: X ⊗ I or I ⊗ X.

Parameters

XQndarray or object with .data

Operator matrix.

Returns

ndarray or sparse matrix

Left superoperator matrix.

Right_Superoperator(XQ)[source]

Construct the right multiplication superoperator: I ⊗ Xᵀ or Xᵀ ⊗ I.

Parameters

XQndarray or object with .data

Operator matrix.

Returns

ndarray or sparse matrix

Right superoperator matrix.

Source_Doc.PyOR_CrystalOrientation module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file contains functions to load crystal orientation data.

It includes utilities to load data from SIMPSON-formatted CSV files and extracted crystallite arrays from SIMPSON’s crystallite library: https://github.com/vosegaard/simpson/blob/master/crystdat.c

Each function returns Euler angles alpha, beta, and the associated crystallite weights. Gamma is assumed to be 0 and excluded unless explicitly required.

Extract_CrystArray(file_path, array_name)[source]

Extracts crystallite alpha, beta, and weight values from a C file containing SIMPSON crystallite arrays, and saves them to a CSV file.

Parameters

file_pathstr

Path to the .c file (crystdat.c). (Donwload from crystdat.c file from https://github.com/vosegaard/simpson/blob/master/crystdat.c)

array_namestr

Name of the crystallite array to extract (e.g., ‘rep2000_cryst’).

Load_Crystallite_CSV(filepath, delimiter=',', skiprows=1)[source]

Loads crystallite orientation data from a SIMPSON-style CSV file.

Parameters

filepathstr

Path to the CSV file.

delimiterstr, optional

Delimiter used in the file (default is comma).

skiprowsint, optional

Number of rows to skip (default is 1 for header).

Returns

alphanp.ndarray

Alpha Euler angles (degrees).

betanp.ndarray

Beta Euler angles (degrees).

gammanp.ndarray

Gamma Euler angles (all zeros, degrees).

weightnp.ndarray

Solid angle weights (sum should be ~1).

Load_rep2000(file_path)[source]

Load rep2000_cryst from crystdat.c and save to rep2000_cryst.csv

Load_zcw28656(file_path)[source]

Load zcw28656_cryst from crystdat.c and save to zcw28656_cryst.csv

Load_zcw4180(file_path)[source]

Load zcw4180_cryst from crystdat.c and save to zcw4180_cryst.csv

Source_Doc.PyOR_DensityMatrix module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file contains the class for computing the equilibrium density matrix.

The equilibrium density matrix is a key concept in magnetic resonance, representing the state of the system at thermal equilibrium.

class DensityMatrix(class_QS, class_HAM)[source]

Bases: object

Adjoint(A)[source]

Return the Hermitian adjoint (conjugate transpose) of a matrix.

Create_DensityMatrix(state)[source]

Create a density matrix from a pure state.

DensityMatrix_Components(AQ, dic, rhoQ, tol=1e-10, roundto=5)[source]

Decompose a density matrix into a linear combination of a given operator basis.

This function calculates the components of the density matrix with respect to a specified basis of operators using an inner product. It prints the resulting decomposition in a readable format.

Parameters

AQlist of QunObj

List of basis operator objects that define the decomposition space.

dicdict

Dictionary mapping indices to basis labels for readable output.

rhoQQunObj

The density matrix (or state vector) to be decomposed.

tolfloat, optional

Tolerance level for treating small component values as zero. Default is 1.0e-10.

roundtoint, optional

Number of decimal places to round the non-zero components. Default is 5.

Raises

TypeError

If AQ is not a list or contains elements that are not instances of QunObj.

Returns

None

The function prints the decomposition of the density matrix but does not return it.

Detection_L(X)[source]

Detection vector for Liouville space.

Parameters

Xndarray

Operator matrix.

Returns

ndarray

Row vector (bra) for detection.

EquilibriumDensityMatrix(Ti, HT_approx=False)[source]

Calculate equilibrium density matrix for given spin temperatures.

Parameters

Tilist or ndarray

Spin temperatures for each spin.

HT_approxbool, optional

Use high temperature approximation if True.

Returns

QunObj

Equilibrium density matrix.

EquilibriumDensityMatrix_Add_TotalHamiltonian(HQ, T, HT_approx=False)[source]

Calculate equilibrium density matrix for total Hamiltonian.

Parameters

HQQunObj

Total Hamiltonian.

Tfloat

Uniform spin temperature.

HT_approxbool, optional

Use high temperature approximation if True.

Returns

QunObj

Equilibrium density matrix.

FinalDensityMatrix(HT_approx=False)[source]

Wrapper for equilibrium density matrix using final temperatures.

InitialDensityMatrix(HT_approx=False)[source]

Wrapper for equilibrium density matrix using initial temperatures.

InnerProduct(A, B)[source]

Compute the inner product ⟨A|B⟩.

Liouville_Bracket(A, B, C)[source]

Compute the Liouville bracket ⟨A|B|C⟩.

Parameters

A, B, C : ndarrays

Returns

float

Real part of the bracket.

Norm_Matrix(A)[source]

Compute the Frobenius norm of a matrix.

Normalize(A)[source]

Return a normalized operator with unit inner product.

PolarizationVector(spinQ, rhoQ, SzQ, PolPercentage)[source]

Compute polarization of a spin system.

Parameters

spinQfloat

Spin quantum number.

rhoQQunObj

Density matrix.

SzQQunObj

Spin-z operator.

PolPercentagebool

Return value as percentage if True.

Returns

float

Spin polarization value.

ProductOperators_ConvertToLiouville(Basis_X)[source]

Convert basis operators to Liouville space.

Parameters

Basis_Xlist of ndarrays

Basis operators in Hilbert space.

Returns

list of QunObj

Operators in Liouville space.

Update()[source]

Update matrix tolerance from quantum system settings.

Vector_L(X)[source]

Vectorize an operator into a Liouville space column vector.

Parameters

Xndarray

Operator matrix.

Returns

ndarray

Vectorized form.

Source_Doc.PyOR_Evolution module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file contains the class Evolutions, which is used for simulating time evolution of spin systems under different Hamiltonians and conditions.

class Evolutions(class_QS, class_Ham=None)[source]

Bases: object

Commutator(A, B)[source]

INPUT

A : matrix A B : matrix B

OUTPUT

Commutator [A,B]

Convert_LrhoTO2Drho(Lrho)[source]

Convert a Vector into a 2d Matrix

INPUT

Lrho: density matrix, coloumn vector OUTPUT —— return density matrix, 2d array

Evolution(rhoQ, rhoeqQ, HamiltonianQ, RelaxationQ=None, HamiltonianArray=None)[source]
Expectation(rho_t, detectionQ)[source]
TimeDependent_Hamiltonian(t)[source]
TimeDependent_Hamiltonian_Hilbert(t)[source]
Update()[source]

Source_Doc.PyOR_Fitting module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file contains functions for curve fitting, typically used to analyze simulation outputs and extract physical parameters.

Functions include utilities for fitting decay curves, frequency sweeps, and relaxation models relevant to magnetic resonance experiments.

Exp_Buildup(x, a, b, c)[source]

Exponential build-up function.

Model

f(x) = c - (c - a) * exp(-b * x)

Parameters

xarray_like

Independent variable.

a, b, cfloat

Fit parameters.

Returns

array_like

Evaluated function.

Exp_Decay(x, a, b, c)[source]

Single exponential decay function.

Model

f(x) = a * exp(-b * x) + c

Parameters

xarray_like

Independent variable.

a, b, cfloat

Fit parameters.

Returns

array_like

Evaluated function.

Exp_Decay_2(x, a, b, c, d, e)[source]

Double exponential decay function.

Model

f(x) = a * exp(-b * x) + c * exp(-d * x) + e

Parameters

xarray_like

Independent variable.

a, b, c, d, efloat

Fit parameters.

Returns

array_like

Evaluated function.

Fitting_LeastSquare(func, xdata, ydata)[source]

Perform non-linear least squares fitting using a custom function.

Parameters

funccallable

Model function to fit, with signature func(x, …).

xdataarray_like

Independent data (x-values).

ydataarray_like

Dependent data (y-values).

Returns

poptarray

Optimal values for the parameters.

pcov2D array

Estimated covariance of popt.

Notes

For more details, see: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

Source_Doc.PyOR_Gamma module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file contains the gyromagnetic ratios of the electron and various nuclei commonly encountered in magnetic resonance experiments.

gamma(value)[source]

Returns the gyromagnetic ratio (γ) of a specified particle.

The gyromagnetic ratio is a fundamental physical constant that relates the magnetic moment of a particle to its angular momentum. It plays a key role in nuclear magnetic resonance (NMR), electron paramagnetic resonance (EPR), and magnetic field interactions.

Parameters:

valuestr
Symbol representing the particle. Common examples include:
  • “E” : Electron

  • “H1” : Proton (Hydrogen-1)

  • “H2” : Deuterium (Hydrogen-2)

  • “C13” : Carbon-13

  • “N14” : Nitrogen-14

  • “N15” : Nitrogen-15

  • “O17” : Oxygen-17

  • “F19” : Fluorine-19

Returns:

float

Gyromagnetic ratio of the given particle, in units of radians per second per tesla (rad·s⁻¹·T⁻¹).

Raises:

AssertionError

If the particle symbol is not found in the predefined GAMMA dictionary. In such cases, users are expected to define and add the gyromagnetic ratio manually.

Example:

gamma(“H1”) 267522000.0

gamma(“N15”) -27116000.0

Reference:

Harris, R. K., Becker, E. D., de Menezes, S. M. C., Goodfellow, R., & Granger, P. (2001). NMR nomenclature. Nuclear spin properties and conventions for chemical shifts (IUPAC Recommendations 2001). Pure and Applied Chemistry, 73(11), 1795–1818. DOI: https://doi.org/10.1351/pac200173111795

Source_Doc.PyOR_Hamiltonian module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file contains the Hamiltonian class, which provides routines for building various spin interaction Hamiltonians used in magnetic resonance simulations.

Supported interactions may include Zeeman, dipolar coupling, scalar coupling, and quadrupolar interactions depending on system specifications.

class Hamiltonian(class_QS)[source]

Bases: object

DDcoupling()[source]

Construct the Dipole-Dipole (DD) interaction Hamiltonian for all spin pairs.

Supports: - Secular approximation (Hetero & Homo) - Full interaction (All terms: secular, pseudo-secular, non-secular) - Individual components: A, B, C, D, E, F

Inputs from class_QS:

  • DipolePairs: list of (i, j) spin index pairs

  • DipoleAngle: list of (theta, phi) for each pair in degrees

  • DipolebIS: list of dipolar coupling constants (Hz)

  • Dipole_DipolarAlpabet: interaction mode (secular, All, A–F)

Output:

QunObj

Complete DD coupling Hamiltonian in angular frequency units

Dipole_Coupling_Constant(Gamma1, Gamma2, distance)[source]

Compute the dipolar coupling constant between two spins.

Formula: b_IS = - (μ₀ / 4π) * (γ₁ * γ₂ * ℏ) / r³

Inputs:

Gamma1float

Gyromagnetic ratio of spin 1 (rad/T·s)

Gamma2float

Gyromagnetic ratio of spin 2 (rad/T·s)

distancefloat

Inter-spin distance in meters

Output:

float

Dipolar coupling constant in Hz

Eigen(H)[source]

Compute eigenvalues and eigenvectors of a Hamiltonian.

Parameters:

Hnp.ndarray

Hamiltonian matrix

Returns:

tuple

(eigenvalues, eigenvectors)

InteractionTensor_LAB(ApafQ, alpha=0.0, beta=0.0, gamma=0.0)[source]

Rotates a tensor from PAF to LAB frame using spherical tensors and Wigner rotation.

Parameters:

ApafQQunObj

Tensor in principal axis frame

alpha, beta, gammafloat

Euler angles

Returns:

QunObj

Rotated tensor in LAB frame

InteractionTensor_LAB_Decomposition(AQ)[source]

Decomposes a LAB-frame tensor into isotropic, symmetric, and antisymmetric parts.

Parameters:

AQQunObj

LAB-frame tensor

Returns:

dict

Dictionary with QunObj entries: “Isotropic”, “Symmetric”, “Antisymmetric”

InteractionTensor_PAF_CSA(Iso, Aniso, Asymmetry)[source]

Constructs the CSA interaction tensor in the principal axis frame (PAF).

Parameters:

Isofloat

Isotropic component

Anisofloat

Anisotropy (Azz - Iso)

Asymmetryfloat

Asymmetry parameter (eta = (Ayy - Axx) / Aniso), range from 0 <= eta <= 1

Returns:

QunObj

3x3 CSA tensor in PAF

InteractionTensor_PAF_Decomposition(AQ)[source]

Decomposes a PAF tensor into isotropic, anisotropy, and asymmetry components.

Parameters:

AQQunObj

Tensor to decompose

Returns:

dict

Dictionary with keys: “Isotropic”, “Anisotropy”, “Asymmetry”

InteractionTensor_PAF_Dipole(d)[source]

Constructs a PAF dipolar tensor.

Parameters:

dfloat

Dipolar coupling constant (in Hz)

Returns:

QunObj

Dipolar tensor in the PAF

InteractionTensor_PAF_ElectronZeeman(gshiftList)[source]

Constructs the electron Zeeman interaction tensor in the principal axis frame (PAF).

This method calculates the electron Zeeman interaction tensor by combining the isotropic contribution (from the free electron g-factor) and the anisotropic shifts (g-shifts). If specified, the resulting tensor components are converted to angular frequency units.

Parameters:

gshiftListlist or array-like of float

A list of three g-shift values [g_xx, g_yy, g_zz] representing the anisotropic g-tensor components in the principal axis frame.

Returns:

QunObj

A quantum object representing the full 3x3 electron Zeeman interaction tensor.

InteractionTensor_PAF_General(diagList)[source]

Constructs an interaction tensor in the Principal Axis Frame (PAF) from a diagonal list of components.

This method builds a 3x3 diagonal interaction tensor in the PAF using values provided in diagList. If the InteractioTensor_AngularFrequency flag is set to True, the input values are assumed to be in Hz and are converted to angular frequency units (rad/s) by multiplying by 2π.

Parameters

diagListlist or array-like of float

A list or array with three diagonal elements representing the interaction tensor components along the x, y, and z axes in the PAF. Units are Hz unless the flag InteractioTensor_AngularFrequency is True, in which case the result will be in rad/s.

Returns

QunObj

An instance of QunObj representing the 3x3 interaction tensor matrix constructed from the diagonal values.

InteractionTensor_PAF_Quadrupole(X, Coupling, etaQ)[source]

Constructs the quadrupolar tensor in the PAF.

Parameters:

Xstr

Spin label

eqfloat

Electric field gradient

etaQfloat

Quadrupolar asymmetry parameter

Returns:

QunObj

Quadrupolar tensor in the PAF

InteractionTensor_PAF_ZeroField(D, E)[source]

Constructs the zero-field splitting (ZFS) interaction tensor in the principal axis frame (PAF).

This method builds a symmetric 3x3 tensor representing the ZFS interaction for an electron spin system in the absence of an external magnetic field. The tensor is expressed in angular frequency units (i.e., radians per second), assuming D and E are initially given in Hz.

Parameters:

Dfloat

The axial zero-field splitting parameter (in Hz).

Efloat

The rhombic zero-field splitting parameter (in Hz).

Returns:

QunObj

A quantum object representing the 3x3 zero-field splitting interaction tensor.

Notes:

  • D and E are converted to angular frequency units by multiplying with 2π.

  • The tensor is constructed with the following diagonal elements:
    • T_xx = (-1/3) * D + E

    • T_yy = (-1/3) * D - E

    • T_zz = (2/3) * D

  • This is appropriate for spin systems with S > 1/2, typically S = 1.

Interaction_Hamiltonian_Catesian_Euler(XQ, AQ, YQ, alpha=0.0, beta=0.0, gamma=0.0)[source]

Rotate interaction tensor using Euler angles and construct Hamiltonian in Cartesian space.

Parameters:

XQstr

Name of spin operator (e.g., “I”)

AQQunObj

Interaction tensor in PAF

YQstr

Second spin operator (e.g., “S”), or “” if external field

alpha, beta, gammafloat

Euler angles in radians

Returns:

QunObj

The interaction Hamiltonian

Interaction_Hamiltonian_Catesian_Wigner(XQ, ApafQ, YQ, alpha=0.0, beta=0.0, gamma=0.0)[source]

General interaction Hamiltonian using Wigner rotation of Cartesian tensors.

Parameters:

XQstr

Name of the spin operator prefix (e.g., “I” or “S”).

ApafQQunObj

Interaction tensor in PAF (Principal Axis Frame).

YQstr

Second spin operator prefix (e.g., “S”) or “” if interacting with external field.

alpha, beta, gammafloat

Euler angles in radians to rotate from PAF to lab frame.

Returns:

QunObj

The interaction Hamiltonian.

Interaction_Hamiltonian_LAB_CSA_Secular(X, ApasQ, theta, phi)[source]

Constructs the secular CSA Hamiltonian in the lab frame.

Parameters:

Xstr

Spin label (e.g., ‘I’ or ‘S’)

ApasQQunObj

CSA tensor in PAF (principal axis frame)

thetafloat

Polar angle in degrees

phifloat

Azimuthal angle in degrees

Returns:

QunObj

The secular CSA Hamiltonian component.

Interaction_Hamiltonian_LAB_Quadrupole_Secular(X, Coupling, etaQ, theta, phi)[source]

Constructs the secular quadrupole Hamiltonian.

Parameters:

Xstr

Nucleus label

eqfloat

Electric field gradient

etaQfloat

Quadrupolar asymmetry parameter

theta, phifloat

Orientation angles in degrees

Returns:

QunObj

The quadrupole Hamiltonian

Interaction_Hamiltonian_MAS_SphericalTensor(X, ApafQ, Y, string, approx, alpha=0.0, beta=0.0, gamma=0.0, alpha1=0.0, beta1=0.0, gamma1=0.0)[source]

General Hamiltonian using spherical tensor formalism for Magical Angle Spinning (MAS).

Reference:

Michael Mehring, Internal Spin Interactions and Rotations in Solids.

Interaction_Hamiltonian_SphericalTensor(X, ApafQ, Y, string, approx, alpha=0.0, beta=0.0, gamma=0.0)[source]

General Hamiltonian using spherical tensor formalism.

Reference:

Michael Mehring, Internal Spin Interactions and Rotations in Solids.

Jcoupling()[source]

Construct full J-coupling Hamiltonian (isotropic scalar coupling).

H_J = ∑₍i<j₎ J_ij * (Sxᵢ·Sxⱼ + Syᵢ·Syⱼ + Szᵢ·Szⱼ)

Inputs:

J2D array (Hz)

Symmetric matrix of J-couplings between spins i and j.

Sx, Sy, Szlist of ndarray

Cartesian spin operators for all spins.

Output:

QunObj

Full J-coupling Hamiltonian (angular frequency units).

Jcoupling_Weak()[source]

Construct simplified J-coupling Hamiltonian (weak coupling approximation).

H_J ≈ ∑₍i<j₎ J_ij * Szᵢ·Szⱼ

Inputs:

J2D array (Hz)

Symmetric matrix of J-couplings between spins i and j.

Szlist of ndarray

Z-component spin operators.

Output:

QunObj

Simplified J-coupling Hamiltonian (angular frequency units).

LarmorFrequency()[source]

Computes the Larmor frequency (Ω₀) for each spin in the lab frame.

Larmor frequency is given by:

Ω₀ = -γ * B₀ - 2π * δ

where:

γ = gyromagnetic ratio, B₀ = magnetic field strength in Tesla, δ = chemical shift offset (in Hz)

Returns:

numpy.ndarray

Larmor frequencies (angular frequencies) for each spin in the system.

MASSpectrum(EVol, rhoI, rhoeq, X, IT_PAF, Y, string, approx, alpha, beta, gamma, weighted=True, weight=None, MagicAngle=0.0, RotortFrequency=0.0, ncores=-2, apodization=0.0)[source]

Computes the Magic Angle Spinning (MAS) powder-averaged spectrum.

This function constructs a periodic time-dependent Hamiltonian array for MAS, evolving the system under that Hamiltonian, and computing the spectrum by Fourier transforming the expectation values.

Parameters:

EVolEvolution object

Evolution class instance capable of time evolution.

rhoIndarray

Initial density matrix.

rhoeqndarray

Equilibrium density matrix.

Xstr

Spin species (e.g., “H”, “C”).

IT_PAFndarray

Interaction tensor in principal axis frame (PAF).

Ystr

Secondary spin species for spin-spin interactions (can be empty for spin-field interactions).

stringstr

Type of interaction: “spin-field” or “spin-spin”.

approxstr

Approximation method: “all”, “secular”, or “secular + pseudosecular”.

alpha, beta, gammaarray-like

Orientation angles (in radians) for the powder averaging.

weightedbool, optional

Whether to use weighted averaging. Default is True.

weightndarray, optional

Weights for each crystallite orientation.

MagicAnglefloat, optional

Magic angle value in degrees. Default is 0.

RotortFrequencyfloat, optional

Spinning frequency in Hz. Default is 0.

ncoresint, optional

Number of cores for parallelization. Default is -2 (use all but two cores).

apodizationfloat, optional

Apodization factor for windowing. Default is 0.

Returns:

freqndarray

Frequency axis (Hz).

spectrumndarray

Powder-averaged spectrum (absolute value).

Acknowledgements:

  1. Subhadip Pradhan, TIFR Hyderabad, for sharing the concept of using periodic Hamiltonian.

MASSpectrum2(EVol, rhoI, rhoeq, X, IT_PAF, Y, string, approx, alpha, beta, gamma, weighted=True, weight=None, MagicAngle=0.0, RotortFrequency=0.0, ncores=-2, apodization=0.0)[source]

<<<< Attention: This function is slow. >>>>

Computes the powder-averaged spectrum over (alpha, beta, gamma) angles.

Parameters:

weightedbool

Whether to use weighted averaging.

weightndarray or None

Optional crystallite weights. If None and weighted=True, defaults to sin(beta) weighting.

Returns:

freqndarray

Frequency axis.

spectrumndarray

Powder-averaged spectrum (absolute value).

PowderSpectrum(EVol, rhoI, rhoeq, X, IT_PAF, Y, string, approx, alpha, beta, gamma, weighted=True, weight=None, SecularEquation='spherical', ncores=-2, apodization=0.5)[source]

Computes the powder-averaged spectrum over (alpha, beta, gamma) angles.

Parameters:

weightedbool

Whether to use weighted averaging.

weightndarray or None

Optional crystallite weights. If None and weighted=True, defaults to sin(beta) weighting.

Returns:

freqndarray

Frequency axis.

spectrumndarray

Powder-averaged spectrum (absolute value).

ShapedPulse_Bruker(file_path, pulseLength, RotationAngle)[source]

Load and process a shaped pulse from a Bruker shape file.

Parameters:

file_pathstr

Path to the shaped pulse file (typically Bruker format)

pulseLengthfloat

Total length of the shaped pulse (in seconds)

RotationAnglefloat

Desired rotation angle (in degrees)

Returns:

tuple

(time array, B1 amplitude over time, B1 phase over time)

References:

ShapedPulse_Interpolate(time, SPIntensity, SPPhase, Kind)[source]

Interpolate amplitude and phase arrays of a shaped pulse.

Parameters:

timearray

Time axis of the pulse shape

SPIntensityarray

Amplitude values of the pulse shape

SPPhasearray

Phase values of the pulse shape (radians)

Kindstr

Interpolation method (e.g., ‘linear’, ‘cubic’, etc.)

Returns:

tuple

(amplitude interpolator, phase interpolator)

Update()[source]

Updates internal parameters from the QuantumSystem instance. Useful when the quantum system is modified externally and the Hamiltonian needs to be resynchronized.

Zeeman()[source]

Constructs the Zeeman Hamiltonian in the laboratory frame.

The Zeeman Hamiltonian is defined as:

\[H_Z = \sum_i \omega_{0i} \cdot S_{zi}\]

where \(\omega_{0i}\) is the Larmor frequency of the i-th spin, and \(S_{zi}\) is the z-component spin operator.

Returns

QunObj

The Zeeman Hamiltonian represented as a quantum object.

Zeeman_B1(Omega1, Omega1Phase)[source]

Constructs the B₁ Hamiltonian for RF excitation in the rotating frame.

Assumes a continuous wave RF field:

H_RF = ω₁ * [Sₓ cos(ϕ) + Sᵧ sin(ϕ)]

Parameters:

Omega1float

RF amplitude in Hz (nutation frequency).

Omega1Phasefloat

RF phase in degrees.

Returns:

QunObj

Time-independent B₁ Hamiltonian in rotating frame.

Zeeman_B1_Offresonance(t, Omega1, Omega1freq, Omega1Phase)[source]

Constructs a time-dependent Zeeman Hamiltonian for an off-resonant RF field.

H(t) = ω₁ * [Sₓ cos(ω_RF * t + ϕ) + Sᵧ sin(ω_RF * t + ϕ)]

Parameters:

tfloat

Time in seconds.

Omega1float

RF amplitude (nutation frequency in Hz).

Omega1freqfloat

RF frequency in Hz (off-resonance frequency in rotating frame).

Omega1Phasefloat

Initial phase in degrees.

Returns:

numpy.ndarray

Time-dependent Hamiltonian matrix (not a QunObj).

Zeeman_B1_ShapedPulse(t, Omega1T, Omega1freq, Omega1PhaseT)[source]

Constructs time-dependent B₁ Hamiltonian with shaped amplitude and phase (e.g., Gaussian).

Parameters:

tfloat

Time (in seconds).

Omega1Tcallable

Function returning time-varying RF amplitude (Hz).

Omega1freqfloat

RF carrier frequency (Hz).

Omega1PhaseTcallable

Function returning time-varying phase (radians).

Returns:

numpy.ndarray

Time-dependent Hamiltonian matrix (not a QunObj).

Zeeman_RotFrame()[source]

Constructs the Zeeman Hamiltonian in the rotating frame.

The Hamiltonian is defined as:

\[H_Z^{\mathrm{RF}} = \sum_i \left( \omega_{0i} - \omega_{\mathrm{RF}i} \right) S_{zi}\]

where: - \(\omega_{0i}\) is the Larmor frequency of the i-th spin - \(\omega_{\mathrm{RF}i}\) is the rotating frame reference frequency

Returns

QunObj

The Zeeman Hamiltonian in the rotating frame.

Source_Doc.PyOR_HardPulse module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file defines the HardPulse class, which implements methods for handling rotation (pulse) operations in both Hilbert and Liouville spaces as applied in magnetic resonance simulations.

The HardPulse class supports the construction of rotation operators, pulse applications, and conversions between different quantum mechanical representations.

class HardPulse(class_QS)[source]

Bases: object

Rotate_CyclicPermutation(AQ, BS, theta)[source]

Rotate operator BS about operator AQ using cyclic commutation relations.

This method applies an analytical rotation based on the cyclic commutator rule: If [A, B] = jC, then the rotation of B about A by angle θ is given by:

EXP(-j A * θ) @ B @ EXP(j A * θ)

= B * cos(θ) - j * [A, B] * sin(θ) = B * cos(θ) + C * sin(θ)

where:

A : Operator about which rotation is applied B : Operator being rotated C : Operator resulting from the commutator [A, B] = jC j : imaginary unit

Parameters

AQQunObj

Operator A about which the rotation happens.

BSQunObj

Operator B to be rotated.

thetafloat

Rotation angle in degrees.

Returns

QunObj

Rotated operator.

Rotate_Pulse(rhoQ, theta_rad, operatorQ)[source]

Perform rotation on an operator or state under a pulse.

This applies the unitary rotation: exp(-iθA) ρ exp(iθA)

Parameters

rhoQQunObj

Density matrix or operator to be rotated.

theta_radfloat

Rotation angle in degrees.

operatorQQunObj

Operator generating the rotation (e.g., Ix, Iy, Iz).

Returns

QunObj

Rotated operator or state.

Source_Doc.PyOR_NonlinearNMR module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file defines the NonLinear class, which provides utilities for incorporating non-linear effects such as radiation damping, dipolar shifts, and Gaussian noise into spin dynamics simulations in nuclear magnetic resonance (NMR).

The NonLinear class enables the simulation of complex feedback mechanisms that are critical for modeling real-world magnetic resonance experiments.

class NonLinear(class_QS)[source]

Bases: object

DipoleShift(rho)[source]

Compute dipolar shift from the current density matrix.

Parameters

rhonp.ndarray

Density matrix of the system.

Returns

float

Average dipolar field shift along z-direction.

Noise_Gaussian(N_mean, N_std, N_length)[source]

Generate Gaussian noise samples.

Parameters

N_meanfloat

Mean of the Gaussian distribution.

N_stdfloat

Standard deviation of the Gaussian distribution.

N_lengthint

Number of random samples to generate.

Returns

np.ndarray

An array of random noise values or zeros depending on configuration.

Radiation_Damping(rho)[source]

Compute the radiation damping field based on the system state.

This function calculates the transverse magnetization contributions to radiation damping and optionally adds spin noise in two different ways depending on simulation settings.

Parameters

rhonp.ndarray

Density matrix of the spin system.

Returns

complex

The effective radiation damping field including optional noise. Real part corresponds to the x-component, imaginary part to y-component.

Source_Doc.PyOR_Particle module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file defines the Particle class, which represents a quantum particle with properties relevant to magnetic resonance simulations.

Attributes:
name (str):

The name of the particle (e.g., ‘1H’, ‘13C’, ‘Electron’).

spin (float):

The spin quantum number of the particle.

gamma (float):

The gyromagnetic ratio of the particle (in rad/s/T).

quadrupole (float):

The quadrupole moment of the particle (if applicable, otherwise zero).

class particle(value)[source]

Bases: object

Source_Doc.PyOR_PhaseCycle module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This file defines the PhaseCycle class, which handles phase cycling operations including pulse phasing and receiver phase adjustments in magnetic resonance simulations.

Phase cycling is a crucial technique for eliminating unwanted coherence pathways and improving signal-to-noise ratios in NMR and EPR experiments.

class PhaseCycle(class_QS)[source]

Bases: object

Pulse_Phase(SxQ, SyQ, phase)[source]

Construct a pulse operator along a defined phase direction.

This generates a combined spin operator that simulates a pulse along the direction defined by phase: Pulse Operator = cos(phase) * Sx + sin(phase) * Sy

Parameters

SxQQunObj

Sx spin operator (should be a list of matrices or summed operator).

SyQQunObj

Sy spin operator (same dimensions as SxQ).

phasefloat

Desired phase angle in degrees.

Returns

QunObj

Spin operator for rotation about the defined phase axis.

Raises

TypeError

If inputs are not instances of QunObj.

Receiver_Phase(SxQ, SyQ, phase)[source]

Construct a receiver (detection) operator with a defined phase.

This rotates the detection operator (Sx + iSy) by the specified receiver phase: Detection Operator = (Sx + i*Sy) * exp(i * phase)

Parameters

SxQQunObj

Sx spin operator.

SyQQunObj

Sy spin operator.

phasefloat

Receiver phase in degrees.

Returns

QunObj

Complex detection operator after phase adjustment.

Raises

TypeError

If inputs are not instances of QunObj.

Source_Doc.PyOR_PhysicalConstants module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides commonly used physical constants relevant to magnetic resonance simulations, including Planck’s constant, Boltzmann constant, magnetic permeability, and elementary charge.

These constants are critical for calculating resonance conditions, thermal polarization, and magnetic interactions.

constants(value)[source]

Returns the value of a fundamental physical constant.

This function provides access to a dictionary of commonly used physical constants in quantum mechanics, electromagnetism, and thermodynamics. The values are given in SI units unless otherwise specified.

Parameters:

valuestr
The key representing the desired constant. Available keys include:
  • “pl” : Planck constant (h), in joule·seconds (J·s)

  • “hbar” : Reduced Planck constant (ħ = h / 2π), in joule·seconds per radian (J·s·rad⁻¹)

  • “ep0” : Vacuum permittivity (ε₀), in farads per meter (F·m⁻¹)

  • “mu0” : Vacuum permeability (μ₀), in newtons per ampere squared (N·A⁻²) or henries per meter (H·m⁻¹)

  • “kb” : Boltzmann constant (k_B), in joules per kelvin (J·K⁻¹)

  • “bm” : Bohr magneton (μ_B), in joules per tesla (J·T⁻¹)

  • “nm” : Nuclear magneton (μ_N), in joules per tesla (J·T⁻¹)

Returns:

float

The numerical value of the requested physical constant in SI units.

Raises:

AssertionError

If the specified key is not found in the CONSTANTS dictionary. Users may add new constants manually if needed.

Example:

constants(“pl”) 6.626e-34

constants(“kb”) 1.380649e-23

Source_Doc.PyOR_Plotting module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module defines the Plotting class, which provides visualization utilities for PyOR simulations.

The Plotting class includes functions for plotting time-domain signals, frequency spectra, evolution of density matrices, and other data relevant to magnetic resonance experiments.

class Fanalyzer(Mx, My, ax, fig, line1, line2, line3, line4, vline1, vline2, vline3, vline4, text1, text2)[source]

Bases: object

Interactive Fourier analyzer for visualizing time-frequency transformations.

This class enables interactive selection and analysis of signal portions in time and frequency domains. It links two time-domain and two frequency-domain plots together, enabling dynamic visual feedback.

Parameters

Mxndarray

Real part of the signal (time domain).

Myndarray

Imaginary part of the signal (time domain).

axndarray of Axes

2x2 array of matplotlib Axes objects.

figmatplotlib.figure.Figure

The figure containing the subplots.

line1Line2D

Plot handle for time-domain signal (top left).

line2Line2D

Plot handle for full spectrum (top right).

line3Line2D

Plot handle for second spectrum (bottom left).

line4Line2D

Plot handle for reconstructed signal (bottom right).

vline1, vline2, vline3, vline4Line2D

Vertical lines indicating selection on plots.

text1, text2Text

Text annotations for selected range (frequency/time).

button_press(event)[source]

Handle mouse press event for interactive selection.

Parameters

eventmatplotlib.backend_bases.MouseEvent

Mouse press event.

button_release(event)[source]

Handle mouse release event and update plots based on selection.

Parameters

eventmatplotlib.backend_bases.MouseEvent

Mouse release event.

class Plotting(class_QS)[source]

Bases: object

InnerProduct(A, B)[source]

Calculate the inner product of two matrices or vectors.

This uses the definition of the inner product as Tr(A†B), where A† is the conjugate transpose of A.

Parameters

Andarray

First operator or vector.

Bndarray

Second operator or vector.

Returns

complex

The inner product value as a complex number.

MatrixPlot(M, xlabel, ylabel, saveplt=False)[source]

Plot a 2D color map of a matrix with labels.

Parameters

Mndarray

Matrix to be plotted.

xlabellist of str

Labels for x-axis.

ylabellist of str

Labels for y-axis.

MatrixPlot3D(rho, xlabel, ylabel, saveplt=False)[source]

Create a 3D bar plot of matrix values.

Parameters

rhondarray

Matrix to be plotted (2D).

xlabellist of str

Labels for x-axis.

ylabellist of str

Labels for y-axis.

MatrixPlot_slider(t, rho_t, xlabel, ylabel)[source]

Plot a time-dependent matrix with a slider to change time steps.

Parameters

tndarray

Array of time points.

rho_tndarray

Array of matrices over time (len(t) x N x N).

xlabellist of str

X-axis labels.

ylabellist of str

Y-axis labels.

Plotting(x, y, xlab, ylab, col, saveplt=False)[source]

Plot a simple 2D line graph.

Parameters

xarray_like

Array containing data for the x-axis.

yarray_like

Array containing data for the y-axis.

xlabstr

Label for the x-axis.

ylabstr

Label for the y-axis.

colstr

Color code or name for the plot line.

Returns

None

Plotting3DWire(x, y, z, xlab, ylab, title, upL, loL, saveplt=False)[source]

Plot a 3D wireframe surface using meshgrid data.

Parameters

xndarray

1D array for x-axis values.

yndarray

1D array for y-axis values.

z2D ndarray

Matrix of z-values defining the surface height.

xlabstr

Label for the x-axis.

ylabstr

Label for the y-axis.

titlestr

Title of the plot.

upLfloat

Upper limit for the X and Y axes.

loLfloat

Lower limit for the X and Y axes.

Returns

None

PlottingContour(x, y, z, xlab, ylab, title, saveplt=False)[source]

Generate a contour plot of a 2D scalar field.

Parameters

xndarray

1D array of x-axis values.

yndarray

1D array of y-axis values.

zndarray

2D array of z values, representing the scalar field.

xlabstr

Label for the x-axis.

ylabstr

Label for the y-axis.

titlestr

Title of the contour plot.

Returns

None

PlottingMulti(x, y, xlab, ylab, col, saveplt=False)[source]

Plot multiple signals on a single set of axes.

Parameters

xlist of array_like

List of X-axis data arrays, each corresponding to one line.

ylist of array_like

List of Y-axis data arrays, each corresponding to one line.

xlabstr

Label for the X-axis.

ylabstr

Label for the Y-axis.

collist of str

Colors for each plotted line.

Returns

None

Displays the plot with multiple signals.

PlottingMulti_SpanSelector(x, y, xlab, ylab, col, saveplt=False)[source]

Plot multiple signals with a horizontal span selector for interactive range selection.

Parameters

xlist of array_like

List of X-axis data arrays for each plotted line.

ylist of array_like

List of Y-axis data arrays for each plotted line.

xlabstr

Label for the X-axis.

ylabstr

Label for the Y-axis.

collist of str

List of color values corresponding to each data series.

Returns

tuple
figmatplotlib.figure.Figure

The generated figure object.

span_selectormatplotlib.widgets.SpanSelector

The interactive span selector widget.

PlottingMultimodeAnalyzer(t, freq, sig, spec, saveplt=False)[source]

Multimode Fourier Analyzer with interactive plot linking time and frequency domains.

Parameters

tarray_like

Time-domain sampling points.

freqarray_like

Frequency-domain sampling points.

sigarray_like

Complex-valued signal in the time domain (FID).

specarray_like

Corresponding spectrum of the signal.

Returns

figmatplotlib.figure.Figure

The main figure object.

fourierFanalyzer

An instance of the Fanalyzer class for interaction handling.

PlottingSphere(Mx, My, Mz, rho_eqQ, plot_vector, scale_datapoints, saveplt=False)[source]

Plot the evolution of magnetization on a Bloch sphere.

Parameters

Mxarray_like

Array of Mx components over time.

Myarray_like

Array of My components over time.

Mzarray_like

Array of Mz components over time.

rho_eqQQuantumState

Equilibrium density matrix wrapped in a custom object.

plot_vectorbool

If True, individual magnetization vectors are shown as arrows.

scale_datapointsint

Controls downsampling of the time points shown.

Returns

None

PlottingTwin(x, y1, y2, xlab, ylab1, ylab2, col1, col2, saveplt=False)[source]

Plot two signals with twin Y-axes.

This method generates a plot where y1 is plotted against x on the left Y-axis, and y2 is plotted against x on a secondary Y-axis (right), allowing comparison of two signals with different scales.

Parameters

xarray_like

1D array for the X-axis data.

y1array_like

1D array for the first Y-axis data (left).

y2array_like

1D array for the second Y-axis data (right).

xlabstr

Label for the X-axis.

ylab1str

Label for the left Y-axis.

ylab2str

Label for the right Y-axis.

col1str

Color for the first plot (y1).

col2str

Color for the second plot (y2).

Returns

None

The function displays the plot and does not return anything.

PlottingTwin_SpanSelector(x, y1, y2, xlab, ylab1, ylab2, col1, col2, saveplt=False)[source]

Plot two signals with twin Y-axes and a horizontal span selector.

This function creates a plot with two Y-axes (left and right), allowing visualization of two datasets y1 and y2 against a common X-axis x, each with its own scale. A span selector tool is included to highlight and annotate a selected horizontal region.

Parameters

xarray_like

1D array representing the X-axis data.

y1array_like

1D array for the primary Y-axis (left).

y2array_like

1D array for the secondary Y-axis (right).

xlabstr

Label for the X-axis.

ylab1str

Label for the left Y-axis (corresponding to y1).

ylab2str

Label for the right Y-axis (corresponding to y2).

col1str

Line color for y1.

col2str

Line color for y2.

Returns

tuple

(fig, span_selector), where fig is the matplotlib Figure object, and span_selector is the interactive selector used to highlight a region on the plot.

Plotting_SpanSelector(x, y, xlab, ylab, col, saveplt=False)[source]

Plot signal with span selector for interactive region selection.

This method plots a signal and adds a horizontal span selector tool to interactively select a region of the plot. It also displays vertical lines marking the selection range and annotates the span width.

Parameters

xarray_like

1D array representing the X-axis data.

yarray_like

1D array representing the Y-axis data.

xlabstr

Label for the X-axis.

ylabstr

Label for the Y-axis.

colstr

Color code or name for the plot line.

Returns

figmatplotlib.figure.Figure

The matplotlib figure object.

span_selectormatplotlib.widgets.SpanSelector

The span selector widget object for interaction.

Source_Doc.PyOR_ProbabilityDensityFunctions module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides probability density functions (PDFs) for use in magnetic resonance simulations and statistical modeling within PyOR.

Functions include Gaussian distributions, Lorentzian distributions, and custom probability models relevant for signal analysis and noise modeling.

PDFgaussian(x: ndarray, std: float, mean: float) ndarray[source]

Compute the normalized Gaussian (normal) probability density function.

Parameters

xnp.ndarray

Array of input values (the variable over which the Gaussian is evaluated).

stdfloat

Standard deviation of the Gaussian distribution.

meanfloat

Mean (center) of the Gaussian distribution.

Returns

np.ndarray

The normalized Gaussian probability density values corresponding to x.

Notes

The Gaussian function is defined as:

PDF(x) = (1 / sqrt(2πσ²)) * exp(- (x - μ)² / (2σ²))

The output is normalized such that the sum of the returned values equals 1. This is useful for discrete approximations of continuous distributions.

Source_Doc.PyOR_QuadrupoleMoment module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides quadrupole moment (Q) values for the electron and various nuclei relevant to magnetic resonance simulations.

The quadrupole moment is important for modeling quadrupolar interactions in NMR and EPR experiments, especially for nuclei with spin > 1/2.

quadrupole(value)[source]

Returns the nuclear electric quadrupole moment of a specified particle.

The nuclear quadrupole moment is a measure of the non-spherical distribution of electric charge within a nucleus. It plays a critical role in quadrupolar interactions observed in NMR and other spectroscopic techniques, especially for nuclei with spin quantum number I ≥ 1.

Parameters:

valuestr
Symbol representing the particle. Common examples include:
  • “E” : Electron

  • “H1” : Proton (Hydrogen-1)

  • “H2” : Deuterium (Hydrogen-2)

  • “C13” : Carbon-13

  • “N14” : Nitrogen-14

  • “N15” : Nitrogen-15

  • “O17” : Oxygen-17

  • “F19” : Fluorine-19

Returns:

float

Nuclear electric quadrupole moment (fm²).

Raises:

AssertionError

If the particle symbol is not found in the predefined QUADRUPOLE dictionary. Users can extend the dictionary by adding values manually as needed.

Example:

quadrupole(“H2”) 0.285783

quadrupole(“N14”) 2.044

Reference:

1. Harris, R. K., Becker, E. D., de Menezes, S. M. C., Goodfellow, R., & Granger, P. (2001). NMR nomenclature. Nuclear spin properties and conventions for chemical shifts (IUPAC Recommendations 2001). Pure and Applied Chemistry, 73(11), 1795–1818. DOI: https://doi.org/10.1351/pac200173111795

  1. Solid State NMR, Principles, Methods, and Applications, Klaus Müller and Marco Geppi

Source_Doc.PyOR_QuantumLibrary module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module defines the QuantumLibrary class, which provides a collection of quantum operations and tools for quantum mechanical systems.

The QuantumLibrary class includes methods for basis construction, tensor operations, commutator evaluation, eigenvalue analysis, partial trace computations, and more, supporting simulations in magnetic resonance and general quantum mechanics.

class QuantumLibrary(class_QS=None)[source]

Bases: object

AntiCommutationSuperoperator(X: QunObj) QunObj[source]

Create the anti-commutation superoperator {X, ⋅} as a matrix acting on vectorized density matrices.

Parameters

XQunObj

Operator to construct anti-commutator superoperator from.

Returns

QunObj

Anti-commutation superoperator.

AntiCommutator(A: QunObj, B: QunObj) QunObj[source]

Compute the anticommutator {A, B} = AB + BA.

Parameters

A, B : QunObj

Returns

QunObj

Anticommutator matrix.

Basis_Bra(dim, index, PrintDefault=False)[source]

Generate a bra basis vector ⟨i| of dimension dim.

Parameters

dimint

Dimension of Hilbert space.

indexint

Index of the basis vector to set to 1.

PrintDefaultbool, optional

Whether to print matrix type info (default is False).

Returns

QunObj

Bra vector as a QunObj.

Basis_Ket(dim, index, PrintDefault=False)[source]

Generate a ket basis vector |i⟩ of dimension dim.

Parameters

dimint

Dimension of Hilbert space.

indexint

Index of the basis vector to set to 1.

PrintDefaultbool, optional

Whether to print matrix type info (default is False).

Returns

QunObj

Ket vector as a QunObj.

Bloch_Vector(theta, phi)[source]

Generate a qubit state vector |ψ⟩ on the Bloch sphere.

Parameters

thetafloat

Polar angle in degrees.

phifloat

Azimuthal angle in degrees.

Returns

QunObj

Bloch state vector as a QunObj.

BlockExtract(Matrix: QunObj, block_index, block_sizes) QunObj[source]

Extract a specific block from a block-diagonal matrix or ket.

Parameters

MatrixQunObj

Input QunObj instance (operator or ket).

block_indexint

Index of the block to extract.

block_sizeslist of tuple

List of (row, col) sizes of each block.

Returns

QunObj

Extracted block as operator or ket.

Bracket(X: QunObj, A: QunObj, Y: QunObj) QunObj[source]

Compute the scalar bracket ⟨X|A|Y⟩ = Tr(X† A Y)

Parameters

XQunObj

First operator or state (conjugated from the left).

AQunObj

Middle operator.

YQunObj

Final operator or state.

Returns

complex

Scalar result of the bracket expression.

CommutationSuperoperator(X: QunObj) QunObj[source]

Create the commutation superoperator [X, ⋅] as a matrix acting on vectorized density matrices.

Parameters

XQunObj

Operator to construct commutator superoperator from.

Returns

QunObj

Commutation superoperator.

Commutator(A: QunObj, B: QunObj) QunObj[source]

Compute the commutator [A, B] = AB - BA.

Parameters

A : QunObj B : QunObj

Returns

QunObj

Commutator matrix.

DMToVec(rho: QunObj) QunObj[source]

Convert a density matrix to a column vector (vectorization) in Liouville space.

Parameters

rhoQunObj

Density matrix.

Returns

QunObj

Vectorized form of the density matrix.

DirectSum(A: QunObj, B: QunObj) QunObj[source]

Compute the direct sum of two QunObj instances.

Parameters

A, BQunObj

Quantum operators or states.

Returns

QunObj

Direct sum matrix or ket.

DirectSumMultiple(*matrices: QunObj) QunObj[source]

Compute direct sum of multiple quantum operators or kets.

Parameters

*matricesQunObj

Arbitrary number of QunObj instances.

Returns

QunObj

Resulting direct sum.

DoubleCommutationSuperoperator(X: QunObj, Y: QunObj) QunObj[source]

Construct the double commutator superoperator [[X, ⋅], Y].

Parameters

XQunObj

First operator.

YQunObj

Second operator.

Returns

QunObj

Superoperator representing [[X, ⋅], Y].

DoubleCommutator(A: QunObj, B: QunObj, rho: QunObj) QunObj[source]

Compute the double commutator [A, [B, ρ]].

Parameters

A, B, rho : QunObj

Returns

QunObj

Result of [[A, [B, rho]]].

Eigen(A: QunObj) tuple[source]

Compute eigenvalues and eigenvectors of a quantum operator.

Parameters

AQunObj

Operator to decompose.

Returns

tuple

(eigenvalues, eigenvectors) where: - eigenvalues: QunObj with shape (1, N) as a row of real parts. - eigenvectors: QunObj with shape (N, N) containing eigenvectors column-wise.

Eigen_Split(A: QunObj) tuple[source]

Compute eigenvalues and eigenvectors of a quantum operator. Eigenvectors are returned as separate QunObj columns.

Parameters

AQunObj

Operator to decompose.

Returns

tuple

(eigenvalues, eigenvector_list) - eigenvalues: QunObj with shape (1, N) - eigenvector_list: list of QunObj, each column vector (N x 1)

Identity(dim)[source]

Create an identity matrix.

Parameters

dimint

Dimension.

Returns

QunObj

Identity matrix.

InnerProduct(A: QunObj, B: QunObj) QunObj[source]

Compute the inner product ⟨A|B⟩.

Parameters

A : QunObj B : QunObj

Returns

QunObj

Scalar inner product as a QunObj.

OuterProduct(A: QunObj, B: QunObj) QunObj[source]

Compute the outer product of two QunObj instances.

Parameters

AQunObj

Ket vector.

BQunObj

Bra vector.

Returns

QunObj

Outer product A ⊗ B† as operator.

PartialTrace(rho: QunObj, keep, Sdim=None) QunObj[source]

Compute the partial trace over specified subsystems of a density matrix.

Parameters

rhoQunObj

Density matrix.

keeplist of int

Indices of subsystems to retain.

Sdimlist of int, optional

Dimensions of subsystems (defaults to class_QS.Sdim).

Returns

QunObj

Reduced density matrix after tracing out unlisted subsystems.

Purity(A: QunObj) QunObj[source]

Calculate the purity of a quantum state: Tr(ρ²).

Parameters

AQunObj

Density matrix.

Returns

QunObj

Scalar result of the purity calculation.

SSpinOp(X, String, PrintDefault=False)[source]

Construct single spin operators (Sx, Sy, Sz, S+, S-) for a given spin S.

Parameters

Xfloat

Spin quantum number (e.g., 1/2, 1, 3/2).

Stringstr

Operator type: ‘x’, ‘y’, ‘z’, ‘p’, or ‘m’.

PrintDefaultbool, optional

Whether to print matrix type info.

Returns

QunObj

Requested spin operator matrix.

TensorProduct(A: QunObj, B: QunObj) QunObj[source]

Compute the Kronecker product (tensor product) of two QunObj instances.

Parameters

A, BQunObj

Quantum operators or states.

Returns

QunObj

Tensor product result.

TensorProductMultiple(*matrices: QunObj) QunObj[source]

Compute tensor product of multiple QunObj instances.

Parameters

*matricesQunObj

Arbitrary number of quantum operators or states.

Returns

QunObj

Tensor product of all matrices.

VecToDM(vec: QunObj, shape: tuple) QunObj[source]

Convert a vectorized density matrix back into matrix form.

Parameters

vecQunObj

Vectorized density matrix.

shapetuple

Shape (rows, cols) of the original density matrix.

Returns

QunObj

Reshaped density matrix.

Zeros(dim)[source]

Create a zero matrix.

Parameters

dimint

Dimension.

Returns

QunObj

Zero matrix.

Source_Doc.PyOR_QuantumObject module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module defines the QunObj (Quantum Object) class, a flexible object for representing quantum states (kets, bras) and operators.

The QunObj class supports standard quantum mechanical operations, including Hermitian conjugation, tensor products, inner products, outer products, expectation value calculations, and more.

class QunObj(data, Type=None, DType=<class 'complex'>, PrintDefault=False)[source]

Bases: object

Adjoint()[source]

Return the Hermitian conjugate (dagger) of the quantum object.

Returns

QunObj

The conjugate transpose of the object.

Basis(basis_name)[source]

Perform a basis transformation using a predefined transformation matrix.

For quantum states (type=’ket’): \(|\psi\rangle \rightarrow U|\psi\rangle\) For operators (type=’operator’): \(O \rightarrow U^\dagger O U\)

Currently supported basis names: - ‘singlettriplet’ : Transformation to singlet-triplet basis.

Parameters

basis_namestr

Name of the predefined basis.

Returns

QunObj

The quantum object in the new basis.

Raises

ValueError

If an unsupported basis name is provided or type is unsupported.

BasisChange(U)[source]

Perform a basis transformation on the quantum object using transformation matrix U.

For quantum states (type=’ket’): \(|\psi\rangle \rightarrow U|\psi\rangle\) For operators (type=’operator’): \(O \rightarrow U^\dagger O U\)

Parameters

UQunObj

The unitary transformation matrix.

Returns

QunObj

The quantum object expressed in the new basis.

Raises

TypeError

If U is not a QunObj.

ValueError

If called on an unsupported object type (e.g., ‘bra’).

Commute(other, matrix=False, tol=None)[source]

Check if two QunObj instances commute.

Parameters

other : QunObj

Returns

bool

True if commutator is zero, False otherwise.

Conjugate()[source]

Return the complex conjugate of the quantum object.

Returns

QunObj

The complex conjugated quantum object.

Expectation(operator)[source]

Compute the expectation value of an operator.

For a state \(|\psi\rangle\): \(\langle \psi | A | \psi \rangle\) For a density matrix \(\rho\): \(\mathrm{Tr}(\rho A)\)

Parameters

operatorQunObj

Operator for which to compute the expectation value.

Returns

complex

Expectation value.

Raises

TypeError

If input is not a QunObj.

Expm()[source]

Compute the matrix exponential exp(A).

Returns

QunObj

The matrix exponential of the object.

Hermitian()[source]

Check whether the matrix is Hermitian (A = A†).

Returns

bool

True if Hermitian, False otherwise.

InnerProduct(other)[source]

Inner product: ⟨ψ|φ⟩ or Tr(A†B).

Parameters

other : QunObj

Returns

complex

Inverse()[source]

Compute the matrix inverse.

Returns

QunObj

The inverse of the quantum object.

Raises

np.linalg.LinAlgError

If the matrix is singular or not square.

Inverse2PI()[source]

Divide all elements of the quantum object by 2π.

Useful for converting angular frequency to frequency units.

Returns

QunObj

The scaled object.

NeumannEntropy()[source]

Compute the Von Neumann entropy S = -Tr(ρ log ρ).

Returns

float

The entropy value.

Norm()[source]

Compute the Frobenius norm of the matrix.

Returns

float

Frobenius norm ||A||_F.

Norm_HZ()[source]

Compute the Frobenius norm scaled by 1 / (2π).

Returns

float

Scaled Frobenius norm.

Normalize()[source]

Normalize the quantum state or operator.

Returns

QunObj

Normalized object.

OuterProduct(other)[source]

Outer product: |ψ⟩⟨φ|.

Parameters

other : QunObj

Returns

QunObj

Positive()[source]

Print whether all diagonal elements are non-negative.

Useful for checking if a density matrix is physical.

Purity()[source]

Compute the purity Tr(ρ²) of a density matrix.

Returns

float

Purity value (1 for pure states).

Rotate(theta_rad, operator)[source]

Apply a unitary rotation to the quantum object.

For operators: \(\rho \rightarrow U \rho U^\dagger\) where \(U = \exp(-i \theta A)\)

For states: \(|\psi\rangle \rightarrow U |\psi\rangle\) where \(U = \exp(-i \theta A)\)

Parameters

theta_radfloat

Rotation angle in degrees.

operatorQunObj

Hermitian operator generating the rotation.

Returns

QunObj

Rotated quantum object.

Raises

TypeError

If operator is not a QunObj.

Round(roundto)[source]

Round the entries in the quantum object to a given decimal place.

Parameters

roundtoint

Number of decimal places to round.

Returns

QunObj

Rounded object.

TensorProduct(other)[source]

Compute tensor product with another QunObj.

Parameters

other : QunObj

Returns

QunObj

Tolarence(tol)[source]

Zero out all elements with magnitude below the specified tolerance.

Parameters

tolfloat

Tolerance value.

Returns

QunObj

Cleaned object with small elements set to zero.

Trace()[source]

Compute the trace of the matrix.

Returns

complex

The trace value.

Tranpose()[source]

Return the transpose of the quantum object (without complex conjugation).

Returns

QunObj

The transposed quantum object.

Source_Doc.PyOR_QuantumSystem module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module defines the QuantumSystem class, which represents composite quantum systems consisting of multiple interacting particles or subsystems.

The QuantumSystem class provides tools for managing the total system Hilbert space, constructing composite states and operators, and simulating evolution under system-wide Hamiltonians.

class QuantumSystem(SpinList, PrintDefault=True)[source]

Bases: object

QuantumSystem: Central class in PyOR for defining and manipulating multi-spin quantum systems.

This class sets up the quantum system based on a list of spins, initializes physical and numerical parameters, manages spin operators, relaxation mechanisms, acquisition settings, plotting preferences, and state evolution.

Parameters

SpinListdict

Dictionary mapping spin labels to spin types (e.g., {‘I’: ‘1H’, ‘S’: ‘13C’})

PrintDefaultbool, optional

If True, prints all default system settings and parameters.

Attributes

SpinListdict

User-defined spin system.

SpinDiclist

List of spin keys from the dictionary.

SpinNamenp.array

List of spin names (e.g., [‘1H’, ‘13C’]).

SpinIndexdict

Dictionary mapping spin label to index.

slistnp.array

List of spin quantum numbers.

Sdimnp.array

Dimensions of each individual spin Hilbert space.

Vdimint

Dimension of the total Hilbert space.

Ldimint

Dimension of the Liouville space (Vdim^2).

hbarEQ1bool

Toggle to treat ℏ = 1 in Hamiltonians.

Gammalist

Gyromagnetic ratios of spins.

B0float

Static magnetic field (Tesla).

OFFSET, OMEGA_RFdict

Offset and rotating frame frequencies.

Jlistnp.ndarray

J-coupling matrix.

Dipole_Pairslist

List of dipolar-coupled spin index pairs.

Various attributes…

Many more attributes initialized for relaxation, plotting, acquisition, etc.

Adjoint(A)[source]

Compute the adjoint (Hermitian conjugate) of an operator.

Parameters

Andarray

Operator or state vector.

Returns

ndarray

Hermitian conjugate of the input.

BasisChange_Operator_Local(O, U)[source]

Transform an operator using the given transformation matrix.

Parameters

Onp.ndarray

Operator in the original basis.

UQunObj

Transformation matrix as a QunObj.

Returns

np.ndarray

Operator in the new basis.

BasisChange_SpinOperators_Local(Sop, U)[source]

Transform an array of spin operators using a transformation matrix.

Parameters

Sopnp.ndarray

Array of shape (N, dim, dim) containing spin operators (e.g., [Sx, Sy, Sz]).

UQunObj

Transformation matrix as a QunObj.

Returns

np.ndarray

Transformed spin operators as an array of shape (N, dim, dim).

Bracket(X: QunObj, A: QunObj, Y: QunObj) float[source]

Compute the bracket ⟨X|A|Y⟩ / ⟨X|Y⟩.

Used for angular momentum evaluation.

Parameters

X, A, YQunObj

Operators and state vectors.

Returns

float

Result of ⟨X|A|Y⟩ normalized by ⟨X|Y⟩.

Convert_EnergyTOFreqUnits(H)[source]

Convert Hamiltonian from energy units (Joules) to angular frequency units (rad/s).

Parameters

Hfloat or ndarray

Hamiltonian in energy units.

Returns

float or ndarray

Hamiltonian in angular frequency units.

Convert_FreqUnitsTOEnergy(H)[source]

Convert Hamiltonian from angular frequency units to energy units (Joules).

Parameters

Hfloat or ndarray

Hamiltonian in angular frequency units.

Returns

float or ndarray

Hamiltonian in energy units.

Eigen(A: QunObj) tuple[source]

Compute eigenvalues and eigenvectors of a quantum object.

Parameters

AQunObj

The quantum object (operator) to decompose.

Returns

tuple

(eigenvalues as ndarray, eigenvectors as QunObj)

Eigen_Split(A: QunObj) tuple[source]

Compute eigenvalues and return eigenvectors as a list of QunObj.

Parameters

AQunObj

Quantum operator.

Returns

tuple

(eigenvalues as ndarray, eigenvectors as list of QunObj column vectors)

HztoPPM(freq_sample, ref)[source]

Convert frequency from Hz to PPM.

Parameters

freq_samplefloat

Frequency in Hz.

reffloat

Reference frequency in Hz.

Returns

float

Chemical shift in ppm.

IndividualThermalDensityMatrix()[source]

Initialize and assign the individual spin thermal density matrices.

For each spin, constructs the density matrix using Boltzmann distribution in the Zeeman basis and stores it as an attribute.

Initialize()[source]

Initialize the quantum system: - Compute spin operators (Sx, Sy, Sz, etc.) - Populate particle-related properties (gamma, quadrupole, etc.)

JcoupleValue(x, y, value)[source]

Set scalar J coupling constant between two spins.

Parameters

xstr

Label of spin 1.

ystr

Label of spin 2.

valuefloat

J coupling constant in Hz.

MagQnuSingle(X)[source]

Return magnetic quantum number values for an individual spin.

Parameters

Xfloat

Spin quantum number.

Returns

np.ndarray

Array of magnetic quantum numbers: [X, X-1, …, -X].

MagQnuSystem()[source]

Return total magnetic quantum numbers (Sz expectation) for each Zeeman state.

Returns

np.ndarray

Diagonal values of total Sz.

PPMtoHz(ppm, ref)[source]

Convert chemical shift from PPM to Hz.

Parameters

ppmfloat

Chemical shift in ppm.

reffloat

Reference frequency in Hz.

Returns

float

Frequency in Hz.

ParticleParameters()[source]

Initialize particle properties for each spin.

Automatically retrieves constants from PyOR_Particle.

PyOR_Version()[source]

Print version info for PyOR and its dependencies.

SpinOperator(PrintDefault=False)[source]

Generate spin operators Sx, Sy, Sz, Sp, Sm for all spins in the system.

Also assigns: - self.Sx_, self.Sy_, self.Sz_, self.Sp_, self.Sm_ : ndarray - self.Jsquared (total angular momentum operator): QunObj - Individual spin operators as class attributes (e.g., Ix, Iy, Iz, etc.)

SpinOperator_SpinQunatulNumber_List(SpinQNlist)[source]

Generate full-system spin operators from a list of spin quantum numbers.

Parameters

SpinQNlistlist of float

List of spin quantum numbers [s1, s2, …, sn].

Returns

tuple of np.ndarray

Arrays of shape (n, dim, dim) for Sx, Sy, and Sz.

SpinOperator_Sub(PrintDefault=False)[source]

Generate subsystem spin operators for each individual spin.

Stores operators with suffix _sub for each spin label. Example: Ix_sub, Iy_sub, Iz_sub, Ip_sub, Im_sub, Iid_sub

SpinOperatorsSingleSpin(X)[source]

Generate spin operators (Sx, Sy, Sz) for a single spin quantum number.

Parameters

Xfloat

Spin quantum number (e.g., 1/2, 1, 3/2).

Returns

np.ndarray

A 3D array with shape (3, dim, dim) representing [Sx, Sy, Sz] matrices.

Reference:

Quantum Mechanics: Concepts and Applications, Nouredine Zettili.

State(MagQunList)[source]

Construct a Zeeman state vector from magnetic quantum numbers of individual spins.

Parameters

MagQunListdict

Dictionary of spin labels to their magnetic quantum numbers.

Returns

QunObj

Tensor product state corresponding to the given Zeeman state.

State_SpinQuantumNumber(A: QunObj)[source]

Find total spin and magnetic quantum number for a system state.

Parameters

AQunObj

State vector.

Returns

tuple

(Total spin l, magnetic quantum number m)

State_SpinQuantumNumber_SpinOperators(A: QunObj, Ssq: QunObj, Sz: QunObj)[source]

Extract spin quantum numbers from a given state and spin operators.

Parameters

AQunObj

State vector.

SsqQunObj

Total spin-squared operator.

SzQunObj

Total Sz operator.

Returns

tuple

(Total spin l, magnetic quantum number m)

States_Coupled(DicList)[source]

Construct tensor product state(s) from a list of Zeeman or coupled spin dictionaries.

Supports both simple Zeeman basis and Clebsch-Gordan combined basis (under testing).

Parameters

DicListlist

List of spin label dictionaries or nested dictionaries with CG specification.

Returns

QunObj

Tensor product of eigenstates.

Unitarytransformation_ZeemanToPMZ()[source]

Constructs and returns the unitary transformation matrix that changes the basis from the Zeeman basis to the PMZ (Product of Mz basis for Spin-1/2) basis.

This transformation is essential for converting operators or states expressed in the Zeeman basis to the PMZ basis, which may be more convenient for certain quantum simulations or analyses.

Returns:

U (ndarray): Unitary transformation matrix from Zeeman basis to PMZ basis.

Update()[source]

Update system settings after parameter changes.

Useful after modifying B0, OMEGA_RF, OFFSET, etc. Recomputes internal attributes used in simulation and spin labels.

ZeemanBasis_Bra()[source]

Return list of basis bras as strings for the full system.

Returns

list of str

Zeeman basis state labels like ⟨1/2,-1/2|.

ZeemanBasis_Ket()[source]

Return list of basis kets as strings for the full system.

Returns

list of str

Zeeman basis state labels like |1/2,-1/2⟩.

Source_Doc.PyOR_Relaxation module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module defines the Relaxation class, which provides methods to model relaxation processes in magnetic resonance simulations.

The Relaxation class includes functionalities for simulating longitudinal (T1) and transverse (T2) relaxation, relaxation superoperators, and decoherence mechanisms relevant to spin dynamics.

class RelaxationProcess(class_QS)[source]

Bases: object

Adjoint(A)[source]

Return adjoint (Hermitian conjugate) of operator A

EigFreq_ProductOperator_H(Hz, opBasis)[source]

Compute eigenfrequency in Hilbert space.

Parameters:

Hznp.ndarray

Hamiltonian (Hilbert space)

opBasisnp.ndarray

Operator to analyze

Returns:

float

Eigenfrequency in Hz

EigFreq_ProductOperator_L(Hz_L, opBasis_L)[source]

Compute the eigenfrequency of a product operator in Liouville space.

Parameters:

Hz_Lnp.ndarray

Liouvillian Hamiltonian superoperator

opBasis_Lnp.ndarray

Vectorized operator (in Liouville space)

Returns:

float

Eigenfrequency in Hz

InnerProduct(A, B)[source]

Inner product of two operators or vectors: ⟨A|B⟩

Lindblad_Dissipator(A, B)[source]

Compute the Lindblad dissipator in Liouville space.

Parameters:

Anp.ndarray

Operator A

Bnp.ndarray

Operator B

Returns:

np.ndarray

Lindblad dissipator superoperator

Lindblad_Dissipator_Hilbert(A, B, rho)[source]

Compute Lindblad dissipator directly in Hilbert space.

Parameters:

Anp.ndarray

Operator A

Bnp.ndarray

Operator B

rhonp.ndarray

Density matrix

Returns:

np.ndarray

Result of applying Lindblad dissipator

Lindblad_TemperatureGradient(t)[source]

Calculate the inverse temperature at time t for a linear temperature gradient.

Parameters:

tfloat

Time (s)

Returns:

float

Instantaneous inverse temperature

Relaxation(rho=None, Rprocess=None)[source]

Compute the relaxation superoperator or apply relaxation to the given density matrix based on the selected relaxation process, propagation space, and master equation.

Parameters

rhondarray, optional

The input density matrix to apply relaxation on. Required for Hilbert space propagation.

Rprocessstr, optional

The relaxation model to apply. If None, the default self.Rprocess is used. Supported options include: - “No Relaxation” - “Phenomenological” - “Phenomenological Matrix” - “Auto-correlated Random Field Fluctuation” - “Phenomenological Random Field Fluctuation” - “Auto-correlated Dipolar Heteronuclear Ernst” - “Auto-correlated Dipolar Homonuclear Ernst” - “Auto-correlated Dipolar Homonuclear”

Returns

ndarray or QunObj

The relaxation superoperator (in Liouville space), or its action on the density matrix (in Hilbert space), depending on the system settings.

Notes

  • MasterEquation and PropagationSpace determine how the relaxation is calculated.

  • This function supports Redfield and Lindblad equations.

  • It handles both Hilbert and Liouville space propagation.

  • For “Hilbert” space, this returns the applied relaxation: R(rho)

  • For “Liouville” space, this returns the relaxation superoperator R

  • Reference: Principles of Nuclear Magnetic Resonance in One and Two Dimensions, R. R. Ernst et al.

RelaxationRate_H(AQ, BQ)[source]

Compute relaxation rate in Hilbert space: <A|R(B)> / <A|A>

Parameters:

AQQunObj

First operator A

BQQunObj

Second operator B

Returns:

float

Relaxation rate (unit depends on RProcess model)

RelaxationRate_L(AQ, BQ, Relax_LQ)[source]

Compute relaxation rate in Liouville space: <A|R|B> / <A|A>

Parameters:

AQQunObj

Operator A (Hilbert space)

BQQunObj

Operator B (Hilbert space)

Relax_LQQunObj

Relaxation superoperator in Liouville space

Returns:

float

Relaxation rate

Relaxation_CoherenceDecay(coherence_orders, relaxa_rate, diagonal_relaxa_rate=0, default_rate=0)[source]

Apply relaxation decay to selected coherence orders, with proper separation of true diagonal elements.

Parameters: - coherence_orders (list or set): coherence orders to apply relaxation to (off-diagonal). - relaxa_rate (float): relaxation rate to apply to specified off-diagonal coherence orders. - diagonal_relaxa_rate (float): relaxation rate for true diagonal elements (population terms). - default_rate (float): relaxation rate for all other coherence orders.

Returns: - Modified coherence Zeeman array with relaxation rates applied.

SpectralDensity(W, tau)[source]

Spectral density function J(ω) for Redfield theory.

Reference: Richard R. Ernst et al., “Principles of Nuclear Magnetic Resonance in One and Two Dimensions”, p.56

Parameters:

Wfloat

Angular frequency

taufloat

Correlation time (s)

Returns:

float

Spectral density J(ω)

SpectralDensity_Lb(W, tau)[source]

Spectral density with thermal correction for Lindblad master equation.

Reference: C. Bengs, M.H. Levitt, JMR 310 (2020), Eq. 140

Parameters:

Wfloat

Angular frequency

taufloat

Correlation time (s)

Returns:

float

Thermally corrected spectral density J(ω)

Spherical_Tensor(spin, Rank, m, Sx, Sy, Sz, Sp, Sm)[source]

Spherical tensor components (Rank 1 and 2).

Reference: S.J. Elliott, J. Chem. Phys. 150, 064315 (2019)

Parameters:

spinlist of int

Spin indices (e.g. [0,1])

Rankint

Tensor rank (1 or 2)

mint

Tensor component (-Rank to +Rank)

Returns:

np.ndarray

Tensor operator T(Rank, m)

Spherical_Tensor_Ernst(spin, Rank, m, Sx, Sy, Sz, Sp, Sm)[source]

Ernst-form spherical tensor operators for dipolar relaxation.

Reference: Ernst et al., “Principles of Nuclear Magnetic Resonance in One and Two Dimensions”, p. 56

Parameters:

spinlist[int]

Spin indices [i, j]

Rankint

Tensor rank (only Rank=2 supported here)

mint

Component index: -2, -1, 0, 1, 2

Returns:

np.ndarray

Spherical tensor operator T(Rank, m)

Spherical_Tensor_Ernst_P(spin, Rank, m, Sx, Sy, Sz, Sp, Sm)[source]

Ernst spherical tensors with frequency label.

Used in relaxation models where each tensor component contributes at a specific Larmor frequency.

Returns both:
  • Tensor operator T(Rank, m)

  • Associated frequency (for spectral density calculation)

Parameters:

spinlist[int]

Spin indices

Rankint

Tensor rank (2)

mint

Component index or identifier (e.g. 10, 20, -11, etc.)

Returns:

Tuple[np.ndarray, float]

Spherical tensor and its corresponding frequency in Hz

Vector_L(X)[source]

Vectorize the operator X for Liouville space calculations.

Source_Doc.PyOR_Rotation module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides functions related to rotation operations in quantum mechanics and magnetic resonance simulations.

Functions include generating rotation matrices, applying rotations to quantum states and operators, and supporting Euler angle-based transformations.

RotateEuler(alpha, beta, gamma)[source]

Performs a rotation using Euler angles (α, β, γ) in three-dimensional space.

This function computes the overall rotation matrix by applying a series of three rotations around the Z-axis, Y-axis, and Z-axis again, using the provided Euler angles: - alpha (α) : rotation about the Z-axis - beta (β) : rotation about the Y-axis - gamma (γ) : rotation about the Z-axis

The rotation order follows the intrinsic Tait-Bryan angle convention (Z-Y-Z), meaning: 1. Rotate by α around the Z-axis. 2. Rotate by β around the Y-axis. 3. Rotate by γ around the Z-axis again.

Parameters:

alphafloat

The angle of rotation about the Z-axis (α) in degrees.

betafloat

The angle of rotation about the Y-axis (β) in degrees.

gammafloat

The angle of rotation about the Z-axis (γ) in degrees.

Returns:

numpy.ndarray

A 3x3 numpy array representing the resulting rotation matrix for the combined Euler rotations.

Notes:

The combined rotation is calculated as:

R = RotateZ(α) * RotateY(β) * RotateZ(γ)

where:
  • RotateZ(α) applies a counterclockwise rotation by α around the Z-axis.

  • RotateY(β) applies a counterclockwise rotation by β around the Y-axis.

  • RotateZ(γ) applies a counterclockwise rotation by γ around the Z-axis.

RotateX(theta)[source]

Rotates a vector or tensor about the X-axis by a given angle.

This function returns a 3x3 rotation matrix that can be applied to a vector or tensor to perform a rotation about the X-axis in three-dimensional space. The angle \(\theta\) is provided in degrees and is internally converted to radians.

Parameters

thetafloat

The angle of rotation in degrees. The function converts this to radians for the rotation calculation.

Returns

numpy.ndarray

A 3x3 NumPy array representing the rotation matrix for a counterclockwise rotation about the X-axis by the angle \(\theta\).

Notes

The rotation matrix for a counterclockwise rotation about the X-axis is:

\[\begin{split}\begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos\theta & -\sin\theta \\ 0 & \sin\theta & \cos\theta \end{bmatrix}\end{split}\]

where \(\theta\) is the angle of rotation in radians.

RotateY(theta)[source]

Rotates a vector or tensor about the Y-axis by a given angle.

This function returns a 3x3 rotation matrix that can be applied to a vector or tensor to perform a rotation about the Y-axis in three-dimensional space. The angle \(\theta\) is provided in degrees and is internally converted to radians.

Parameters

thetafloat

The angle of rotation in degrees. The function converts this to radians for the rotation calculation.

Returns

numpy.ndarray

A 3x3 NumPy array representing the rotation matrix for a counterclockwise rotation about the Y-axis by the angle \(\theta\).

Notes

The rotation matrix for a counterclockwise rotation about the Y-axis is:

\[\begin{split}\begin{bmatrix} \cos\theta & 0 & \sin\theta \\ 0 & 1 & 0 \\ -\sin\theta & 0 & \cos\theta \end{bmatrix}\end{split}\]

where \(\theta\) is the angle of rotation in radians.

RotateZ(theta)[source]

Rotates a vector or tensor about the Z-axis by a given angle.

This function returns a 3x3 rotation matrix that can be applied to a vector or tensor to perform a rotation about the Z-axis in three-dimensional space. The angle \(\theta\) is provided in degrees and is internally converted to radians.

Parameters

thetafloat

The angle of rotation in degrees. The function converts this to radians for the rotation calculation.

Returns

numpy.ndarray

A 3x3 NumPy array representing the rotation matrix for a counterclockwise rotation about the Z-axis by the angle \(\theta\).

Notes

The rotation matrix for a counterclockwise rotation about the Z-axis is:

\[\begin{split}\begin{bmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{bmatrix}\end{split}\]

where \(\theta\) is the angle of rotation in radians.

Wigner_D_Matrix(rank, alpha, beta, gamma)[source]

Computes the Wigner D-matrix for a given rank and three Euler angles (alpha, beta, gamma).

The Wigner D-matrix is used to describe rotations in quantum mechanics and is particularly useful in representing the rotation of angular momentum eigenstates. The matrix is constructed using the three Euler angles: alpha (\(\alpha\)), beta (\(\beta\)), and gamma (\(\gamma\)), which correspond to rotations around the Z-axis, Y-axis, and Z-axis again, respectively.

Parameters

rankint

The angular momentum quantum number \(l\) for which the Wigner D-matrix is computed. The resulting matrix is of size \((2l + 1) \times (2l + 1)\).

alphafloat

Rotation angle around the first Z-axis (\(\alpha\)) in degrees.

betafloat

Rotation angle around the Y-axis (\(\beta\)) in degrees.

gammafloat

Rotation angle around the second Z-axis (\(\gamma\)) in degrees.

Returns

QunObj

A quantum object wrapping the computed Wigner D-matrix, which is a unitary matrix of size \((2l + 1) \times (2l + 1)\).

Notes

The Wigner D-matrix for the given Euler angles is computed using the following expression:

\[D^l_{m,m'}(\alpha, \beta, \gamma) = \exp(-i \alpha S_z) \cdot \exp(-i \beta S_y) \cdot \exp(-i \gamma S_z)\]

where:

  • \(S_z\) is the spin operator along the Z-axis.

  • \(S_y\) is the spin operator along the Y-axis.

  • The angles \(\alpha\), \(\beta\), and \(\gamma\) are the Euler angles in radians.

The Wigner D-matrix represents the rotation of quantum states under the specified Euler angles.

See Also

expm : Matrix exponential function QLib.SSpinOp : Generates spin operators for a given rank

References

  1. Nouredine Zettili, Quantum Mechanics: Concepts and Applications.

Wigner_d_Matrix(rank, beta)[source]

Computes the Wigner d-matrix for a given rank and angle.

The Wigner d-matrix is used to represent the rotation of spherical harmonics or quantum states under rotations in quantum mechanics. It is often used in various fields, including nuclear magnetic resonance (NMR) and quantum chemistry. This function computes the Wigner d-matrix for a given rank (angular momentum quantum number) and a rotation angle \(\beta\) (in degrees).

Parameters

rankint

The rank (or angular momentum quantum number) for which the Wigner d-matrix is computed. This corresponds to the quantum number \(l\) in the Wigner d-matrix formulation.

betafloat

The rotation angle \(\beta\) in degrees. The function converts this to radians for the computation.

Returns

QunObj

A quantum object wrapping the computed Wigner d-matrix. The matrix is unitary and has shape \((2l + 1) \times (2l + 1)\).

Notes

The Wigner d-matrix \(d^l_{m,m'}(\beta)\) describes how spherical harmonics or spin states transform under rotations. In this function:

  • \(l\) is the angular momentum quantum number (rank)

  • \(\beta\) is the rotation angle around the Y-axis, in degrees

  • The function uses the spin operator \(S_y\) and applies the exponential:

\(\exp(-i \, \beta \, S_y)\)

See Also

expm : Matrix exponential function. QLib.SSpinOp : Function to generate spin operators.

References

  1. Nouredine Zettili, Quantum Mechanics: Concepts and Applications.

Source_Doc.PyOR_SignalProcessing module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides functions for signal processing in magnetic resonance simulations, including time-domain and frequency-domain transformations.

Functions include Fourier transforms, filtering operations, phase corrections, and signal normalization techniques tailored for NMR and EPR data.

FourierTransform(signal, fs, zeropoints)[source]

Computes the Fourier Transform of a time-domain signal with optional zero filling.

This function performs a one-dimensional FFT of a signal and returns the frequency axis and the corresponding complex spectrum. The result is centered using fftshift, and zero-filling is applied to improve spectral resolution.

Parameters

signalarray-like

Time-domain signal (1D array).

fsfloat

Sampling frequency in Hz (not angular). This represents the total bandwidth.

zeropointsint

Zero-filling factor. Total FFT points = zeropoints × len(signal).

Returns

freqndarray

Frequency axis in Hz, centered around 0 using fftshift.

spectrumndarray

Complex frequency-domain representation of the input signal.

FourierTransform2D(signal, fs1, fs2, zeropoints)[source]

Perform a 2D Fourier Transform on a 2D signal array.

This function is commonly used in 2D NMR to transform a time-domain signal into the frequency domain along both the indirect (F1) and direct (F2) dimensions.

Parameters

signalndarray (2D)

2D signal array with dimensions [F2, F1] (rows: direct, cols: indirect).

fs1float

Sampling frequency for the F1 (indirect) dimension.

fs2float

Sampling frequency for the F2 (direct) dimension.

zeropointsint

Zero-filling factor, multiplies each dimension size for padding.

Returns

freq1ndarray

Frequency axis for the F1 (indirect) dimension.

freq2ndarray

Frequency axis for the F2 (direct) dimension.

spectrumndarray (2D)

Complex-valued frequency-domain spectrum after 2D FFT and shift.

FourierTransform2D_F1(signal, fs, zeropoints)[source]

Perform a 1D Fourier Transform along the F1 (indirect) dimension of a 2D NMR signal.

This function applies a 1D FFT to each column (F1 dimension) of the signal matrix and returns the frequency axis and spectrum.

Parameters

signalndarray (2D)

2D time-domain signal array with dimensions [F2, F1].

fsfloat

Sampling frequency for the F1 dimension.

zeropointsint

Zero-filling factor for F1 dimension (not used here).

Returns

freqndarray

Frequency axis for the F1 (indirect) dimension.

spectrumndarray (2D)

Transformed signal with FFT applied along F1.

FourierTransform2D_F2(signal, fs, zeropoints)[source]

Perform a 1D Fourier Transform along the F2 (direct) dimension of a 2D NMR signal.

Applies FFT row-wise (along the F2 axis) and returns the frequency axis and the resulting spectrum.

Parameters

signalndarray

2D time-domain signal array with dimensions [F2, F1].

fsfloat

Sampling frequency for the F2 (direct) dimension.

zeropointsint

Zero-filling factor to improve frequency resolution (multiplied to original length).

Returns

freqndarray

Frequency axis corresponding to the F2 dimension.

spectrumndarray

Fourier-transformed 2D spectrum along F2.

PhaseAdjust_PH0(spectrum, PH0)[source]

Applies zero-order phase correction to a spectrum.

This function performs a uniform phase shift (PH0) across the entire frequency-domain spectrum. This is typically used to correct for a constant phase error introduced by the acquisition system or processing.

Parameters

spectrumndarray

Complex spectrum (1D or 2D array).

PH0float

Zero-order phase in degrees.

Returns

ndarray

Phase-adjusted spectrum.

PhaseAdjust_PH1(freq, spectrum, pivot, slope)[source]

Applies first-order phase correction to a spectrum.

First-order phase correction applies a frequency-dependent phase shift, typically to correct dispersion lineshape distortions. The phase is zero at the pivot frequency and changes linearly with the slope.

Parameters

freqndarray

Frequency axis (same length as the spectrum).

spectrumndarray

Complex-valued frequency-domain spectrum.

pivotfloat

Frequency (in Hz or ppm) at which the phase correction is zero.

slopefloat

Slope of the phase correction in degrees per kHz.

Returns

ndarray

Spectrum after applying first-order phase correction.

WindowFunction(t, signal, LB)[source]

Applies an exponential window function to simulate signal decay.

This function multiplies a time-domain signal by an exponential decay factor, typically used in signal processing to apply line broadening in NMR and other spectroscopy techniques.

Parameters

tarray-like

Time array (same length as the signal).

signalarray-like

The input signal array to be decayed.

LBfloat

Line broadening factor (decay rate).

Returns

array-like

The decayed signal after applying the exponential window.

Source_Doc.PyOR_SphericalTensors module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides functions related to spherical tensors, which are essential in the quantum mechanical description of angular momentum operators and their transformations.

Functions include the construction of irreducible spherical tensors, tensor operator manipulation, and transformation properties under rotations, relevant to magnetic resonance simulations.

MatrixToSphericalTensors(AQ)[source]

Converts a 3x3 Cartesian matrix into its corresponding spherical tensor components.

This function decomposes a Cartesian second-rank tensor (typically used in NMR or other physics applications) into spherical tensor components of rank 0 (isotropic), rank 1 (antisymmetric), and rank 2 (symmetric traceless). The decomposition follows the formalism described in Pascal P. Man’s 2014 paper on Cartesian and spherical tensors in NMR Hamiltonians.

Parameters:

AQnumpy.matrix or similar object

A 3x3 matrix (usually Hermitian or real) representing the Cartesian tensor to be converted. AQ must be a quantum object with attribute “data”.

Returns:

dict
A dictionary containing the spherical tensor components:
  • “rank0”: complex

    The rank-0 (isotropic) component T(0,0).

  • “rank1”: list of complex

    The rank-1 (antisymmetric) components [T(1,1), T(1,0), T(1,-1)].

  • “rank2”: list of complex

    The rank-2 (symmetric traceless) components [T(2,2), T(2,1), T(2,0), T(2,-1), T(2,-2)].

Reference:

1. Pascal P. Man, “Cartesian and Spherical Tensors in NMR Hamiltonians”, Concepts in Magnetic Resonance Part A, 2014. https://doi.org/10.1002/cmr.a.21289 (Equations 275 to 281 are particularly relevant)

  1. Tensors and Rotations in NMR, LEONARD J. MUELLER, https://doi.org/10.1002/cmr.a.20224

SphericalTensorsToMatrix(Sptensor)[source]

Reconstructs a 3x3 complex Cartesian matrix from its spherical tensor components.

This function performs the inverse operation of MatrixToSphericalTensors. It takes a dictionary containing spherical tensor components of ranks 0 (isotropic), 1 (antisymmetric), and 2 (symmetric traceless), and reconstructs the corresponding Cartesian second-rank tensor as a 3x3 complex NumPy array.

Parameters:

Sptensordict
Dictionary containing spherical tensor components with the following keys:
  • ‘rank0’: complex

    Scalar representing the isotropic component T(0,0).

  • ‘rank1’: list of 3 complex numbers

    Antisymmetric components [T(1,1), T(1,0), T(1,-1)].

  • ‘rank2’: list of 5 complex numbers

    Symmetric traceless components [T(2,2), T(2,1), T(2,0), T(2,-1), T(2,-2)].

Returns:

QunObj

A custom object (assumed from context) wrapping a 3x3 complex NumPy array that represents the reconstructed Cartesian tensor.

Notes:

  • The spherical to Cartesian transformation follows standard NMR tensor decomposition conventions, particularly those described in:

  • This function assumes QunObj is a class or wrapper that accepts a 3x3 complex NumPy array. Ensure QunObj is defined in your codebase or environment.

See Also:

MatrixToSphericalTensorsFunction that performs the forward decomposition from a

Cartesian tensor to spherical tensor components.

Reference:

  1. Tensors and Rotations in NMR, LEONARD J. MUELLER, https://doi.org/10.1002/cmr.a.20224

Source_Doc.PyOR_SpinQuantumNumber module

PyOR - Python On Resonance

Author:

Vineeth Francis Thalakottoor Jose Chacko

Email:

vineethfrancis.physics@gmail.com

Description:

This module provides spin quantum numbers for the electron and various nuclei, which are essential parameters for magnetic resonance simulations.

Spin quantum numbers are used to define the size of Hilbert spaces, construct spin operators, and simulate spin dynamics in NMR and EPR experiments.

spin(value)[source]

Returns the spin quantum number of a specified particle.

This function looks up the spin quantum number for common particles (nuclei and electrons) based on predefined values. These spin quantum numbers are commonly used in NMR, EPR, and quantum mechanical calculations.

Parameters:

valuestr
Symbol representing the particle. Common examples include:
  • “E” : Electron

  • “H1” : Proton (Hydrogen-1)

  • “H2” : Deuterium (Hydrogen-2)

  • “C13” : Carbon-13

  • “N14” : Nitrogen-14

  • “N15” : Nitrogen-15

  • “O17” : Oxygen-17

  • “F19” : Fluorine-19

Returns:

float

The spin quantum number of the given particle.

Raises:

AssertionError

If the particle symbol is not found in the predefined SPIN dictionary. In that case, the user is expected to define and add the spin value manually.

Example:

spin(“H1”) 0.5

spin(“O17”) 2.5

Notes:

The SPIN dictionary can be extended to include other nuclei or particles as needed.

References:

Title: NMR nomenclature. Nuclear spin properties and conventions for chemical shifts(IUPAC Recommendations 2001) Authors: Robin K. Harris , Edwin D. Becker , Sonia M. Cabral de Menezes , Robin Goodfellow and Pierre Granger Journal: Pure and Applied Chemistry DOI: https://doi.org/10.1351/pac200173111795

Module contents