libics.tools.math
models
- class libics.tools.math.models.ModelBase(*data, const_p0=None, **kwargs)
Bases:
abc.ABC,libics.core.io.base.FileBaseBase class for functional models.
Supports fitting.
For convenience, fitting can be directly applied by passing the data to the constructor.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- const_p0dict(str->float)
Not fitted parameters set to the given value.
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
Notes
For subclassing, implement the following attributes and methods:
P_ALL : Iterable[str], e.g. [“x0”, “y0”, “z0”]. Ordered (w.r.t model function) list of parameter names (will be used to access parameters). Class attribute.
P_DEFAULT : Iterable[float]. Default p0 parameters.
_func : Callable[var, *param]. Model function. Static method.
find_p0 : Callable[*data]. Automatized initial parameter finding routine. The argument *data should be interpretable by
_split_fit_data(). Optional method.
Examples
Assumes a concrete model class (i.e. subclass of this base class).
>>> class Model(ModelBase): ... P_ALL = ["x0"] ... P_DEFAULT = [1] ... @staticmethod ... def _func(var, x0): ... return var + x0 >>> model = Model() >>> model.pfit = ["x0"] >>> model.p0 = [1] >>> var_data, func_data = np.array([[0, 1, 2], [2.2, 3.0, 3.8]]) >>> model.find_popt(var_data, func_data) True >>> model.popt array([2.]) >>> model.pstd array([0.013333333]) >>> model.x0 2. >>> model.x0_std 0.013333333 >>> model["x0"] 2. >>> model["x0_std"] 0.013333333 >>> model(var_data) array([2., 3., 4.])
A direct fit is applied as:
>>> model = Model(var_data, func_data) >>> model.psuccess True
- Attributes
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0()Routine for initial fit parameter finding.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.models.ModelBase (WARNING)>
- P_ALL = NotImplemented
- P_DEFAULT = NotImplemented
- SER_KEYS = {'_p0', '_pcov', '_pfit', '_popt', '_var_rect', 'psuccess'}
- copy()
Returns a deep copy of the object.
- find_chi2(*data)
Gets the chi squared statistic.
This is the sum of the squared residuals.
- find_chi2_red(*data)
Gets the reduced chi squared statistic.
This is the sum of the squared residuals divided by the degrees of freedom (data points minus number of fit parameters).
- find_chi2_significance(*data)
Gets the chi squared confindence quantile for the fit.
Example: For a 2-sigma-quality fit, 0.95 is returned.
- find_p0()
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, bounds=None, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- get_model_data(shape=50)
Gets a (continuos) model data array using fitted parameters.
Generates a continuos meshgrid spanning the domain of the data points used for fitting. Calls the model function using the optimized fit parameters for this meshgrid.
- Parameters
- shapeIter[int] or int
Shape of meshgrid. If int, uses the same size in all dimensions.
- Returns
- data_contArrayData(float)
Continuos model data.
- Raises
- ValueError
If no prior fit has been performed.
- get_p0(as_dict=True)
- get_popt(as_dict=True, pall=True)
- get_pstd(as_dict=True)
- p0_is_set()
- property pall
dict(name->index) for all parameters
- property pcov
- property pcov_for_fit
- property pfit
dict(name->index) for fitted parameters
- property pstd
- property pstd_for_fit
- set_p0(**p0)
Sets initial parameters.
- Parameters
- **p0str->float
Initial parameter name->value.
- set_pfit(*opt, const=None, **const_p0)
Set which parameters to fit.
- Parameters
- *optstr
Names of fit parameters to be optimized. If any opt is given, const and const_p0 will be ignored.
- constIter[str]
Names of parameters not to be fitted.
- **const_p0str->float
Same as const, float arguments are used to fix the constant parameters.
- split_fit_data(*data, func_dim=- 1)
- test_hypothesis_chi2(*data, p_value=0.05)
Tests the whether the fit is valid.
- Parameters
- p_valuefloat
Critical confidence level (“alpha-value”), e.g. 0.05 for 2-sigma.
- libics.tools.math.models.ModelFromArray(ar, param_dims=None, scale_dims=None, offset_dims=None, interpolation='linear', extrapolation=True)
Uses an interpolated array to define a variable-scaled model.
Can be used to fit a scale and offset to the array variables.
- Parameters
- arArray[float]
Array interpreted as functional values.
- param_dimsint or Iter[int]
Array dimensions used as fitting parameters.
- scale_dims, offset_dimsint or Iter[int]
Array dimensions that should be scaled/offset.
- interpolationstr
Interpolation mode: “nearest”, “linear”.
- extrapolationbool or float
If True, extrapolates using the method given by interpolation. If False, raises an error upon extrapolation. If float, uses the given value as constant extrapolation value.
- Returns
- FitArrayDataclass
Generated model class (subclass of
ModelBase).
- Raises
- ValueError
If the given dimensions are invalid.
Examples
Consider a typical physical model f (t, x; a, b). This could, e.g., be a charge distribution f at time t and location x, given some parameters a and b (like conductivities). Since this might be a complicated model, it might be numerically defined and given as the array ar:
>>> ar.ndim 4
Let us assume that the goal is to fit this model to measurements f_i (t_i, x). f_i denotes the data set, which we assume is taken at all positions x and at a single point in time t_i:
>>> f.ndim 2
If we want to fit a, b, we have to pass the dimensions of a and b as param_dims:
>>> param_dims = [2, 3]
Let us further assume that we also want to fit the times. If we allow for a scalable time, we can set the corresponding dimensions:
>>> scale_dims : [0]
If we allow for a time offset, we can again set the dimensions:
>>> offset_dims = [0]
Now we can create the class representing the fit model from the numerical model:
>>> FitModel = ModelFromArray( ... ar, param_dims=param_dims, ... scale_dims=scale_dims, offset_dims=offset_dims ... )
This class is a subclass of
ModelBaseand can now be used to fit the measurement data:>>> fit = FitModel(f)
- class libics.tools.math.models.RvContinuous(momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)
Bases:
scipy.stats._distn_infrastructure.rv_continuous- Attributes
random_stateGet or set the generator object for generating random variates.
Methods
__call__(*args, **kwds)Freeze the distribution for the given arguments.
amplitude(*args, **kwds)Amplitude of the given RV, i.e., the maximum value of the PDF.
cdf(x, *args, **kwds)Cumulative distribution function of the given RV.
entropy(*args, **kwds)Differential entropy of the RV.
expect([func, args, loc, scale, lb, ub, ...])Calculate expected value of a function with respect to the distribution by numerical integration.
fit(data, *args, **kwds)Return estimates of shape (if applicable), location, and scale parameters from data.
fit_loc_scale(data, *args)Estimate loc and scale parameters from data using 1st and 2nd moments.
freeze(*args, **kwds)Freeze the distribution for the given arguments.
interval([confidence])Confidence interval with equal areas around the median.
ipdf(p, *args[, branch, tol])Mode of the given RV, i.e., the maximum location of the PDF.
isf(q, *args, **kwds)Inverse survival function (inverse of sf) at q of the given RV.
logcdf(x, *args, **kwds)Log of the cumulative distribution function at x of the given RV.
logpdf(x, *args, **kwds)Log of the probability density function at x of the given RV.
logsf(x, *args, **kwds)Log of the survival function of the given RV.
mean(*args, **kwds)Mean of the distribution.
median(*args, **kwds)Median of the distribution.
mode(*args, **kwds)Mode of the given RV, i.e., the maximum location of the PDF.
moment([order])non-central moment of distribution of specified order.
nnlf(theta, x)Negative loglikelihood function.
pdf(x, *args, **kwds)Probability density function at x of the given RV.
ppf(q, *args, **kwds)Percent point function (inverse of cdf) at q of the given RV.
rvs(*args, **kwds)Random variates of given type.
separation_loc([distr_l, distr_r, amp_l, ...])Gets the position of best separation between two distributions.
separation_loc_multi(distrs_l, distrs_r[, ...])Gets the position of best separation between two distributions.
sf(x, *args, **kwds)Survival function (1 - cdf) at x of the given RV.
stats(*args, **kwds)Some statistics of the given RV.
std(*args, **kwds)Standard deviation of the distribution.
support(*args, **kwargs)Support of the distribution.
var(*args, **kwds)Variance of the distribution.
kurtosis
skewness
variance
- LOGGER = <Logger libics.tools.math.models.RvContinuous (WARNING)>
- amplitude(*args, **kwds)
Amplitude of the given RV, i.e., the maximum value of the PDF.
- Parameters
- arg1, arg2, arg3,…Array
The shape parameter(s) for the distribution (see docstring of the instance object for more information)
- Returns
- amplitudefloat
Amplitude of probability density function.
- freeze(*args, **kwds)
Freeze the distribution for the given arguments.
- Parameters
- arg1, arg2, arg3,…array_like
The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include
locandscale.
- Returns
- rv_frozenrv_frozen instance
The frozen distribution.
- ipdf(p, *args, branch='left', tol=None, **kwds)
Mode of the given RV, i.e., the maximum location of the PDF.
- Parameters
- pArray
Probability density.
- arg1, arg2, arg3,…Array
The shape parameter(s) for the distribution (see docstring of the instance object for more information)
- locArray, optional
location parameter (default=0)
- scaleArray, optional
scale parameter (default=1)
- branchstr
Which branch of the PDF to select. Options for unimodal distributions: “left”, “right”.
- Returns
- ipdfArray
Inverse of the probability density function.
- kurtosis(*args, **kwargs)
- mode(*args, **kwds)
Mode of the given RV, i.e., the maximum location of the PDF.
- Parameters
- arg1, arg2, arg3,…Array
The shape parameter(s) for the distribution (see docstring of the instance object for more information)
- locArray, optional
location parameter (default=0)
- scaleArray, optional
scale parameter (default=1)
- Returns
- modefloat
Mode of probability density function.
- separation_loc(distr_l=None, distr_r=None, amp_l=1, amp_r=1, args_l=(), args_r=(), kwargs_l={}, kwargs_r={})
Gets the position of best separation between two distributions.
- Parameters
- distr_l, distr_rRvContinuous or RvContinuousFrozen or None
(Left, right) distribution. If None, uses the current object. If RvContinuousFrozen, overwrites arg and kwarg.
- amp_l, amp_rfloat
(Relative) amplitudes of the distributions. Used if one distribution contains “more” probability than another.
- args_l, args_rtuple(float)
Distribution arguments (left, right).
- kwargs_l, kwargs_rdict(str->Any)
Distribution keyword arguments (left, right).
- Returns
- xsfloat
Separation position.
- ql, qrfloat
Quantile of the (left, right) distribution on the “wrong” side.
- static separation_loc_multi(distrs_l, distrs_r, amp_l=1, amp_r=1)
Gets the position of best separation between two distributions.
- Parameters
- distr_l, distr_rRvContinuous or RvContinuousFrozen or None
(Left, right) distribution. If None, uses the current object. If RvContinuousFrozen, overwrites arg and kwarg.
- amp_l, amp_rfloat
(Relative) amplitudes of the distributions. Used if one distribution contains “more” probability than another.
- args_l, args_rtuple(float)
Distribution arguments (left, right).
- kwargs_l, kwargs_rdict(str->Any)
Distribution keyword arguments (left, right).
- Returns
- xsfloat
Separation position.
- ql, qrfloat
Quantile of the (left, right) distribution on the “wrong” side.
- skewness(*args, **kwargs)
- variance(*args, **kwargs)
- class libics.tools.math.models.RvContinuousFrozen(dist, *args, **kwds)
Bases:
scipy.stats._distn_infrastructure.rv_continuous_frozen- Attributes
- random_state
Methods
cdf
entropy
expect
interval
isf
logcdf
logpdf
logsf
mean
median
moment
pdf
ppf
rvs
sf
stats
std
support
var
- class libics.tools.math.models.TensorModelBase(*data, **kwargs)
Bases:
abc.ABC- Attributes
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
find_p0()Routine for initial fit parameter finding.
find_popt(*data, **kwargs)Fits the model function to the given data.
get_popt
p0_is_set
popt_is_set
- LOGGER = <Logger libics.math.models.TensorModelBase (WARNING)>
- P_DEFAULT = NotImplemented
- P_SCAL = NotImplemented
- P_TENS = 'ptens'
- P_VECT = NotImplemented
- find_p0()
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- get_popt(as_dict=True)
- property p0
- p0_is_set()
- property pall_scal
dict(name->index) for scalar parameters
- property pall_vect
dict(name->index) for vector parameters
- property pcov
- popt_is_set()
- property pstd
flat
- class libics.tools.math.flat.FitCosine1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
cosine_1d().- Parameters
- afloat
amplitude
- ffloat
frequency without 2π
- phifloat
additive phase
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data[, MAX_POINTS])Routine for initial fit parameter finding.
find_popt(*data, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitLinear1d (WARNING)>
- P_ALL = ['a', 'f', 'phi', 'c']
- P_DEFAULT = [1, 1, 0, 0]
- find_p0(*data, MAX_POINTS=1024)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.flat.FitCosine2d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
cosine_2d().- Parameters
- afloat
amplitude
- fx, fyfloat
frequency without 2π
- phifloat
additive phase
- cfloat
offset
- Attributes
- f
Vectorial frequency (fx, fy)
- angle
Frequency angle arctan(fy/fx)
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data[, MAX_LINES, MAX_POINTS])Routine for initial fit parameter finding.
find_popt(*data, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitCosine2d (WARNING)>
- P_ALL = ['a', 'fx', 'fy', 'phi', 'c']
- P_DEFAULT = [1, 1, 0, 0, 0]
- property angle
- property angle_std
- property f
- find_p0(*data, MAX_LINES=16, MAX_POINTS=1024)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.flat.FitErrorFunction(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
error_function().- Parameters
- afloat
amplitude
- x0float
center
- wfloat
width
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitErrorFunction (WARNING)>
- P_ALL = ['a', 'x0', 'w', 'c']
- P_DEFAULT = [1, 0, 1, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.flat.FitLinear1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
linear_1d().- Parameters
- afloat
amplitude
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitLinear1d (WARNING)>
- P_ALL = ['a', 'c']
- P_DEFAULT = [1, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.flat.FitLinearStepFunction(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
linear_step_function().- Parameters
- afloat
amplitude
- x0float
center
- wfloat
width
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitLinearStepFunction (WARNING)>
- P_ALL = ['a', 'x0', 'w', 'c']
- P_DEFAULT = [1, 0, 1, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*data, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.flat.FitPowerLaw1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
power_law_1d().- Parameters
- afloat
amplitude
- pfloat
power
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitPowerLaw1d (WARNING)>
- P_ALL = ['a', 'p']
- P_DEFAULT = [1, 1]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- class libics.tools.math.flat.FitPowerLaw1dCenter(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
power_law_1d()with center as fit variable.- Parameters
- afloat
amplitude
- pfloat
power
- x0float
center
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.tools.math.flat.FitPowerLaw1dCenter (WARNING)>
- P_ALL = ['a', 'p', 'x0', 'c']
- P_DEFAULT = [1, 1, 0, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- libics.tools.math.flat.cosine_1d(var, amplitude, frequency, phase, offset=0.0)
- libics.tools.math.flat.cosine_2d(var, amplitude, frequency_x, frequency_y, phase, offset=0.0)
- libics.tools.math.flat.error_function(x, amplitude, center, width, offset=0)
Error function in one dimension.
\[a \mathrm{erf}((x - x_0) / w) + c\]
- libics.tools.math.flat.linear_1d(x, a, c=0.0)
Linear in one dimension.
\[a x + c\]
- libics.tools.math.flat.linear_step_function(x, amplitude, center, width, offset=0)
Linearly interpolated step function in one dimension.
\[c - a (for x < x_0 - w), \frac{a}{w} (x - x_0) + c (for x_0 - w < x < x_0 + w), c + a (for x > x_0 + w)\]
- libics.tools.math.flat.power_law_1d(x, amplitude, power, center=0, offset=0)
Power law in one dimension.
\[a (x - x_0)^p + c\]
peaked
- class libics.tools.math.peaked.FitAiryDisk2d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
airy_disk_2d().- Parameters
- afloat
amplitude
- x0, y0float
center
- wfloat
width
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Algorithm: linear min/max approximation.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitAiryDisk2d (WARNING)>
- P_ALL = ['a', 'x0', 'y0', 'w', 'c']
- P_DEFAULT = [1, 0, 0, 1, 0]
- find_p0(*data)
Algorithm: linear min/max approximation.
- class libics.tools.math.peaked.FitBmGaussianParabolic1dInt2d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitGaussian1dFit class for
bm_gaussian_parabolic_1d_int2d().- Parameters
- ag, apfloat
amplitudes of Gaussian and parabola
- x0float
center
- wgx, wpxfloat
width of Gaussian and parabola
- cfloat
offset
- Attributes
- distribution_amplitude
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
DISTRIBUTION__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Algorithm: find_p0 of Gaussian -> split data at width -> fit tails with Gaussian, center with parabola.
find_popt(*args[, maxfev])Fits the model function to the given data.
Gets a fit object only modelling the Gaussian part.
Gets a fit object only modelling the parabolic part.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_distribution
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitBmGaussianParabolic1d (WARNING)>
- P_ALL = ['ag', 'ap', 'x0', 'wgx', 'wpx', 'c']
- P_DEFAULT = [0.5, 0.5, 0, 1, 0.5, 0]
- find_p0(*data)
Algorithm: find_p0 of Gaussian -> split data at width -> fit tails with Gaussian, center with parabola.
Notes
Currently only works for positive data.
- get_fit_gaussian_1d()
Gets a fit object only modelling the Gaussian part.
- get_fit_parabolic_1d_int2d()
Gets a fit object only modelling the parabolic part.
- class libics.tools.math.peaked.FitBmGaussianParabolic2dInt1dTilt(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitGaussian2dTiltFit class for
bm_gaussian_parabolic_2d_int1d().- Parameters
- ag, apfloat
amplitudes of Gaussian and parabola
- x0, y0float
center
- wgu, wgv, wpu, wpvfloat
widths of Gaussian and parabola
- tiltfloat
tilt in [-45°, 45°]
- cfloat
offset
- Attributes
- ellipticity
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)- Parameters
find_popt(*args, **kwargs)Fits the model function to the given data.
Gets a fit object only modelling the Gaussian part.
Gets a fit object only modelling the parabolic part.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitBmGaussianParabolic2dInt1dTilt (WARNING)>
- P_ALL = ['ag', 'ap', 'x0', 'y0', 'wgu', 'wgv', 'wpu', 'wpv', 'tilt', 'c']
- P_DEFAULT = [0.5, 0.5, 0, 0, 1, 1, 0.5, 0.5, 0, 0]
- find_p0(*data)
- Parameters
- algorithmstr
“linear”, “fit1d”.
- find_popt(*args, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- get_fit_gaussian_2d_tilt()
Gets a fit object only modelling the Gaussian part.
- get_fit_parabolic_2d_int1d_tilt()
Gets a fit object only modelling the parabolic part.
- class libics.tools.math.peaked.FitExponential1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
exponential_1d().- Parameters
- afloat
amplitude
- gfloat
rate
- cfloat
offset
- Attributes
- x0float
variable offset, assuming unity amplitude
- xifloat
decay length, inverse rate
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitExponential1d (WARNING)>
- P_ALL = ['a', 'g', 'c']
- P_DEFAULT = [1, 1, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- property x0
- property xi
- class libics.tools.math.peaked.FitExponential1dStretched(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
exponential_1d_stretched().- Parameters
- afloat
amplitude
- gfloat
rate
- bfloat
stretched exponent
- cfloat
offset
- Attributes
- xifloat
decay length, inverse rate
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitExponential1dStretched (WARNING)>
- P_ALL = ['a', 'g', 'b', 'c']
- P_DEFAULT = [1, 1, 1, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- property xi
- class libics.tools.math.peaked.FitExponentialDecay1d(*args, **kwargs)
Bases:
object
- class libics.tools.math.peaked.FitGaussian1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
gaussian_1d().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- cfloat
offset
- Attributes
- distribution_amplitude
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*args[, maxfev])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_distribution
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- DISTRIBUTION = <libics.tools.math.peaked._Normal1dDistribution_gen object>
- LOGGER = <Logger libics.math.peaked.FitGaussian1d (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'c']
- P_DEFAULT = [1, 0, 1, 0]
- property distribution_amplitude
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*args, maxfev=100000, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- get_distribution()
- class libics.tools.math.peaked.FitGaussian2dTilt(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
gaussian_2d_tilt().- Parameters
- afloat
amplitude
- x0, y0float
center
- wu, wvfloat
width
- tiltfloat
tilt in [-45°, 45°]
- cfloat
offset
- Attributes
- ellipticity
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data[, algorithm])- Parameters
find_popt(*args, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitGaussian2dTilt (WARNING)>
- P_ALL = ['a', 'x0', 'y0', 'wu', 'wv', 'tilt', 'c']
- P_DEFAULT = [1, 0, 0, 1, 1, 0, 0]
- property ellipticity
- find_p0(*data, algorithm='fit1d')
- Parameters
- algorithmstr
“linear”, “fit1d”.
- find_popt(*args, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.peaked.FitLorentzian1dAbs(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
lorentzian_1d_abs().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Algorithm: dummy max.
find_popt(*args, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitLorentzian1dAbs (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'c']
- P_DEFAULT = [1, 0, 1, 0]
- find_p0(*data)
Algorithm: dummy max.
- find_popt(*args, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- class libics.tools.math.peaked.FitLorentzianEit1dImag(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
lorentzian_eit_1d_imag().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- x1float
shift
- wx1float
split
- cfloat
offset
- Attributes
- gefloat
excited state decay rate
- fcfloat
control field Rabi frequency
- dcfloat
control field detuning
- lmaxfloat
position of left maximum
- rmaxfloat
position of right maximum
- cminfloat
position of central minimum
- lwidth, rwidthfloat
width of left/right maximum
- cwidthfloat
width of central minimum
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*args, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
get_phys()Gets parameters parametrized as physical quantities.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitLorentzianEit1dImag (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'x1', 'wx1', 'c']
- P_DEFAULT = [1, 0, 1, 0, 1, 0]
- property cmin
- property cwidth
- property dc
- property dp
- property fc
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*args, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- property ge
- get_phys()
Gets parameters parametrized as physical quantities.
- Returns
- physdict(str->float)
Parameters: amplitude “a”, probe resonance frequency “dp”, control resonance frequency “dc”, control Rabi frequency: “fc”, intermediate state decay rate “ge”, offset “c”.
- property lmax
- property lwidth
- property rmax
- property rwidth
- class libics.tools.math.peaked.FitLorentzianRydEit1dImag(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitLorentzianEit1dImagFit class for
lorentzian_ryd_eit_1d_imag().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- x1float
shift
- wx1float
split
- rfloat
ratio
- cfloat
offset
- Attributes
- gefloat
excited state decay rate
- fcfloat
control field Rabi frequency
- dcfloat
control field detuning
- lmax, rmaxfloat
position of left/right maximum
- cminfloat
position of central minimum
- lwidth, rwidthfloat
width of left/right maximum
- cwidthfloat
width of central minimum
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data[, const_p0])- Parameters
find_popt(*args, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
get_phys()Gets parameters parametrized as physical quantities.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitLorentzianRydEit1dImag (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'x1', 'wx1', 'r', 'c']
- P_DEFAULT = [1, 0, 1, 0, 1, 0.5, 0]
- find_p0(*data, const_p0=None)
- Parameters
- const_p0dict(str->float)
Constant parameters which should not be fitted when estimating p0 with r == 0 fit.
- class libics.tools.math.peaked.FitParabolic1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.models.ModelBaseFit class for
parabolic_1d().- Parameters
- afloat
amplitude
- x0float
center
- cfloat
offset
- Attributes
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*data[, bounds])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitParabolic1d (WARNING)>
- P_ALL = ['a', 'x0', 'c']
- P_DEFAULT = [1, 0, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- class libics.tools.math.peaked.FitParabolic1dInt2d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitGaussian1dFit class for
parabolic_1d_int2d().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- cfloat
offset
- Attributes
- distribution_amplitude
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
DISTRIBUTION__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*args[, maxfev])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_distribution
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitParabolic1dInt2d (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'c']
- P_DEFAULT = [1, 0, 1, 0]
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- class libics.tools.math.peaked.FitParabolic2dInt1dTilt(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitGaussian2dTiltFit class for
parabolic_1d_int2d().- Parameters
- afloat
amplitude
- x0, y0float
center
- wu, wvfloat
width
- tiltfloat
tilt in [-45°, 45°]
- cfloat
offset
- Attributes
- ellipticity
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data[, algorithm])- Parameters
find_popt(*args, **kwargs)Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- LOGGER = <Logger libics.math.peaked.FitParabolic2dInt1dTilt (WARNING)>
- P_ALL = ['a', 'x0', 'y0', 'wu', 'wv', 'tilt', 'c']
- P_DEFAULT = [1, 0, 0, 1, 1, 0, 0]
- class libics.tools.math.peaked.FitSkewGaussian1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitGaussian1dFit class for
skew_gaussian_1d().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- alphafloat
parameter controlling skewness
- cfloat
offset
- Attributes
- distribution_amplitude
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*args, **kwargs)Fits the model function to the given data.
Gets the distribution corresponding to this model.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- DISTRIBUTION = <libics.tools.math.peaked._SkewNormal1dDistribution_gen object>
- LOGGER = <Logger libics.math.peaked.FitSkewGaussian1d (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'alpha', 'c']
- P_DEFAULT = [1, 0, 1, 0, 0]
- property distribution_amplitude
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- find_popt(*args, **kwargs)
Fits the model function to the given data.
- Parameters
- *dataAny
Data interpretable by
_split_fit_data().- boundsdict(str->(float, float))
Bounds for fitted values for each parameter: dict(parameter_name->(lower_bound, upper_bound)).
- **kwargs
Keyword arguments passed to
scipy.optimize.curve_fit().
- Returns
- psuccessbool
Whether fit succeeded.
- get_distribution()
Gets the distribution corresponding to this model.
- Returns
- distrSkewNormal1dDistribution
Distribution object corresponding to best fit parameters.
- class libics.tools.math.peaked.FitSymExponential1d(*data, const_p0=None, **kwargs)
Bases:
libics.tools.math.peaked.FitGaussian1dFit class for
sym_exponential_1d().- Parameters
- afloat
amplitude
- x0float
center
- wxfloat
width
- cfloat
offset
- Attributes
- distribution_amplitude
p0All
p0p0_for_fitFitted
p0palldict(name->index) for all parameters
- pcov
- pcov_for_fit
pfitdict(name->index) for fitted parameters
poptAll
popt(non-fitted ones usep0)popt_for_fitFitted
popt- pstd
- pstd_for_fit
Methods
__call__(var, *args, **kwargs)Calls the model function with current parameters.
attributes()Default saved attributes getter.
copy()Returns a deep copy of the object.
find_chi2(*data)Gets the chi squared statistic.
find_chi2_red(*data)Gets the reduced chi squared statistic.
find_chi2_significance(*data)Gets the chi squared confindence quantile for the fit.
find_p0(*data)Routine for initial fit parameter finding.
find_popt(*args[, maxfev])Fits the model function to the given data.
get_model_data([shape])Gets a (continuos) model data array using fitted parameters.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.set_p0(**p0)Sets initial parameters.
set_pfit(*opt[, const])Set which parameters to fit.
test_hypothesis_chi2(*data[, p_value])Tests the whether the fit is valid.
get_distribution
get_p0
get_popt
get_pstd
p0_is_set
split_fit_data
- DISTRIBUTION = <libics.tools.math.peaked._SymExpon1dDistribution_gen object>
- LOGGER = <Logger libics.math.peaked.FitSymExponential1d (WARNING)>
- P_ALL = ['a', 'x0', 'wx', 'c']
- P_DEFAULT = [1, 0, 1, 0]
- property distribution_amplitude
- find_p0(*data)
Routine for initial fit parameter finding.
Should return whether this succeeded.
- get_distribution()
- class libics.tools.math.peaked.RndDscBallistic1d(*args, sites=None, time=None, hopping=None, **kwargs)
Bases:
scipy.stats._distn_infrastructure.rv_discrete1D ballistic transport site occupation random variable.
- Parameters
- sitetuple(int)
Minimum and maximum sites (site_min, site_max).
- timefloat
Evolution time in seconds (s).
- hoppingfloat
Hopping frequency in radians (rad).
- Attributes
random_stateGet or set the generator object for generating random variates.
Methods
__call__(*args, **kwds)Freeze the distribution for the given arguments.
cdf(k, *args, **kwds)Cumulative distribution function of the given RV.
entropy(*args, **kwds)Differential entropy of the RV.
expect([func, args, loc, lb, ub, ...])Calculate expected value of a function with respect to the distribution for discrete distribution by numerical summation.
freeze(*args, **kwds)Freeze the distribution for the given arguments.
interval([confidence])Confidence interval with equal areas around the median.
isf(q, *args, **kwds)Inverse survival function (inverse of sf) at q of the given RV.
logcdf(k, *args, **kwds)Log of the cumulative distribution function at k of the given RV.
logpmf(k, *args, **kwds)Log of the probability mass function at k of the given RV.
logsf(k, *args, **kwds)Log of the survival function of the given RV.
mean(*args, **kwds)Mean of the distribution.
median(*args, **kwds)Median of the distribution.
moment([order])non-central moment of distribution of specified order.
nnlf(theta, x)Negative loglikelihood function.
pmf(k, *args, **kwds)Probability mass function at k of the given RV.
ppf(q, *args, **kwds)Percent point function (inverse of cdf) at q of the given RV.
rvs(*args, **kwargs)Random variates of given type.
sf(k, *args, **kwds)Survival function (1 - cdf) at k of the given RV.
stats(*args, **kwds)Some statistics of the given RV.
std(*args, **kwds)Standard deviation of the distribution.
support(*args, **kwargs)Support of the distribution.
var(*args, **kwds)Variance of the distribution.
- class libics.tools.math.peaked.RndDscBlochOsc1d(*args, sites=None, time=None, hopping=None, gradient=None, **kwargs)
Bases:
scipy.stats._distn_infrastructure.rv_discrete1D Bloch oscillation site occupation random variable.
- Parameters
- sitetuple(int)
Minimum and maximum sites (site_min, site_max).
- timefloat
Evolution time in seconds (s).
- hoppingfloat
Hopping frequency in radians (rad).
- gradientfloat
Frequency difference between neighbouring sites in radians (rad).
- Attributes
random_stateGet or set the generator object for generating random variates.
Methods
__call__(*args, **kwds)Freeze the distribution for the given arguments.
cdf(k, *args, **kwds)Cumulative distribution function of the given RV.
entropy(*args, **kwds)Differential entropy of the RV.
expect([func, args, loc, lb, ub, ...])Calculate expected value of a function with respect to the distribution for discrete distribution by numerical summation.
freeze(*args, **kwds)Freeze the distribution for the given arguments.
interval([confidence])Confidence interval with equal areas around the median.
isf(q, *args, **kwds)Inverse survival function (inverse of sf) at q of the given RV.
logcdf(k, *args, **kwds)Log of the cumulative distribution function at k of the given RV.
logpmf(k, *args, **kwds)Log of the probability mass function at k of the given RV.
logsf(k, *args, **kwds)Log of the survival function of the given RV.
mean(*args, **kwds)Mean of the distribution.
median(*args, **kwds)Median of the distribution.
moment([order])non-central moment of distribution of specified order.
nnlf(theta, x)Negative loglikelihood function.
pmf(k, *args, **kwds)Probability mass function at k of the given RV.
ppf(q, *args, **kwds)Percent point function (inverse of cdf) at q of the given RV.
rvs(*args, **kwargs)Random variates of given type.
sf(k, *args, **kwds)Survival function (1 - cdf) at k of the given RV.
stats(*args, **kwds)Some statistics of the given RV.
std(*args, **kwds)Standard deviation of the distribution.
support(*args, **kwargs)Support of the distribution.
var(*args, **kwds)Variance of the distribution.
- class libics.tools.math.peaked.RndDscDiffusive1d(*args, sites=None, time=None, diffusion=None, **kwargs)
Bases:
scipy.stats._distn_infrastructure.rv_discrete1D random variable for diffusive transport on discrete sites.
- Parameters
- sitetuple(int)
Minimum and maximum sites (site_min, site_max).
- timefloat
Evolution time in seconds (s).
- diffusionfloat
Diffusion constant in sites² per second (1/s).
- Attributes
random_stateGet or set the generator object for generating random variates.
Methods
__call__(*args, **kwds)Freeze the distribution for the given arguments.
cdf(k, *args, **kwds)Cumulative distribution function of the given RV.
entropy(*args, **kwds)Differential entropy of the RV.
expect([func, args, loc, lb, ub, ...])Calculate expected value of a function with respect to the distribution for discrete distribution by numerical summation.
freeze(*args, **kwds)Freeze the distribution for the given arguments.
interval([confidence])Confidence interval with equal areas around the median.
isf(q, *args, **kwds)Inverse survival function (inverse of sf) at q of the given RV.
logcdf(k, *args, **kwds)Log of the cumulative distribution function at k of the given RV.
logpmf(k, *args, **kwds)Log of the probability mass function at k of the given RV.
logsf(k, *args, **kwds)Log of the survival function of the given RV.
mean(*args, **kwds)Mean of the distribution.
median(*args, **kwds)Median of the distribution.
moment([order])non-central moment of distribution of specified order.
nnlf(theta, x)Negative loglikelihood function.
pmf(k, *args, **kwds)Probability mass function at k of the given RV.
ppf(q, *args, **kwds)Percent point function (inverse of cdf) at q of the given RV.
rvs(*args, **kwargs)Random variates of given type.
sf(k, *args, **kwds)Survival function (1 - cdf) at k of the given RV.
stats(*args, **kwds)Some statistics of the given RV.
std(*args, **kwds)Standard deviation of the distribution.
support(*args, **kwargs)Support of the distribution.
var(*args, **kwds)Variance of the distribution.
- libics.tools.math.peaked.airy_disk_2d(var, amplitude, center_x, center_y, width, offset=0.0)
- \[A \left( \frac{2 J_1 \left( \sqrt{(x-x_0)^2 + (y-y_0)^2} / w \right)} {\sqrt{(x-x_0)^2 + (y-y_0)^2} / w} \right)^2 + C\]
- Parameters
- varfloat
\((x, y)\)
- amplitudefloat
\(A\)
- center_x, center_yfloat
\((x_0, y_0)\)
- widthfloat
\(w\)
- offsetfloat
\(C\)
Notes
Handles limiting value at \((x, y) -> (0, 0)\).
- libics.tools.math.peaked.bm_gaussian_parabolic_1d_int2d(x, ag, ap, x0, wgx, wpx, c=0)
- libics.tools.math.peaked.bm_gaussian_parabolic_2d_int1d(var, ag, ap, x0, y0, wgu, wgv, wpu, wpv, tilt=0, c=0)
- libics.tools.math.peaked.dsc_ballistic_1d(var, hopping)
- \[J_n^2 \left( 2 J t \right)\]
The hopping energy \(J\) should be given in \(2 \pi\) frequency units, i.e. in units of \(\hbar\).
- Parameters
- varfloat
\((n, t)\)
- hoppingfloat
\(J\)
- Returns
- res
Probability distribution of 1D ballistic transport for the given site var[0] at the given time var[1].
- libics.tools.math.peaked.dsc_bloch_osc_1d(var, hopping, gradient)
- \[J_n^2 \left( \frac{4 J}{\Delta} \cdot \left| \sin \frac{\Delta t}{2} \right| \right)\]
\(\Delta = F a\) specifies the energy difference between neighbouring sites with distance \(a\) at a potential gradient \(F\). Energies \(J, \Delta\) should be given in \(2 \pi\) frequency units, i.e. in units of \(\hbar\).
- Parameters
- varfloat
\((n, t)\)
- hoppingfloat
\(J\)
- gradientfloat
\(\Delta\)
- Returns
- res
Probability distribution of 1D Bloch oscillations for the given site var[0] at the given time var[1].
- libics.tools.math.peaked.dsc_bloch_osc_2d(var, hopping_x, hopping_y, gradient_x, gradient_y)
See
bloch_osc_1d().- Parameters
- varfloat
\((n_x, n_y, t)\)
- libics.tools.math.peaked.dsc_bloch_osc_3d(var, hopping_x, hopping_y, hopping_z, gradient_x, gradient_y, gradient_z)
See
bloch_osc_1d().- Parameters
- varfloat
\((n_x, n_y, n_z, t)\)
- libics.tools.math.peaked.dsc_diffusive_1d(var, diffusion)
- \[\frac{1}{\sqrt{4 \pi D t}} \exp \left( -\frac{n^2}{4 D t} \right)\]
The diffusion constant \(D\) should be given in units of the lattice constant \(a\), i.e. \(D_\text{SI} = D / a^2\).
- Parameters
- varfloat
\((n, t)\)
- diffusionfloat
\(D\)
- Returns
- res
Probability distribution of 1D ballistic transport for the given site var[0] at the given time var[1].
- libics.tools.math.peaked.exponential_1d(x, amplitude, rate, offset=0.0)
Exponential function in one dimension.
\[A e^{\gamma x} + C\]- Parameters
- xfloat
Variable \(x\).
- amplitudefloat
Amplitude \(A\).
- ratefloat
Rate of exponential \(\gamma\).
- offsetfloat, optional (default: 0)
Offset \(C\)
- libics.tools.math.peaked.exponential_1d_stretched(x, amplitude, rate, beta, offset=0.0)
Stretched exponential function in one dimension.
\[A e^{-\text{sgn}(\gamma) (|\gamma| x)^\beta} + C\]- Parameters
- xfloat
Variable \(x\).
- amplitudefloat
Amplitude \(A\).
- ratefloat
Rate of exponential \(\gamma\).
- betafloat
Stretched exponent \(\beta\).
- offsetfloat, optional (default: 0)
Offset \(C\)
- libics.tools.math.peaked.exponential_decay_1d(*args, **kwargs)
- libics.tools.math.peaked.exponential_decay_nd(x, amplitude, center, length, offset=0.0)
Exponential decay in \(n\) dimensions.
\[A e^{-\sum_{i=1}^n \frac{|x_i - c_i|}{\xi_i}} + C\]- Parameters
- xnumpy.array(n, float)
Variables \(x_i\).
- amplitudefloat
Amplitude \(A\).
- centernumpy.array(n, float)
Centers \(c_i\).
- lengthnumpy.array(n, float)
Characteristic lengths \(\xi_i\).
- offsetfloat, optional (default: 0)
Offset \(C\)
- libics.tools.math.peaked.gamma_distribution_1d(x, amplitude, mean, number, offset=0.0)
Gamma distribution in one dimension.
\[A \frac{(N / \mu)^N}{\Gamma (N)} x^{N - 1} e^{-\frac{N}{\mu} x} + C\]- Parameters
- xfloat
Variable \(x\).
- amplitudefloat
Amplitude \(A\).
- meanfloat
Mean \(\mu\).
- numberfloat
Number \(N\).
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.gaussian_1d(x, amplitude, center, width, offset=0.0)
Gaussian in one dimension.
\[A e^{-\frac{(x - c)^2}{2 \sigma^2}} + C\]- Parameters
- xfloat
Variable \(x\).
- amplitudefloat
Amplitude \(A\).
- centerfloat
Center \(c\).
- widthfloat
Width \(\sigma\).
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.gaussian_2d_tilt(var, amplitude, center_x, center_y, width_u, width_v, tilt, offset=0.0)
Tilted (rotated) Gaussian in two dimensions.
\[A e^{-\frac{((x - x_0) \cos \theta + (y - y_0) \sin \theta))^2} {2 \sigma_u^2} -\frac{((y - y_0) \cos \theta - (x - x_0) \sin \theta))^2} {2 \sigma_v^2}} + C\]- Parameters
- varnumpy.array(2, float)
Variables \(x, y\).
- amplitudefloat
Amplitude \(A\).
- center_x, center_yfloat
Centers \(x_0, y_0\).
- width_u, width_vfloat
Widths \(\sigma_u, \sigma_v\).
- tiltfloat(0, numpy.pi)
Tilt angle \(\theta\).
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.gaussian_nd(x, amplitude, center, width, offset=0.0)
Gaussian in \(n\) dimensions.
\[A e^{-\sum_{i=1}^n \left( \frac{x_i - c_i}{2 \sigma_i} \right)^2} + C\]- Parameters
- xnumpy.array(n, float)
Variables \(x_i\).
- amplitudefloat
Amplitude \(A\).
- centernumpy.array(n, float)
Centers \(c_i\).
- widthnumpy.array(n, float)
Widths \(\sigma_i\).
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.gaussian_nd_centered(x, amplitude, width, offset=0.0)
Centered Gaussian in \(n\) dimensions.
\[A e^{-\sum_{i=1}^n \left( \frac{x_i}{2 \sigma_i} \right)^2} + C\]- Parameters
- xnumpy.array(n, float)
Variables \(x_i\).
- amplitudefloat
Amplitude \(A\).
- widthnumpy.array(n, float)
Widths \(\sigma_i\).
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.gaussian_nd_symmetric(x, amplitude, center, width, offset=0.0)
Symmetric Gaussian in \(n\) dimensions.
\[A e^{-\sum_{i=1}^n \left( \frac{x_i - c_i}{2 \sigma} \right)^2} + C\]- Parameters
- xnumpy.array(n, float)
Variables \(x_i\).
- amplitudefloat
Amplitude \(A\).
- centernumpy.array(n, float)
Centers \(c_i\).
- widthnumpy.array(n, float)
Width \(\sigma\).
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.lorentzian_1d_abs(var, amplitude, center, width, offset=0.0)
- libics.tools.math.peaked.lorentzian_1d_complex(var, amplitude, center, width, offset=0.0)
- libics.tools.math.peaked.lorentzian_eit_1d_imag(var, amplitude, center, width, shift, split, offset=0.0)
- libics.tools.math.peaked.lorentzian_ryd_eit_1d_imag(var, amplitude, center, width, shift, split, ratio, offset=0.0)
-
- Parameters
- ratiofloat
Rydberg fraction (ratio of non-EIT).
- libics.tools.math.peaked.parabolic_1d(x, a, x0, c=0)
Parabola in one dimension.
\[A (x - x_0) + C\]- Parameters
- xfloat
Variable \(x\).
- afloat
Amplitude \(A\).
- x0float
Center \(x_0\).
- cfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.parabolic_1d_finsup(x, a, x0, wx, c=0)
Parabola on finite support in one dimension.
\[\left(a - \frac{\sign{a}}{2} \left(\frac{x - x_0}{w_x}\right)^2\right) \Theta (w_x \sqrt{2 A} - |x - x_0|) + c\]- Parameters
- xfloat
Variable \(x\).
- afloat
Amplitude \(A\).
- x0float
Center \(x_0\).
- wxfloat
Width of parabola \(w_x\). Normalized to be consistent with Gaussian width in series expansion.
- cfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.parabolic_1d_int2d(var, a, x0, wx, c=0)
3D parabola on finite support integrated over two dimensions.
- libics.tools.math.peaked.parabolic_2d_int1d_tilt(var, a, x0, y0, wu, wv, tilt=0, c=0)
3D parabola on finite support integrated over one dimension.
- libics.tools.math.peaked.skew_gaussian_1d(x, amplitude, center, width, alpha, offset=0.0)
Skewed Gaussian in one dimension.
See: https://en.wikipedia.org/wiki/Skew_normal_distribution.
- Parameters
- xfloat
Variable.
- amplitudefloat
Amplitude of PDF.
- centerfloat
Mode of PDF.
- widthfloat
Standard deviation of PDF.
- alphafloat
Parameter controlling skewness.
- offsetfloat, optional (default: 0)
Offset \(C\).
- libics.tools.math.peaked.sym_exponential_1d(x, amplitude, center, width, offset=0.0)
Symmetric exponential function in one dimension.
\[A e^{-|x - x_0| / w \sqrt{2}} + C\]- Parameters
- xfloat
Variable \(x\).
- amplitudefloat
Amplitude \(A\).
- centerfloat
Center \(x_0\).
- widthfloat
Width of exponential \(w\).
- offsetfloat, optional (default: 0)
Offset \(C\)
intervalfunc
- class libics.tools.math.intervalfunc.IntervalSeries
Bases:
objectContainer class for a series of interval functions.
- Attributes
- size
Methods
append(*data[, func, t0, dt, y0, y1, args, ...])Appends interval function data.
get_blocks([iv_gap])Calculates the block intervals.
get_data([mode, iv_gap, num])Gets the evaluated data traces.
get_times([iv_gap])Calculates the time intervals from specified start times and durations.
- KEYS = {'args', 'dt', 'func', 'kwargs', 't0', 'y0', 'y1'}
- append(*data, func=None, t0=None, dt=None, y0=None, y1=None, args=None, kwargs=None)
Appends interval function data.
- get_blocks(iv_gap=0)
Calculates the block intervals.
- get_data(mode='val', iv_gap=0, num=64)
Gets the evaluated data traces.
- Parameters
- modestr
“val”: Independent variable is set by value. “block”: Independent variable is set by block.
- iv_gapfloat
Default gap between subsequent intervals. val mode: Used when start times are not explicitly specified.
- numint
Points per interval trace.
- Returns
- ivslist(ArrayData(1, float))
Traces of intervals with length self.size.
- gapslist(ArrayData(1, float))
Traces of gaps between intervals with length self.size - 1.
- get_times(iv_gap=0)
Calculates the time intervals from specified start times and durations.
- property size
- libics.tools.math.intervalfunc.assume_func(func)
Returns an interval function within this module.
- Parameters
- funcstr or callable
If callable returns input. If str, gets the module-scoped function by name.
- Returns
- funccallable
Requested function.
- libics.tools.math.intervalfunc.cosh(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
cosh().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Hyperbolic cosine: \(y(t) = a \cosh((t - 1/2) / \tau) + c\).
Positional parameters:
- ypfloat
Peak value.
- taufloat
Time constant.
- libics.tools.math.intervalfunc.exp(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
exp().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Exponential: \(y(t) = a e^{t / \tau} + c\).
Positional parameters:
- taufloat
Time constant.
- libics.tools.math.intervalfunc.gauss(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
gauss().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Gaussian: \(y(t) = a e^{-(t - 1/2)^2 / 2 \tau^2} + c\).
Positional parameters:
- ypfloat
Peak value.
- taufloat
Time constant.
- libics.tools.math.intervalfunc.interval_func(*rescale_param)
Interval function factory.
- Parameters
- *rescale_paramint or str
Function call parameters which should be rescaled by the interval length dt. Use int to specify the indices of positional arguments. Use str to specify the keys of keyword arguments.
- Returns
- _ivf_factorycallable
Decorator for function func. Functions with call signature: func(t, y0, y1, *args), where t is the independent variable defined on the interval [0, 1], y0 and y1 are the functional values at t = 0 and t = 1.
Examples
To specify positional argument p1:
>>> @interval_func(1) >>> def func(t, y0, y1, p0, p1, p2, k0=0, k1=1, k2=2): ... pass
To specify keyword argument “k2”:
>>> @interval_func("k2") >>> def func(t, y0, y1, p0, p1, p2, k0=0, k1=1, k2=2): ... pass
- libics.tools.math.intervalfunc.lin(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
lin().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Linear: \(y(t) = a t + c\).
No additional parameters.
- libics.tools.math.intervalfunc.step(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
step().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Step: sudden rise and fall.
Positional parameters:
- ypfloat
Peak value.
Keyword parameters:
- tc0float
Time of first step.
- tc1float
Time of second step. Defaults to 1 - tc0.
- libics.tools.math.intervalfunc.tanh(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
tanh().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Hyperbolic tangent: \(y(t) = a \tanh((2 t - 1) / \tau) + c\).
Positional parameters:
- taufloat
Time constant.
- libics.tools.math.intervalfunc.trapez(t, y0, y1, *args, t0=0, t1=None, dt=1, rescale=True, **kwargs)
Interval function for
trapez().- Parameters
- tArray or Scalar
Independent variable.
- y0, y1float
Start, stop value.
- *args, **kwargs
Positional and keyword arguments passed to the actual function implementation. See below.
- t0, t1, dtfloat
Interval start value/stop value/extent. Specifying t1 takes precedence over dt.
- rescalebool or float
Whether to rescale scale-dependent function parameters. If float, uses given value for rescaling.
Notes
Trapezoidal: linear rise and fall, flat top.
Positional parameters:
- ypfloat
Peak value.
Keyword parameters:
- tc0float
Rise time.
- tc1float
Fall time. Defaults to 1 - tc0
calculus
- libics.tools.math.calculus.differentiate_array(ar, x=None, dx=None, axis=- 1, edge_order=2)
Differentiates an array.
- Parameters
- arArray
Function represented by an array.
- xArray(1, float)
Coordinates to differentiate along. Overwrites dx. If not given, deduces x from ar.
- dxfloat
Coordinate steps to differentiate along.
- axisint
Array dimension to differentiate along.
- edge_order1 or 2
Numerical differentiation using first/second-order-accurate differences at the boundaries.
- Returns
- ar_difArray
Differentiated array of same type as ar.
- libics.tools.math.calculus.integrate_array(ar, bounds=False, x=None, dx=None, x0=None, axis=- 1)
Performs a definite or indefinite 1D integral of an array.
- Parameters
- arArray
Function represented by an array.
- boundsbool or tuple(float)
False: performs indefinite integral. True: performs definite integral over full array. tuple(float): integration bounds [xmin, xmax].
- xArray(1, float)
Coordinates to integrate along. Overwrites dx. If not given, deduces x from ar.
- dxfloat
Coordinate steps to integrate along.
- x0None or float
Used only for indefinite integration, where \(F(x) = \int_{x_0}^{x} f(x') dx'\). If None, sets the integration constant to zero.
- axisint
Array dimension to integrate along.
- Returns
- ar_intArray or Number
If indefinite integration, returns same type as ar. If definite integration, removes one dimension of ar.
optimize
- libics.tools.math.optimize.maximize_discrete_stepwise(fun, *args, **kwargs)
Analogous to
minimize_discrete_stepwise()but maximizing.Minimizes a discrete function by nearest neighbour descent.
- Parameters
- funcallable
Function to be minimized. Its signature must be fun(x0, *args) -> float.
- x0Array[1] or Scalar
Initial guess for solution.
- argstuple(Any)
Additional function arguments.
- kwargsdict(str->Any)
Function keywword arguments.
- dxArray[1] or Scalar
Discrete steps along each dimension. If scalar, applies given step to all dimensions.
- search_rangeint
Number of discrete steps to be evaluated per iteration. E.g. search_range = 1 means evaluating in the range [-1, 0, 1]. Larger search_range avoids ending in local optimum but is slower.
- maxiterint
Maximum number of optimization steps.
- results_cachedict or None
Dictionary of pre-calculated results.
- ret_cachebool
Whether to return the results_cache.
- Returns
- xArray[1, float] or float
Solution. Scalar or vectorial depending on x0.
- results_cachedict
Results cache. Only returned if ret_cache is True.
- libics.tools.math.optimize.minimize_discrete_stepwise(fun, x0, args=(), kwargs={}, dx=1, search_range=1, bounds=None, maxiter=10000, results_cache=None, ret_cache=False)
Minimizes a discrete function by nearest neighbour descent.
- Parameters
- funcallable
Function to be minimized. Its signature must be fun(x0, *args) -> float.
- x0Array[1] or Scalar
Initial guess for solution.
- argstuple(Any)
Additional function arguments.
- kwargsdict(str->Any)
Function keywword arguments.
- dxArray[1] or Scalar
Discrete steps along each dimension. If scalar, applies given step to all dimensions.
- search_rangeint
Number of discrete steps to be evaluated per iteration. E.g. search_range = 1 means evaluating in the range [-1, 0, 1]. Larger search_range avoids ending in local optimum but is slower.
- maxiterint
Maximum number of optimization steps.
- results_cachedict or None
Dictionary of pre-calculated results.
- ret_cachebool
Whether to return the results_cache.
- Returns
- xArray[1, float] or float
Solution. Scalar or vectorial depending on x0.
- results_cachedict
Results cache. Only returned if ret_cache is True.
sampling
- libics.tools.math.sampling.get_nonlinear_support_points(start, stop, nr_points, func, offset=0.1, method='slope', **kwargs)
Creates a set of support points that are distributed to maximize sampling around regions of interest.
The overall idea is to distribute the sampling points to obtain an equidistant spacing by some critertion. Choosing “slope” as an example, the returned sampling points are weighted with the respective slope of the function.
- Parameters
- startfloat
Startpoint of scan. Will always be in final set of support points.
- stopfloat
Last point of scan. Will always be in final set of support points.
- nr_pointsint
Number of points in final set of support points.
- funccallable
A known a priori function that we want to sample.
- offsetfloat
Level of offset added to any background region of un-interest (meaning if we filter for “curvature”, any region without curvature is of un-interest). If set to 0, no sample points can be found in the regions without interest.
- methodstr
Possible strings are [“slope”, “curvature”, “max”, “equidistant”]. The method defines the region of interest where the sample points are generated.
- **kwargs
Additional arguments to be passed on to func.
- Returns
- xnp.ndarray(float)
Support points ranging from start to stop with special weight given according to method.
signal
- class libics.tools.math.signal.PeakInfo(data=None, fit=None, center=None, width=None, base=None, subpeak=None)
Bases:
libics.core.io.base.FileBaseResults class for peak analysis.
- Attributes
- dataArrayData(1, float)
Raw peak data.
- fitFitSkewGaussian1d
Fit model object representing best skew Gaussian fit to the raw data.
- centerfloat
(Fitted) maximum position of peak.
- widthfloat
(Fitted) standard deviation of peak.
- base(float, float)
(Left, right) base position corresponding to the estimated range of the fit validity.
- subpeakNone or PeakInfo
If None, no substructure in the peak is estimated. If PeakInfo, the
fitmay be insufficient to describe the peak, hence another subpeak is fitted (using only data outside of thebase).
Methods
attributes()Default saved attributes getter.
Gets the fitted peak data.
Recursively iterates all peaks (both top-level peak and subpeaks).
Recursively iterates all subpeaks.
load(file_path, **kwargs)Wrapper for
load()function.save(file_path, **kwargs)Wrapper for
save()function.separation_loc(peak_info_left, peak_info_right)Finds the position where the overlap between peaks is minimal.
- LOGGER = <Logger libics.tools.math.signal.PeakInfo (WARNING)>
- SER_KEYS = {'_fit', 'base', 'center', 'data', 'subpeak', 'width'}
- property distribution
- property distribution_amplitude
- property fit
- get_model_data()
Gets the fitted peak data.
- Returns
- adArrayData(1, float)
Fitted peak data evaluated at the positions of the raw data.
- iter_peaks()
Recursively iterates all peaks (both top-level peak and subpeaks).
- Yields
- peakPeakInfo
Peak.
- iter_subpeaks()
Recursively iterates all subpeaks.
- Yields
- subpeakPeakInfo
Subpeak.
- property nsubpeaks
Number of subpeaks.
- classmethod separation_loc(peak_info_left, peak_info_right)
Finds the position where the overlap between peaks is minimal.
This position is calculated by making the absolute mass on the “wrong” side of each peak equal. Takes the total mass of each peak into account
- Parameters
- peak_info_left, peak_info_rightPeakInfo
Left and right peaks.
- Returns
- xsfloat
Peak separation position.
- overlapl, overlaprfloat
Probability for the (left, right) peak to be on the wrong side of the separation line (i.e., the separation error probability).
- libics.tools.math.signal.analyze_single_peak(peak_ad, max_subpeaks=1, x0=None, alpha=None, c=0, p0=None, fit_class=<class 'libics.tools.math.peaked.FitSkewGaussian1d'>, max_width_std=0.001, min_subpeak_len_abs=5, min_subpeak_len_rel=0.2, maxfev=None, _is_recursion=False)
Fits a peak with a distribution model.
Recursively fits subpeaks to residuals.
- Parameters
- peak_adArray[1, float]
Raw peak data.
- max_subpeaksint
Maximal number of subpeaks to be fitted.
- x0float or None
If float, fixes the peak maximum position, thereby removing one fit degree of freedom. Only applied to top-level peak.
- alphafloat or None
If float, fixes the peak skewness parameter, thereby removing one fit degree of freedom. Only applied to top-level peak. Only applied for skewed models, e.g. for fit_class=FitSkewGaussian1d.
- cfloat
Fixed peak background level. Only applied to top-level peak.
- p0dict(str->float)
Fitting initial values.
- fit_classclass
Fit model class inheriting from
libics.tools.math.models.ModelBase. Must implement the parameters “a”, “x0”, “wx” and be associated with a distribution, i.e., must implement get_distribution() which must return a subclass oflibics.tools.math.models.RvContinuous. Examples are: FitGaussian1d, FitSkewGaussian1d, FitSymExponential1d.- max_width_stdfloat
Maximum fit uncertainty for the width to not continue to search for subpeaks.
- min_subpeak_len_absint
Minimum absolute number of data points to attempt subpeak fit.
- min_subpeak_len_relfloat
Minimum relative number of points outside the peak base to attempt subpeak fit.
- maxfevint or None
Maximum number of function evaluations for the fit.` If None, uses scipy.optimize.least_sq default.
- Returns
- peak_infoPeakInfo or None
If a peak could be fitted, returns a peak information object. If not, returns None.
- libics.tools.math.signal.correlate_g2(d1, d2, connected=False, normalized=False, mode='valid', method='auto')
Calculates a multidimensional two-point cross-correlation.
- Parameters
- d1, d2Arraylike
Input arrays.
- connectedbool
Whether to calculate connected correlation (E[x,y]-E[x]E[y]).
- normbool
Whether to calculate normalized correlation (E[x,y]/E[x]E[y]).
- modestr
“valid”, “full”, “same”.
- methodstr
“direct”, “fft”, “auto”.
- Returns
- dcArraylike
Correlation array of the same data type as the input arrays.
- libics.tools.math.signal.find_histogram(data, **kwargs)
Finds a 1D histogram.
- Parameters
- dataArray[float]
Array on which to calculate histogram.
- **kwargs
Keyword arguments passed to np.histogram.
- Returns
- histArrayData(1, float or int)
(Flattened) histogram.
- libics.tools.math.signal.find_peak_1d(*data)
Single-peak wrapper for
find_peaks_1d().- Parameters
- *dataArray[1, float] or (Array[1, float], Array[1, float])
1D data to find peaks in. Data may be provided as ArrayData, data or x, y.
- Returns
- center, center_errfloat
Peak position and uncertainty.
- libics.tools.math.signal.find_peaks_1d(*data, npeaks=None, rel_prominence=0.55, check_npeaks=True, base_prominence_ratio=None, edge_peaks=False, fit_algorithm='gaussian', ret_vals=None, _DEBUG=False)
Finds the peaks of a 1D array by peak prominence.
- Parameters
- *dataArray[1, float] or (Array[1, float], Array[1, float])
1D data to find peaks in. Data may be provided as ArrayData, data or x, y.
- npeaksint or None
Number of peaks to be found. If None, determines npeaks from rel_prominence.
- rel_prominencefloat
Minimum relative prominence of peak w.r.t. mean of other found peaks.
- base_prominence_ratiofloat or None
If None: the size of the base is unrestricted. If float: the base of a peak may not extend into the base of secondary peaks if these peaks have a relative prominence that is higher than base_prominence_ratio.
- edge_peaksbool
Whether to allow the array edge to be considered as peak.
- check_npeaksbool or str
If npeaks is given, checks that npeaks is smaller or equal to the number of peaks found by rel_prominence. Performs the following actions if this condition is not fulfilled: If error, raises RuntimeError. If warning or True, prints a warning. If False, does not perform the check.
- fit_algorithmstr or type(ModelBase)
Which algorithm to use for peak fitting among: “mean”, “gaussian”, “lorentzian”. Alternatively, a model class can be given. It must be subclassed from libics.tools.models.ModelBase; its center parameter must be called x0, its width wx.
- ret_valsIter[str]
Sets which values to return. Available options: “width”, “fit”.
- Returns
- resultdict(str->list(float))
Dictionary containing the following items:
- center, center_err
Peak positions and uncertainties.
- width
Peak width.
- fit
Fit object.
- libics.tools.math.signal.find_peaks_1d_prominence(*data, npeaks=None, rel_prominence=0.55, base_prominence_ratio=None, edge_peaks=False, check_npeaks='warning')
Finds positive peaks in 1D data by peak prominence.
- Parameters
- *dataArray[1, float] or (Array[1, float], Array[1, float])
1D data to find peaks in. Data may be provided as ArrayData, data or x, y.
- npeaksint or None
Number of peaks to be found. If None, determines npeaks from rel_prominence.
- rel_prominencefloat
Minimum relative prominence of peak w.r.t. mean of other found peaks.
- base_prominence_ratiofloat or None
If None: the size of the base is unrestricted. If float: the base of a peak may not extend into the base of secondary peaks if these peaks have a relative prominence that is higher than base_prominence_ratio.
- edge_peaksbool
Whether to allow the array edge to be considered as peak.
- check_npeaksbool or str
If npeaks is given, checks that npeaks is smaller or equal to the number of peaks found by rel_prominence. Performs the following actions if this condition is not fulfilled: If error, raises RuntimeError. If warning or True, prints a warning. If False, does not perform the check.
- Returns
- retdict(str->Array[1, Any])
Dictionary containing the following items:
- positionnp.ndarray(1, float)
Raw position of each peak.
- datalist(ArrayData)
List of sliced data containing the data of each peak.
- prominencenp.ndarray(1, float)
Prominence of each peak.
Notes
The number of returned peaks may vary.
tensor
- class libics.tools.math.tensor.DiagonalizableLS(*args, **kwargs)
Bases:
libics.tools.math.tensor.LinearSystemEigensystem solver for arbitrary square diagonalizable matrices.
The linear system is defined as
\[M x = y, x = \sum_p b_p m_p,\]where \(M\) is the matrix, \(x\) is the solution vector, \(y\) is the result vector, \((\mu_p, m_p)\) is the eigensystem and \(b_p\) is the eigenvector decomposition.
If the matrix has additional properties, please use the subclasses
HermitianLSandSymmetricLS.Notes
Usage:
Initialization: Set the matrix defining the linear system. Set the axes for higher rank tensors.
Given the matrix \(M\), this class allows for (1.) the calculation of the eigensystem \((\mu_p, m_p)\), (2.) solving for \(x\), and (3.) calculating the result \(y\).
Run
calc_eigensystem()to calculate eigenvalues and left/right eigenvectors.
If the eigenvalues should be arranged meaningfully, they can be ordered using
sort_eigensystem().For non-symmetric and non-Hermitian matrices or for degenerate eigenvalues, the eigenvectors are not orthogonal. A computationally expensive orthonormalization can be obtained with
ortho_eigensystem().
Given the result vector \(y\), there are two options to solve for \(x\).
If the eigensystem was calculated before, one can use
decomp_result()to obtain the eigenvector decomposition. Subsequently callingcalc_solution()calculates the solution vector \(x\).Alternatively, the solution can be obtained without eigensystem decomposition with
solve(), which only populates the solution vector \(x\).
Given the solution vector \(x\), there are two options to obtain the result \(y\).
If the eigensystem was calculated before, one can use
decomp_solution()to obtain the eigenvector decomposition. Subsequently callingcalc_result()calculates the result vector \(y\).Alternatively, the result can be obtained without eigensystem decomposition with
eval(), which only populates the result vector \(y\).
- Attributes
- decomp
- eigvals
- eigvecs
- is_defective
- is_diagonalizable
is_invertibleChecks the rank of the matrix.
- is_singular
- leigvecs
- mata_axes
- matb_axes
- matrix
- reigvecs
- result
- solution
- vec_axes
- veca_axes
- vecb_axes
Methods
Calculates eigenvalues, normalized left and right eigenvectors.
calc_result([decomp_vec])Calculates the result vector \(y\) from a decomposition vector \(b\).
calc_solution([decomp_vec])Calculates the solution vector \(x\) from a decomposition vector \(b\).
decomp_result([res_vec])Decomposes a result vector \(y\) into an overlap vector \(b\).
decomp_solution([sol_vec])Decomposes a solution vector \(x\) into an overlap vector \(b\).
eval([sol_vec])For a given solution vector \(x\), directly evaluates the result vector \(y\).
Orthonormalizes the eigenvectors.
solve([res_vec, algorithm])For a given result vector \(y\), directly solves for the solution vector \(x\).
sort_eigensystem([order])Sorts the eigensystem according to the given order.
- calc_eigensystem()
Calculates eigenvalues, normalized left and right eigenvectors.
Notes
The eigenvalues are in no guaranteed order. See
sort_eigensystem().The eigenvectors are not necessarily orthogonal. See
ortho_eigensystem().
- calc_result(decomp_vec=None)
Calculates the result vector \(y\) from a decomposition vector \(b\).
- calc_solution(decomp_vec=None)
Calculates the solution vector \(x\) from a decomposition vector \(b\).
- property decomp
- decomp_result(res_vec=None)
Decomposes a result vector \(y\) into an overlap vector \(b\).
- decomp_solution(sol_vec=None)
Decomposes a solution vector \(x\) into an overlap vector \(b\).
- property eigvals
- property eigvecs
- property is_defective
- property is_diagonalizable
- property is_invertible
Checks the rank of the matrix. Can be computationally expensive!
- property is_singular
- property leigvecs
- property matrix
- ortho_eigensystem()
Orthonormalizes the eigenvectors.
- property reigvecs
- sort_eigensystem(order=None)
Sorts the eigensystem according to the given order.
- Parameters
- ordernp.ndarray or callable or None
- np.ndarray:
Index order defined by this array. Dimensions: [n_dof].
- callable:
Eigenvalue measurement function whose ascendingly sorted return value defines the index order. Call signature: func(np.ndarray(…, n_dof))->float.
- None:
Index order ascending in modulus of eigenvalue.
- class libics.tools.math.tensor.HermitianLS(*args, **kwargs)
Bases:
libics.tools.math.tensor.DiagonalizableLSEigensystem solver for Hermitian diagonalizable matrices.
- Attributes
- decomp
- eigvals
- eigvecs
- is_defective
- is_diagonalizable
is_invertibleChecks the rank of the matrix.
- is_singular
- leigvecs
- mata_axes
- matb_axes
- matrix
- reigvecs
- result
- solution
- vec_axes
- veca_axes
- vecb_axes
Methods
Calculates eigenvalues, normalized left and right eigenvectors.
calc_result([decomp_vec])Calculates the result vector \(y\) from a decomposition vector \(b\).
calc_solution([decomp_vec])Calculates the solution vector \(x\) from a decomposition vector \(b\).
decomp_result([res_vec])Decomposes a result vector \(y\) into an overlap vector \(b\).
decomp_solution([sol_vec])Decomposes a solution vector \(x\) into an overlap vector \(b\).
eval([sol_vec])For a given solution vector \(x\), directly evaluates the result vector \(y\).
ortho_eigensystem()Orthonormalizes the eigenvectors.
solve([res_vec, algorithm])For a given result vector \(y\), directly solves for the solution vector \(x\).
sort_eigensystem([order])Sorts the eigensystem according to the given order.
- calc_eigensystem()
Calculates eigenvalues, normalized left and right eigenvectors.
Notes
The eigenvalues are in no guaranteed order. See
sort_eigensystem().The eigenvectors are not necessarily orthogonal. See
ortho_eigensystem().
- class libics.tools.math.tensor.LinearSystem(matrix=None, mata_axes=- 2, matb_axes=- 1, veca_axes=- 1, vecb_axes=- 1, vec_axes=None)
Bases:
objectLinear system solver for arbitrary complex matrices.
The linear system is defined as
\[M x = y,\]where \(M\) is the matrix, \(x\) is the solution vector, and \(y\) is the result vector.
For a given matrix \(M\) and solution vector \(x\), this class supports evaluation of \(y\). If \(y\) is given, the system supports direct solving for \(x\). The matrix and vector dimensions can consist of multiple indices which are automatically linearized. For an eigensystem solver, refer to
DiagonalizableLS.- Parameters
- matrixnp.ndarray
Possibly high rank tensor representable as diagonalizable matrix, defining a linear system. There must be two sets of dimensions which can be reshaped as square matrix. The remaining dimensions will be broadcasted.
- mata_axes, matb_axes, veca_axes, veca_bxestuple(int)
Axes representing the multidimensional indices of the matrix. \(M = M_{\{a_1, ...\}, \{b_1, ...\}}, x, y = x, y_{\{v_1, ...\}}\). \(M x = y = \sum_b M_{a, b} x_b = y_a\). The shape of each dimension must be identical and the total number defines the degrees of freedom \(n_{\text{dof}} = \prod_i n_i\).
- Attributes
- mata_axes
- matb_axes
- matrix
- result
- solution
- vec_axes
- veca_axes
- vecb_axes
Methods
eval([sol_vec])For a given solution vector \(x\), directly evaluates the result vector \(y\).
solve([res_vec, algorithm])For a given result vector \(y\), directly solves for the solution vector \(x\).
- eval(sol_vec=None)
For a given solution vector \(x\), directly evaluates the result vector \(y\).
- property mata_axes
- property matb_axes
- property matrix
- property result
- property solution
- solve(res_vec=None, algorithm=None)
For a given result vector \(y\), directly solves for the solution vector \(x\).
- property vec_axes
- property veca_axes
- property vecb_axes
- class libics.tools.math.tensor.SymmetricLS(*args, **kwargs)
Bases:
libics.tools.math.tensor.DiagonalizableLSEigensystem solver for complex symmetric diagonalizable matrices.
- Attributes
- decomp
- eigvals
- eigvecs
- is_defective
- is_diagonalizable
is_invertibleChecks the rank of the matrix.
- is_singular
- leigvecs
- mata_axes
- matb_axes
- matrix
- reigvecs
- result
- solution
- vec_axes
- veca_axes
- vecb_axes
Methods
Calculates eigenvalues, normalized left and right eigenvectors.
calc_result([decomp_vec])Calculates the result vector \(y\) from a decomposition vector \(b\).
calc_solution([decomp_vec])Calculates the solution vector \(x\) from a decomposition vector \(b\).
decomp_result([res_vec])Decomposes a result vector \(y\) into an overlap vector \(b\).
decomp_solution([sol_vec])Decomposes a solution vector \(x\) into an overlap vector \(b\).
eval([sol_vec])For a given solution vector \(x\), directly evaluates the result vector \(y\).
ortho_eigensystem()Orthonormalizes the eigenvectors.
solve([res_vec, algorithm])For a given result vector \(y\), directly solves for the solution vector \(x\).
sort_eigensystem([order])Sorts the eigensystem according to the given order.
- calc_eigensystem()
Calculates eigenvalues, normalized left and right eigenvectors.
Notes
The eigenvalues are in no guaranteed order. See
sort_eigensystem().The eigenvectors are not necessarily orthogonal. See
ortho_eigensystem().
- libics.tools.math.tensor.calc_op_outer(ar1, ar2, op='*', reduce_ndim=1, ret_dims=False, dtype=None)
Perform elementwise operation with broadcasting.
- Parameters
- ar1, ar2Array
Arrays as first and second operators with dimensions: [{non_ar1/2_dims}, {red_dims}].
- opstr or callable
Binary operator as function or from
BINARY_OPS_NUMPY.- reduce_ndimint
Number of dimensions (from the last axis) to perform the operation elementwise. Other dimensions are broadcasted by outer product.
- ret_dimsbool
Flag whether to return the number of non-positional dimensions of the vectors ar1 and ar2.
- dtypetype
Numpy dtype of return value.
- Returns
- arArray
Reduced operator result with dimensions: [{non_ar1_dims}, {non_ar2_dims}, {red_dims}].
- non_ar1_dims, non_ar2_dimsint
Number of non-reduced dimensions of respective axes. Only returned if ret_dims is True.
- libics.tools.math.tensor.complex_norm(ar, axis=None)
Computes the pseudonorm \(\sqrt{x^T x}\) on the complex (tensorial) vector \(x\).
- Parameters
- arnp.ndarray
Array constituting the vector to be normalized.
- axistuple(int)
Tensorial indices corresponding to the vectorial dimensions.
- Returns
- normnp.ndarray
Resulting norm with removed vectorial axes.
- libics.tools.math.tensor.euclid_norm(ar, axis=None)
Computes the Euclidean norm \(\sqrt{x^\dagger x}\) on the complex (tensorial) vector \(x\).
- Parameters
- arnp.ndarray
Array constituting the vector to be normalized.
- axistuple(int)
Tensorial indices corresponding to the vectorial dimensions.
- Returns
- normnp.ndarray
Resulting norm with removed vectorial axes.
- libics.tools.math.tensor.extract_diag(tensorized_matrix)
Extracts a diagonal tensor.
- Parameters
- tensorized_matrixnp.ndarray
“Matrix” with dimensions: [{vec_dims}, {vec_dims}].
- Returns
- tensorized_vectornp.ndarray
“Vector” with dimensions: [{vec_dims}]. Contains the multi-dimensional diagonal elements of tensorized_matrix.
Notes
Inverse operation of
make_diag().
- libics.tools.math.tensor.get_dirac_delta(*shape, dtype=None, order='abab')
Gets a multi-dimensional Dirac delta tensor.
- Parameters
- *shapeint
Entries per dimension.
- dtypenp.dtype
Data type of generated array.
- orderstr
Dimensional order of Dirac delta. “abab”, “aabb”.
- Returns
- dirac_deltanp.ndarray
Multi-dimensional Dirac delta tensor.
- libics.tools.math.tensor.insert_dims(ar, ndim, axis=- 1)
Expands the dimensions of an array.
- Parameters
- arnp.ndarray
Array to be expanded.
- ndimint
Number of dimensions to be inserted.
- axisint
Dimensional index of insertion.
- Returns
- arnp.ndarray
Expanded array.
Examples
>>> ar = np.arange(2 * 3 * 4).reshape((2, 3, 4)) >>> insert_dims(ar, 3, axis=-2).shape (2, 3, 1, 1, 1, 4)
- libics.tools.math.tensor.make_diag(tensorized_vector)
Creates a diagonal tensor.
- Parameters
- tensorized_vectornp.ndarray
“Vector” with dimensions: [{vec_dims}].
- Returns
- tensorized_matrixnp.ndarray
Diagonal “matrix” with dimensions: [{vec_dims}, {vec_dims}]. Contains the tensorized_vector elements on its diagonal.
Notes
Inverse operation of
extract_diag().
- libics.tools.math.tensor.ortho_gram_schmidt(vectors, norm_func=<function norm>)
Naive Gram-Schmidt orthogonalization.
- Parameters
- vectorsnp.ndarray
Normalized, linearly independent row vectors to be orthonormalized. Dimensions: [n_vector, n_components].
- normcallable
Function computing a vector norm. Call signature: norm_func(vector)->scalar.
- Returns
- basisnp.ndarray
Orthonormal basis of space spanned by vectors. Dimensions: [n_vector, n_components].
- libics.tools.math.tensor.tensorinv_numpy_array(ar, a_axes=- 2, b_axes=- 1)
Calculates the tensor inverse (w.r.t. to
tensormul_numpy_array()).- Parameters
- arnp.ndarray
Full tensor.
- a_axes, b_axestuple(int)
Corresponding dimensions to be inverted. These specified dimensions span an effective square matrix.
- Returns
- arnp.ndarray
Inverted full tensor.
- libics.tools.math.tensor.tensorize_numpy_array(vec, tensor_shape, tensor_axes=(- 2, - 1), vec_axis=- 1)
Tensorizes a vectorized numpy array. Opposite of
vectorize_numpy_array().- Parameters
- vecnp.ndarray
Vector array.
- tensor_shapetuple(int)
Shape of tensorized dimensions.
- tensor_axestuple(int)
Tensor axes of resulting array. Tensorization is performed in C-like order.
- vec_axisint
Dimension of vector array to be tensorized.
- Returns
- arnp.ndarray
Tensor array.
- libics.tools.math.tensor.tensormul_numpy_array(a, b, a_axes=(Ellipsis, 0), b_axes=(0, Ellipsis), res_axes=(Ellipsis,))
Einstein-sums two numpy tensors.
- Parameters
- a, bnp.ndarray
Tensor operands.
- a_axes, b_axes, res_axestuple(int)
Indices of Einstein summation. Dimensions are interpreted relative. Allows for use of ellipses. res_axes allows for None to obtain a scalar.
- Returns
- resnp.ndarray
Combined result tensor.
Notes
This function wraps numpy.einsum.
Examples
Denote: (a_axes), (b_axes) -> (res_axes) [np.einsum string]
Matrix multiplication: e.g. (0, 1), (1, 2) -> (0, 2) [“ij,jk->ik”].
Tensor dot: e.g. (0, 1, 2, 3), (4, 2, 3, 5) -> (0, 1, 4, 5) [“ijkl,mjkn->ilmn”].
Tensor dot with broadcasting: e.g. (0, 1, 2, 3), (0, 1, 2, 3) -> (0, 3) [“ijkl,ijkl->il”].
- libics.tools.math.tensor.tensorsolve_numpy_array(ar, res, a_axes=- 2, b_axes=- 1, res_axes=- 1, algorithm=None)
Solves a tensor equation \(A x = b\) for \(x\), where all operands may be high-dimensional.
- Parameters
- arnp.ndarray
Matrix tensor \(A\).
- resnp.ndarray
Vector tensor \(b\).
- a_axes, b_axes, res_axestuple(int)
Tensorial indices corresponding to \(\sum_{b} A_{ab} x_b = y_{res}\).
- algorithmNone or str
None or “lu_fac”: LU factorization. “lst_sq”: least squares optimization.
- Returns
- solnp.ndarray
Solution vector tensor \(x\) with solution indices res_axes.
Notes
Tries to solve the linear equation using a deterministic full-rank solver. If this fails, a least-squares algorithm is used. The least-squares solver does not support broadcasting.
- libics.tools.math.tensor.tensortranspose_numpy_array(ar, a_axes=- 2, b_axes=- 1)
Transposes the matrix spanned by a_axes, b_axes.
- Parameters
- arnp.ndarray
Full tensor.
- a_axes, b_axestuple(int)
Corresponding dimensions to be transposed. These specified dimensions span an effective square matrix.
- Returns
- arnp.ndarray
Transposed full tensor.
- libics.tools.math.tensor.vectorize_numpy_array(ar, tensor_axes=(- 2, - 1), vec_axis=- 1, ret_shape=False)
Vectorizes a tensor (high-dimensional) numpy array. Opposite of
tensorize_numpy_array().- Parameters
- arnp.ndarray
Tensor array.
- tensor_axestuple(int)
Tensor axes to be vectorized. Vectorization is performed in C-like order.
- vec_axisint
Vectorized dimension of resulting vector array.
- ret_shapebool
Flag whether to return the shape of the vectorized dimensions.
- Returns
- vecnp.ndarray
Vector array.
- vec_shapetuple(int)
If ret_shape is set: shape of vectorized dimensions. Useful as parameter for tensorization.
Notes
Performance is maximal for back-aligned, ordered vectorization since in-place data ordering is possible.
Examples
Given a tensor A[i, j, k, l], required is a vectorized version A[i, j*k, l]. The corresponding call would be:
>>> i, j, k, l = 2, 3, 4, 5 >>> A = np.arange(i * j * k * l).reshape((i, j, k, l)) >>> A.shape (2, 3, 4, 5) >>> B = vectorize_numpy_array(A, tensor_axes=(1, 2), vec_axis=1) >>> B.shape (2, 12, 5)