Source documentation

mugui

Main GUI class

— tools — Utilities

tools.tools.TauMu_mus()[source]

muon mean lifetime in microsecond from Particle Data Group 2017 (not present in scipy.constants)

tools.tools._available_components_()[source]

returns a list of template dictionaries (one per fit component): retreived magically from the mucomponents mumodel class.

Each dictionary contains ‘name’ and ‘pardicts’,
‘pardicts’ = list of parameter dictionaries,
keys:
‘name’, ‘error, ‘limits’

errore are used by minuit as initial steps limits are

[None,None] for uncostrained parameters A,B,φ,λ [0,None] for positive parity parameters Δ,σ

and for positive defined parameters ‘α’,’β’,’Λ’,’ν’

[0,0] for fake parameter BL

:: ({‘name’:’bl’,’pardicts’:[{‘name’:’A’,’error’:0.01,’limits’[None,None]},
{‘name’:’λ’,’error’:0.01,’limits’[None,None]}}, …)
tools.tools._errors_(component, available_components)[source]

inputs: one legal mucomponent name contained in the _available_components_(), which must be the second input output: a list of errors (steps), one for each parameter of this component

tools.tools._limits_(component, available_components)[source]

inputs: one legal mucomponent name contained in the _available_components_(), which must be the second input output: a list of lists of limits (low, high), one for each parameter of this component

tools.tools._nparam(model)[source]

input: dashboard[‘model_guess’] output: ntot, nmintot, nfree

tools.tools._ps_acme_score(ph, data)[source]

Phase correction using ACME algorithm by Chen Li et al. Journal of Magnetic Resonance 158 (2002) 164-168

Parameters * pd : tuple, current p0 and p1 values * data : ndarray, array of NMR data.

Returns * score : float, value of the objective function (phase score)

tools.tools._ps_peak_minima_score(ph, data)[source]

Phase correction using simple minima-minimisation around highest peak This is a naive approach but is quick and often achieves reasonable results. The optimisation is performed by finding the highest peak in the spectra (e.g. TMSP) and then attempting to reduce minima surrounding it. Parameters * pd : tuple, current p0 and p1 values * data : ndarray, array of NMR data.

Returns * score : float, value of the objective function (phase score)

tools.tools.add_step_limits_to_model(dash_in)[source]

input: original dashboard dash_in, already checked output: dash_out is a deepcopy including ‘error’ and ‘limits’

tools.tools.addcomponent(name)[source]

addcomponent(‘ml’) # adds e.g. a mu precessing, lorentzian decay, component this method adds a component selected from _available_components_(), tuple of directories with zeroed values, error and limits from available_components, flags set to ‘~’ and zeros functions [plan also addgroupcomponents and addruncomponents (for A2, B2, C1, C2)]

tools.tools.autops(data, fn, p0=0.0, p1=0.0)[source]

Automated phase correction from NMRglue by https://github.com/jjhelmus These functions provide support for automatic phasing of NMR data.

Automatic linear phase correction

Parameters

data : ndarray

Array of NMR data.

fn : str or function

Algorithm to use for phase scoring. Built in functions can be specified by one of the following strings: “acme”, “peak_minima”

p0 : float

Initial zero order phase in degrees.

p1 : float

Initial first order phase in degrees.

Returns

ndata : ndarray

Phased NMR data.
tools.tools.calib(dashboard)[source]

True if the first component is ‘al’

tools.tools.checkvalidmodel(name, component_names)[source]

checkvalidmodel(name) checks that name is either :: A1, B1: 2*component string of valid component names, e.g.

‘daml’ or ‘mgmgbl’
:: or A2, B2: same, ending with 1 digit, number of groups (max 9 groups),
‘daml2’ or ‘mgmgml2’ (2 groups)
:: or C1: same, beginning with 1 digit, number of external minuit parameters (max 9)
‘3mgml’ (3 external parameters e.g. A, f, phi)
:: or C2: same, both previous options
‘3mgml2’ (3 external parameters, 2 groups)
tools.tools.chi2_csv(chi2, lowchi2, hichi2, groups, offset)[source]
input:
chi2, chi2-sdt, chi2+sdt, groups, offset (bins) groups is suite.groups and its len, 1 or more, identifies multigroup
output:
cvs partial row with these values and timestring
tools.tools.chi2std(nu)[source]

computes 1 std for least square chi2

tools.tools.component(model, kin)[source]

returns the index of the component to which parameter k belongs in model = self.model_guess, in mugui, a list of complex dictionaries:

[{'name':'da', 'pardicts':{'name':'lpha',...},
{'name':'mg', 'pardicts':{       ...       }]

kin is the index of a dashboard parameter (kint)

tools.tools.create_model(model)[source]

create_model(‘daml’) # adds e.g. the two component ‘da’ ‘ml’ model this method does not check syntax (prechecked by checkvalidmodel)

? separates nexternals number from model name (e.g. ‘3mgml’ -> ‘mgml’, 3) ? starts switchyard for A1,A1,B1, B2, C1, C2 fits

adds a model of components selected from the available_component tuple of directories with zeroed values, stepbounds from available_components, flags set to ‘~’ and zeros functions

tools.tools.cstack(npfunc, x, *pars)[source]

vectorialize npfunc input:

npfunc numpy function with input (x,*argv) x time *pars is a list of lists of parameters,

list len n is the output_function_array.shape[0]
output:
output_function_array
stacks vertically n replica of npfunc distributing parameters as in (x, *argv[i]) for each i-th replica
tools.tools.derange(string, vmax, pack=1)[source]

derange(string,vmax,pack=1) reads string assumes it contains 2, 3, 4 or 5 csv or space separated values uses isinstance(vmax,float) to distinguish floats (fft) from integers (fit and plot)

5: start, stop, packe, last, packl # for plot 4: start, stop, last, packl # for plot (packe is 1) 3: start, stop, pack 2: start, stop (pack is added, pack default is 1)

returns 2, 3, 4 or 5 floats or int, or default values, 0,vmax,pack, if fails validity check (stop>start, bin <stop-start, last < vmax) errmsg = ‘’ in ok, a string indicates errors

tools.tools.derun(string)[source]

parses string, producing a list of runs; expects comma separated items

looks for ‘l’,’l:m’,’l+n+m’,’l:m:-1’ where l, m, n are integers also more than one, comma separated

rejects all other characters

returns a list of lists of integer

tools.tools.diffunc(func)[source]
input user function of the form ‘p[0]*(1-p[1])’
up to functions of three parameters (this could be easily extended)

output a list of its derivatives [with respect to ‘p[0]’ and ‘p[1]’] and the list of their indices, [0,1]

tools.tools.errorpropagate(string, p, e)[source]

parse function in string

substitute p[n] with xn, with errors en calculate the partial derivative pdn = partial f/partial xn return the sqrt of the sum of (pdn*en)**2

tools.tools.exit_safe()[source]

opens an are you sure box?

tools.tools.fft_filter(t, fy, f0)[source]

filter above 0.2*fy peak freq works for 1-2 d

tools.tools.find_nth(haystack, needle, n)[source]

Finds nth needle in haystack

Returns its first occurrence (0 if not present)

Used by ?

tools.tools.findall(p, s)[source]

Yields all the positions of the pattern p in the string s.

Used by translate.

tools.tools.get_datafile_path_ext(datafile, run)[source]

datafilename = template, e.g. ‘/fullpath/deltat_gps_tdc_0935.bin’ run = string of run digits, e.g. ‘1001’ returns ‘/fullpath/deltat_gps_tdc_1001.bin’

tools.tools.get_datafilename(datafile, run)[source]

datafilename = template, e.g. ‘/fullpath/deltat_gps_tdc_0935.bin’ run = string of run digits, e.g. ‘1001’ returns ‘/fullpath/deltat_gps_tdc_1001.bin’

tools.tools.get_fit_range(string)[source]

transform a valid string for fit_range into a list of integers

tools.tools.get_functions_in(model, kk)[source]
input

model = single-run model dashboard dict kk = kloc -1, is incremented at each free parameter of the model, so that it scans the internal minuit indices

for these parameters (ignoring those determined by a user funct e.g. “p[0]*p[4]”
output
functions_in = list of lists, one per component, of user functs, one per parameter, for the single-run model,
all component parameters, including “~” and “!”, are translated to appropriate user funct
tools.tools.get_group(grouping)[source]

reverse of get_grouping, input

grouping is an np.array of indices of detectors , 0 based
output is
groupcsv shorthand as in self.group[k][“forward”} or self.group[k][“backward”}
e.g ‘1:3,5’ or ‘1,3,5’ etc.
tools.tools.get_grouping(groupcsv)[source]
input

groupcsv is a shorthand csv string, e.g. ‘1:3,5’ or ‘1,3,5’ etc. contained in self.suite.group[k][“forward] of self.suite.group[k][“backward”]

(the k-th detector group of a multi group fit)
output
grouping is an np.array of indces, 0 based
tools.tools.get_indices(func)[source]
input
func is a user string function, e.g. ‘p[0]*p[2]’
output
list of (string) indices found in the string, in between ‘p[’ and ‘]’, e.g. ‘0’,’2’
tools.tools.get_nruns(the_suite)[source]

get nrun strings

tools.tools.get_number_minuit_internal(nruns, n_globals, n_locals, model)[source]
tools.tools.get_run_number_from(path_filename, filespecs)[source]

strips number after filespecs[0] and before filespec[1]

tools.tools.get_run_title(the_suite)[source]
output
list of run and title strings
each run and group in the run replicates its run number + title

used only in mufitplot (fit and fft

tools.tools.get_title(run, notemp=False, nofield=False)[source]

form standard psi title

tools.tools.get_totals(suite)[source]

calculates the grand totals and group totals of a single run iput is self.suite of class musuite returns strings totalcounts groupcounts nsbin maxbin

tools.tools.getname(fullname)[source]

estracts parameter name from full parameter name (i.e. name + label) for the time being just the first letter

tools.tools.group_shorthand(grouping)[source]

group_calib is the list of gorup dictionaries

tools.tools.initialize_csv(Bstr, filespec, the_run)[source]

writes beginning of csv row with nrun T [T eT T eT] B for ISIS [PSI]

tools.tools.int2_calib_method_key(dashboard, the_model)[source]

NOT USED, remove input: the dashboard dict structure and the fit model ‘alxx..’ instance

the actual model contains ‘al’ plus ‘xx’, .. the present method considers only the latter FOR PLOTTING ONLY (USE int2_method for the actual calib fit)
output: a list of methods for calib fits, in the order of the ‘xx..’ model components
(skipping al) for the use of mumodel._add_single_.
Invoked by the iMinuit initializing call
self._the_model_._load_data_,

just before submitting migrad, self._the_model_ is an instance of mumodel

This function applies tools.translate to the parameter numbers in formulas since on the dash each parameter of each component gets an internal number, but alpha is popped and shared or formula-determined (‘=’) ones are not minuit parameters

tools.tools.int2_calib_multigroup_method_key(dashboard, the_model)[source]

NOT USED, remove input: the dashboard dict structure and the fit model ‘alxx..’ instance

the actual model contains ‘al’ plus ‘xx’, .. the present method considers only the latter FOR PLOTTING ONLY (USE int2_method for the actual calib fit)
output: a list of methods for calib fits, in the order of the ‘xx..’ model components
(skipping al) for the use of mumodel._add_single_.
Invoked by the iMinuit initializing call
self._the_model_._load_data_,

just before submitting migrad, self._the_model_ is an instance of mumodel

This function applies tools.translate to the parameter numbers in formulas since on the dash each parameter of each component gets an internal number, but alpha is popped and shared or formula-determined (‘=’) ones are not minuit parameters

tools.tools.int2_method_key(dashboard, the_model)[source]
input:
dashboard, the dashboard dict structure the_model, a fit model instance (not necessarily loaded)
output:
a list of lists, the inner lists contain each
method, a mumodel component method, in the order of the model components
for the use of mumodel._add_.
keys, a list of as many lambda functions as the parameters of teh component
hard coding the translated “function” string for fast evaluation.

This function applies tools.translate to the parameter numbers in formulas: dashboard “function” is written in terms of the internal parameter index, while Minuit parameter index skips shared or formula-determined (‘=’) parameters

tools.tools.int2_multigroup_method_key(dashboard, the_model)[source]
input:

dashboard, the dashboard dict structure fit._the_model_ is an instance of mumodel

(the number of groups is obtained from dashboard)
output: a list of methods and keys, in the order of the model components

for the use of mumodel._add_multigroup_. method is a 2d vector function accepting time and a variable number of lists of (component) parameters

e.g if one component is mumodel.bl(x,A,λ) the corresponding component for a two group fit accepts the following argument (t,[A1, A2],[λ1,λ2])

keys is a list of lists of strings they are evaluated to produce the method parameters, there are

ngroups strings per parameter (inner list) npar parametes per component (outer list)
Invoked by the iMinuit initializing call
self._the_model_._load_data_multigroup_

just before submitting migrad,

This function does not need userpardicts and tools.translate since the correspondence with Minuit parameters is given directly either by “function” or by “function_multi”

tools.tools.int2_multirun_grad_method_key(dashboard, the_model, nruns)[source]
input:
dashboard, the dashboard dict structure the_model is fit._the_model_ i.e. an instance of global multirun mumodel nruns is the numer of runs in the suite
output
minuit_ordered_grad_list
i.e. a list of lists [k,n,j,grad_bndmthd,dkey])], one for each minuit internal parameter p[m]

k n j are indices of run, component and parameter for which dkndj_bndmthd is the <module> that computes the derivative of component n in run k with respect to parameter j

(if par are the parameters for component n in run k, then dkndj_bndmthd(x,*par) calculates the derivative)
djdm is a <module> that computes the derivative of the user funct (e.g. “p[0]*p[21]’) with respect to p[m]
(then djdm(p) is the value of the derivative)

The products of these derivatives is sparse, i.e. non zero only for few values k,n,j The present method identifies each and every set of indices (k,n,j) for which the product

gg_nj = dkndj_bndmthd(x,*par)*djdm(p) != 0

————————— Usage To generate chisquare grad values for all minuit parameters, in order to optimize numpy miniut calculations; mucomponents _add_multirun_grad_ uses the 2D array

gg = sum_n,j gg_nj

and multiplies it by the 2D array dcdf = 2(f-y)/e^2 The m-th component of the chisquare gradient is sum(dcdf*gg,axis=None) ————————– General equation Assuming asymmetry data end errors y(k;i), ey(k;i), the expression for the chisquare gradient is

sum_i,k {2(sum_n y_n(k;i,*par(k,n))-y(k;i))/ey(k;i)^2} * sum_n,j {partial y_n(k;i,*par(k,n)/partial par[k,n,j]} * {partial par[k,n,j]/partial p[m]}

hereafter dcdf * sum_n,j dkndj * djdm

tools.tools.int2_multirun_user_method_key(dashboard, the_model, nruns)[source]
input:
dashboard, the dashboard dict structure the_model is fit._the_model_ i.e. an instance of mumodel nruns is the numer of runs in the suite

output: a list of methods and a list of lists of keys, [[key,…,key],…,[key,..,key]] the internal list is same parameter, different runs the model components

for the use of mumodel._add_multirun_. method is a component function accepting time and a list of parameters, e.g mumodel.bl(x,A,λ) key is string defining a lambda function that produces one method parameter for a specific run, the list is for the same parameter over diffenet runs keys is a list of lists for all the parameters (any flag) of the component the list of [binding,keys] is over the components of the model

This list of [binding, keys] allows mumodel _add_multirun_ to use the minuit p list (n_globals global user values, followed by nruns replica of

n_locals local user values and a model specific number of local (~,!) component par values)

to produce component-driven vectorized values, as many values in the vector as the runs In this way minuit fcn is a vector, one fcn per run, likewise asymm, asyme are vectors (see suite for multirun) and mumodel._chisquare_ cost function sums over individual runs for a unique global chisquare Invoked by the iMinuit initializing call

self._the_model_._load_data_multirun_user_

just before submitting migrad

tools.tools.int2fft(model)[source]
input:
model
dashboard[“model_guess”]
output:
fft_subtract: a list of boolean values, one per model component
fft flag True, component subtracted in residues
tools.tools.int2min(model)[source]
input:
model
either dashboard[“model_guess”] (after add_step_limits_to_model) or dashboard[“model_guess”] both lists of dicts
output: a list of lists:
values: minuit parameter values, either guess of result errors: their steps fixed: True/False for each limits: [low, high] limits for each or [None,None] names: name of parameter ‘x_label’ for each parameter pospar: parameter for which component is positive parity, eg s in e^{-(s*t)^2/2}
tools.tools.int2min_multigroup(pardicts)[source]
input:
pardicts
either dashboard[“userpardicts_guess”] if guess = True or dashboard[“userpardicts_result”] if guess = False
output: a list of lists:
values: minuit parameter values, either guess of result errors: their steps fixed: True/False for each limits: [low, high] limits for each or [None,None] name: name of parameter ‘x_label’ for each parameter pospar: parameter for which component is positive parity, eg s in e^{-(s*t)^2/2}

this works for A2 single fit, multigroup with userpardicts parameters = Minuit parameters

tools.tools.int2min_multirun(dashboard, runs)[source]
input:
dashboar for single group multirun
containins both
dashboard[“userpardicts_guess”] or dashboard[“userpardicts_result”] dashboard[“model_guess”] (after add_step_limits_to_model) or dashboard[“model_result”]

runs = list of run numbers

output: a list of lists, each list containing minuit internal parameters for a run
values: minuit parameter values, either guess of result errors: their steps fixed: True/False for each limits: [low, high] limits for each or [None,None] names: name of parameter ‘x_label’ for each parameter pospar: parameter for which component is positive parity, eg s in e^{-(s*t)^2/2}
Note: this method knows the model, hence it can generate only minuit parameters
mucomponents, i.e. the cost function, needs to feed also non minuit parameters to the components e.g. mg with A global B1 local phi global s1 global will have only two minuit parameters per run , the second and the fourth, and it must know which value to use for the first and third This is accomplished by _add_multirun_singlegroup_ in mucomponents, using self._components_
tools.tools.json_name(model, datafile, grouping, version, g=False)[source]

model is e.g. ‘mlmg’ datafile is e.g. ‘/afs/psi.ch/bulkmusr/data/gps/d2022/tdc/deltat_gps_tdc_1233.bin’

must have a single ‘.’

grp_calib is the list of dictionaries defining the groups g = True for global version is a label returns a unique name for the json dashboard file

tools.tools.len_print_components(names, values, errors)[source]
input: for a component
parameter names parameter values parameter errors
output:
max length of string to print, e.g. “bl.A_fast 0.123(4) bl.λ_fast 12.3(4) bl.σ_fast 0(0)”
tools.tools.len_print_components_multirun(names, values, errors)[source]
input: for a component
parameter names parameter values parameter errors
output:
max length of string to print, e.g. “bl.A_fast 0.123(4) bl.λ_fast 12.3(4) bl.σ_fast 0(0)”
tools.tools.min2int(model_guess, values_in, errors_in)[source]
input:
model_component from dashboard values_in Minuit.values errors_in Minuit.errors
output: for all dashbord parameters
names list of lists of parameter names values_out list of lists of their values errors_out list of lists of their errors

reconstruct dashboard with Minuit best fit values and errors for print_components, compact fit summary

tools.tools.min2int_multigroup(dashboard, p, e)[source]
input:
userpardicts_guess from dashboard
(each dict corresponds to a Minuit parameter)
x used only to retrieve “function”
and “error_propagation_multi” p,e Minuit best fit parameter values and std
output: for all parameters
namesg list of lists of dashboard parameter names parsg list of lists of dashboard parameter values eparsg list of lists of dashboard parameter errors

used only in summary_global

tools.tools.min2int_multirun(dashboard, p, e, _the_runs_)[source]
input:
dashboard; userpardicts_guess and model_guess from
used only to retrieve “function” or “function_multi” and “error_propagation_multi”

p,e Minuit best fit parameter values and std _th_runs_ = list of run numbers in suite

output: for all parameters
names list of lists of parameter names pars list of lists ofparameter values epars list of lists of parameter errors
used only in summary_multirun_global that prints name value(error)
one or more lines of global user parameters (the first list in the inner lists) one line per run local user parameters and local component parameters (the others)
tools.tools.minglobal2sequential(p_out, p_in, method_keys, dashboard)[source]

translate global best fit results (values) into nruns equivalent sequential fits for plotting purposes: mufitplot(plot_range,the_fit) will access self.fit.lastfits and self.fit.dashboard_single if self.fit.C1 is True input:

p_out is global best fit minuit parameters self.lastfit p_in is global fit minuit guess parameters values_in method_key is produced by int2_multirun_user_method_key dashboard is the fit global dashboard results toggles between plotting result of guess
output:
lastfits, list of lists of best fits, in the style of multirun sequential single group (B1) dashboard_single (a dashboard that produces a single run best fit function for animated plots)
tools.tools.minparam2_csv(dashboard, values_in, errors_in, multirun=0)[source]

transforms Minuit values Minuit errors in cvs format input:

dashboard
dashboard[“model_guess”], for single group None, for multi group dashboard, for single group multirun user (C1)

values_in, errors_in are Minuit values Minuit errors if multirun is nruns !=0 (True) uses

min2int_multirun(dashboard,values_in,errors_in,multirun_nruns)
else (multirun = 0 (False) uses
min2int(dashboard,values_in,errors_in)
output:
cvs partial row with parameters and errors for A1, A20 and B1, or A21
list of partial rows (one per run) for C1
tools.tools.mixer(t, y, f0)[source]

mixer of a time-signal with a reference input

t time y the time-signal f0 frequency of the cosine reference
output
y_rrf = 2*y*cos(2*pi*f0*t)

t is 1d and y is 1-d, 2-d or 3-d but t.shape[0] == y.shape[-1] t is vstack-ed to be the same shape as y

tools.tools.model_name(dashboard)[source]

input the dashboard dictionary structure output the model name (e.g. ‘mgbgbl’)

tools.tools.modelstrip(name)[source]

strips numbers of external parameters at beginning of model name

tools.tools.multigroup_in_components(dashboard)[source]

input full dashboard output mask list,

1 where “model_guess” contains at least one component (dict) whose “pardicts” (list) contains a parameter dict with at least one “function_multi”:[string, string ..] key 0 otherwise
tools.tools.muvalid(string)[source]

parse function

CHECK WITH MUCOMPONENT, THAT USES A DIFFERENT SCHEME

accepted functions are RHS of agebraic expressions of parameters p[i], i=0…ntot

tools.tools.muvalue(lrun, string)[source]

Run suite fits:

muvalue returns the value for the nint-th parameter of the lrun-th run according to string (corresponding flag=’l’). Large parameter change across the run suite requires different migrad start guesses. Probably broken!

tools.tools.muvaluid(string)[source]

Run suite fits: muvaluid returns True/False * checks the syntax for string function corresponding to flag=’l’. Meant for pars displaying large changes across the run suite, requiring different migrad start guesses:

# string syntax: e.g. "0.2*3,2.*4,20."
# means that for the first 3 runs value = 0.2,
#            for the next 4 runs value = 2.0
#            from the 8th run on value = 20.0
tools.tools.muzeropad(runs, nzeros=4)[source]

runs is a string containing the run number nzeros the number of digit chars in the filename PSI bin: nzeros=4 ISIS nxs nzeros=8 returns the runs string with left zero padding to nzeros digits

tools.tools.name_of_model(model_components, model)[source]

check if model_components list of dictionaries correstponds to model

tools.tools.nextrun(datapath)[source]

assume datapath is path+fileprefix+runnumber+extension datafile is next run, runnumber incremented by one if datafile exists return next run, datafile else return runnumber and datapath

tools.tools.p2x(instring)[source]

replaces parameters e.g. p[2] with variable x2 in string returns substitude string and list of indices (ascii)

tools.tools.path_dialog(path, title)[source]
tools.tools.path_file_dialog(path, spec)[source]
tools.tools.plot_parameters(nsub, labels, fig=None)[source]

standard plot of fit parameters vs B,T (or X to be implemente) input

nsub<6 is the number of subplots labels is a dict of labels, e.g. {title:self.title, xlabel:’T [K]’, ylabels: [‘asym’,r’$lambda$’,r’$sigma$,…]} fig is the standard fig e.g self.fig_pars
output

the ax array on which to plot one dimensional (from top to bottom and again, for two columns) example

two asymmetry parameters are both plotfal=1 and are plotted in ax[0] a longitudinal lambda is plotflag=2 and is plotted in ax[1] … a transverse sigma is plotflag=n and is plotted in ax[n-1]
tools.tools.prevrun(datapath)[source]

assume datapath is path+fileprefix+runnumber+extension datafile is prev run, runnumber decremented by one if datafile exists return prev run, datafile else return runnumber and datapath

tools.tools.print_components(names, values, errors, maxlen)[source]
input: for a component
parameter names parameter values parameter errors
output:
string to print, e.g. “bl.A_fast 0.123(4) bl.λ_fast 12.3(4) bl.σ_fast 0(0)”
tools.tools.print_components_multirun(names, values, errors, maxlen)[source]
input: for a component
parameter names parameter values parameter errors
output:
strings to print, e.g. “A.fast λ.fast σ.fast” “0.123(4) 12.3(4) 0(0)”
tools.tools.ps(data, p0=0.0, p1=0.0, inv=False)[source]

Linear phase correction

Parameters

data : ndarray

Array of NMR data.

p0 : float

Zero order phase in degrees.

p1 : float

First order phase in degrees.

inv : bool, optional

True for inverse phase correction

Returns

ndata : ndarray

Phased NMR data.
tools.tools.rebin(x, y, strstp, pack, e=None)[source]
input:

x is 1D intensive (time) y [,e] are 1D, 2D or 3D intensive arrays to be rebinned pack > 1 is the rebinning factor, e.g it returns:

xr = array([x[k*pack:k*(pack+1)].sum()/pack for k in range(int(floor((stop-start)/pack)))])

strstp = [start,stop] is a list of slice indices

rebinning of x, y [,e] is done on the slice truncated to the approrpiate pack multiple, stopm
x[start:stopm], y[start:stopm], [e[start:stopm]]

use either:

xr,yr = rebin(x,y,strstp,pack)

or:

xr,yr,eyr = rebin(x,y,strstp,pack,ey) # the 5th is y error
tools.tools.rebin_decay(x, yf, yb, bf, bb, strstp, pack)[source]
input:

x is 1D intensive (time) yf, yb 1D, 2D, 3D extensive arrays to be rebinned bf, bb are scalars or arrays (see musuite.single_for_back_counts and musuite.single_multigroup_for_back_counts) pack > 1 is the rebinning factor, e.g it returns:

xr = array([x[k*pack:k*(pack+1)].sum()/pack for k in range(int(floor((stop-start)/pack)))]) yr = array([y[k*pack:k*(pack+1)].sum() for k in range(int(floor((stop-start)/pack)))])

strstp = [start,stop] is a list of slice indices

rebinning of x,y is done on the slice truncated to the approrpiate pack multiple, stopm
x[start:stopm], y[start:stopm]

use:

xr,yfr, ybr, bfr, bbr, yfmr, ybmr = rebin(x,yf,yb,bf,bb,yfm,ybm,strstp,pack)
tools.tools.results()[source]

generate a notebook with some results

tools.tools.run_shorthand(runstrings)[source]
write the runlist contained in runstrings (suite self.runs produced by derun)
i.e. a list of lists, with separate run numbers in string format, the inner ones to be added

in a compact string, with space separated notation e.g. ‘650:655,675,656:674’

tools.tools.safetry(string)[source]

Used by muvalid

tools.tools.scanms(y, n)[source]
tools.tools.set_bar(n, b)[source]

service to animate histograms e.g. in the fit tab

extracted from matplotlib animate histogram example

tools.tools.set_fig(num, nrow, ncol, title, **kwargs)[source]

num is figure number (static, to keep the same window) nrow, ncol number of subplots rows and columns kwargs is a dict of keys to pass to subplots as is initializes figures when they are first called or after accidental killing

tools.tools.set_key(string)[source]
input: the function string from the json or the mudash dashboard
e.g. that written in the json file as ‘function’:’p[0]*(0.5+1/pi*arctan(p[2])’
or typed into mudash text widget as ‘p[0]*(0.5+1/pi*arctan(p[2])’
output: key, a python method, such that in mumodel mucomponents _add_ the command
key(p) evaluates the formula the evaluation knows simple numpy functions, see the import in string code, below
tools.tools.shorten(path, subpath)[source]

shortens path e.g. path, subpath = ‘/home/myname/myfolder’, ‘/home/myname’

shart = ‘./myfolder’
tools.tools.signif(x, p)[source]

write x with p significant digits

tools.tools.spec_prec(a)[source]

format specifier precision:

0 for a > 1.0
1 for 1.0 > a > 0.1
2 for 0.1 > a > 0.01 etc.
tools.tools.step(x, a, n, dn, b)[source]
tools.tools.stringify_groups(groups)[source]

returns a unique string for many groups to use in json file name

tools.tools.thisrun(datapath)[source]

assume datapath is path+fileprefix+runnumber+extension datafile is present run if datafile exists returns path to datafile

tools.tools.tlog_exists(path, run, ndigits)[source]

check if tlog exists under various known filenames types

tools.tools.translate(nint, lmin, function_in)[source]
input:
nint: dashbord index, lmin: list of minuit indices replacement, one for each dashboard index, -1 is blanck function: single function string, of dashboard index nint, to be translated
output:
function_out: single translated function

Used in int2_method_key and min2int to replace parameter indices contained in function[nint] e.g.

p[0]*2+p[3]

by translate the internal parameter indices 0 and 3 (written according to the dashboard dict order) into the corresponding minuit parameter list indices, skipping shared parameters.

e.g. if parameter 1 is shared with parameter 0, the minuit parameter index 3 will be translated to 2 (skipping internal index 1)

tools.tools.translate_multirun(functions_in, n_locals, kloc, nruns)[source]
functions_in = [list of function strings],
for the model components of a single-run model (obtained from get_functions_in) where a “~”,”!” parameter dummy function has been redefined as ‘p[k]’ and k is their dash index

n_locals = number of user_local parameters kloc = index of first component first parameter

in the single run model (kloc-n_locals is the index of the first user_locals)

nruns = number of runs in the suite functions_out = [list of lists of function strings, indices of component & parameter],

with translated minuit indices outer list is components of the model, middle list is runs, inner list is component parameter functions

used in int2_multirun_user_method_key and int2_multirun_grad_method_key

tools.tools.translate_nint(nint, lmin, function)[source]

Used in int2_int and min2int to parse parameters contained in function[nint].value e.g.

p[4]*2+p[7]

and translate the internal parameter indices 4 and 7 (written according to the gui parameter list order) into the corresponding minuit parameter list indices, that skips shared and fixed parameters.

e.g. if parameter 6 is shared with parameter 4 and parameter 2 is fixed, the minuit parameter indices will be 3 instead of 4 (skipping internal index 2) and 5 instead of 7 (skipping both 2 and 6) Returns lmin[nint]

tools.tools.userlocals(dashboard)[source]
input:
full dashboard
output:
True is “userpardicts_local” in dashboard.keys
tools.tools.userpars(dashboard)[source]

checks if there are userpardicts in the fit dashboard alias of global type fit, of any kind (gg, gr, G) used by fit and plt switchyard

tools.tools.validmodel(model)[source]

checks valid simple name “almlmg”

tools.tools.value_error(v, e)[source]

returns a string of the format v(e)

tools.tools.write_csv(header, row, the_run, file_csv, filespec, scan=None)[source]
input :
header, the model specific csv header
to compare with that of the csv file

row, the line to be added to the csv file the_run, run instance (first one for added runs) file_csv, full path/filename to csv file filespec, ‘bin’, ‘mdu’ or ‘nsx’ scan, T, B or None

output:
two strings to write on console

writes onto csv finding the right line writes a new file if csv does not exist or is incompatible (writes ~ version)

mucomponents

Components for data fit with iminuit

musr2py

wrapper to the MuSR_td_PSI.cpp class