Fork me on GitHub

pyhrf.tools.misc module

class pyhrf.tools.misc.AnsiColorizer

Format strings with an ANSI escape sequence to encode color

BEGINC = '\x1b['
COLORS = {'blue': '94', 'green': '92', 'purple': '95', 'red': '91', 'yellow': '93'}
ENDC = '\x1b[0m'
disable()
enable()
no_tty_check()
tty_check()
pyhrf.tools.misc.Extract_TTP_whM_from_group(hrfs_pck_file, dt, model, Path_data, acq)

Extract TTP and whM from a group of hrfs whose values are saved in a .pck (size nb_subjects * nb_coeff_hrf)

pyhrf.tools.misc.Extract_TTP_whM_hrf(hrf, dt)

Extract TTP and whM from an hrf

pyhrf.tools.misc.PPMcalculus_jde(threshold_value, apost_mean_activ_fn, apost_var_activ_fn, apost_mean_inactiv_fn, apost_var_inactiv_fn, labels_activ_fn, labels_inactiv_fn, nrls_fn, mask_file, null_hyp=True)

Function to calculate the probability that the nrl in voxel j, condition m, is superior to a given hreshold_value Computation for all voxels Compute Tvalue according to null hypothesis

class pyhrf.tools.misc.PickleableStaticMethod(fn, cls=None)

Bases: object

class pyhrf.tools.misc.Pipeline(quantities)
THE_ROOT = 0
add_root(label)
checkGraph()

Check the rightness of the builded graph (acyclicity, uniqueness and no short-circuits)

detectCyclity(viewedNodes)
detectShortCircuit(curRoot, curDepth, depths)

Recursive method which detects and corrects short-circuits

get_func(f)
get_value(label)

Return the value associated with ‘label’

get_values()

Return all computed values. Perform a full update if not done yet.

init_dependencies(quantities)
removeShortCircuits(label, depths)
reportChange(rootLabel)

Trigger update of the sub graph starting at the given root

reprAllDeps()

Build a string representing the while graph : a concatenation of representations of all nodes (see reprDep)

reprDep(label)

Build a string representing all dependencies and dependers of the variable label. The returned string is in the form

       label
depee1 <-
depee2 <-
       -> deper1
       -> deper2
resolve()
save_graph_plot(image_filename, images=None)
setDepths(label, depths, curDepth)
update_all()
update_quantity(label, updated)
update_subgraph(root)
pyhrf.tools.misc.add_prefix(fn, prefix)

Add a prefix at the beginning of a file name.

>>> add_prefix('./my_file.txt', 'my_prefix_')
'./my_prefix_my_file.txt'
pyhrf.tools.misc.add_suffix(fn, suffix)

Add a suffix before file extension.

>>> add_suffix('./my_file.txt', '_my_suffix')
'./my_file_my_suffix.txt'
pyhrf.tools.misc.apply_to_leaves(tree, func, funcArgs=None, funcKwargs=None)

Apply function ‘func’ to all leaves in given ‘tree’ and return a new tree.

pyhrf.tools.misc.array_summary(a, precision=4)
pyhrf.tools.misc.assert_file_exists(fn)
pyhrf.tools.misc.assert_path_not_in_src(p)
pyhrf.tools.misc.attrs_to_string(attrs)
pyhrf.tools.misc.buildPolyMat(paramLFD, n, dt)
pyhrf.tools.misc.cache_exists(func, args=None, prefix=None, path='./', digest_code=False)
pyhrf.tools.misc.cache_filename(func, args=None, prefix=None, path='./', digest_code=False)
pyhrf.tools.misc.cached_eval(func, args=None, new=False, save=True, prefix=None, path='./', return_file=False, digest_code=False, gzip_mode='cmd')
pyhrf.tools.misc.calc_nc2D(a, b)
pyhrf.tools.misc.cartesian(*sequences)

Generate the “cartesian product” of all ‘sequences’. Each member of the product is a list containing an element taken from each original sequence.

Note: equivalent to itertools.product, which is at least 2x faster !!

pyhrf.tools.misc.cartesian_apply(varying_args, func, fixed_args=None, nb_parallel_procs=1, joblib_verbose=0)

Apply function func iteratively on the cartesian product of varying_args with fixed args fixed_args. Produce a tree (nested dicts) mapping arg values to the corresponding evaluation of function func

Parameters:
  • varying_args (OrderedDict) – a dictionary mapping argument names to a list of values. The Orderdict is used to keep track of argument order in the result. WARNING: all argument values must be hashable
  • func (function) – the function to be applied on the cartesian product of given arguments
  • fixed_args (dict) – arguments that are fixed (do not enter cartesian product)
Returns:

nested dicts – where each node is an argument value from varying args and each leaf is the result of the evaluation of the function. The order to the tree levels corresponds the order in the input OrderedDict of varying arguments.

Return type:

tree

Examples

>>> from pyhrf.tools import cartesian_apply
>>> from pyhrf.tools.backports import OrderedDict
>>> def foo(a,b,c): return a + b + c
>>> v_args = OrderedDict( [('a',[0,1]), ('b',[1,2])] )
>>> fixed_args = {'c': 3}
>>> cartesian_apply(v_args, foo, fixed_args) == { 0 : { 1:4, 2:5}, 1 : { 1:5, 2:6} }
True
pyhrf.tools.misc.cartesian_combine_args(varying_args, fixed_args=None)

Construct the cartesian product of varying_args and append fixed_args to it.

Parameters:
  • varying_args

    Specify varying arguments as a dict mapping arg names to iterables of arg values. e.g:

    {'my_arg1' : ['a','b','c'],
     'my_arg2' : [2, 5, 10]}
    
  • fixed_args

    Specify constant arguments as a dict mapping arg names to arg values. e.g:

    { 'my_arg3' : ['fixed_value'] }
    

Examples

>>> from pyhrf.tools import cartesian_combine_args
>>> vargs = {'my_arg1' : ['a','b','c'],'my_arg2' : [2, 5, 10],}
>>> fargs = { 'my_arg3' : 'fixed_value' }
>>> res = cartesian_combine_args(vargs, fargs)
>>> res ==         [{'my_arg1': 'a', 'my_arg2': 2, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'b', 'my_arg2': 2, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'c', 'my_arg2': 2, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'a', 'my_arg2': 5, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'b', 'my_arg2': 5, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'c', 'my_arg2': 5, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'a', 'my_arg2': 10, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'b', 'my_arg2': 10, 'my_arg3': 'fixed_value'},
...  {'my_arg1': 'c', 'my_arg2': 10, 'my_arg3': 'fixed_value'}]
True
pyhrf.tools.misc.cartesian_eval(func, varargs, fixedargs=None)
pyhrf.tools.misc.cartesian_params(**kwargs)
pyhrf.tools.misc.cartesian_test()
pyhrf.tools.misc.check_files_series(fseries, verbose=False)
pyhrf.tools.misc.closestsorted(a, val)
pyhrf.tools.misc.condense_series(numbers)
pyhrf.tools.misc.convex_hull_mask(mask)

Compute the convex hull of the positions defined by the given binary mask

Parameters:mask (-) – binary mask of positions to build the chull from
Returns:a numpy.ndarray binary mask of positions within the convex hull
pyhrf.tools.misc.crop_array(a, m=None, extension=0)

Return a sub array where as many zeros as possible are discarded Increase bounding box of mask by extension

pyhrf.tools.misc.cuboidPrinter(c)
pyhrf.tools.misc.describeRois(roiMask)
pyhrf.tools.misc.diagBlock(mats, rep=0)

Construct a diagonal block matrix from blocks which can be 1D or 2D arrays. 1D arrays are taken as column vectors. If ‘rep’ is a non null positive number then blocks are diagonaly ‘rep’ times

pyhrf.tools.misc.distance(c1, c2, coord_system=None)
pyhrf.tools.misc.do_if_nonexistent_file(*dargs, **kwargs)
pyhrf.tools.misc.extractRoiMask(nmask, roiId)
pyhrf.tools.misc.extract_file_series(files)

group all file names sharing a common prefix followed by a number, ie: <prefix><number><extension> Return a dictionnary with two levels (<tag>,<extension>), mapped to all corresponding series index found.

pyhrf.tools.misc.foo(*args, **kwargs)
pyhrf.tools.misc.format_duration(dt)
pyhrf.tools.misc.format_serie(istart, iend)
pyhrf.tools.misc.gaussian_blur(a, shape)
pyhrf.tools.misc.gaussian_kernel(shape)

Returns a normalized ND gauss kernel array for convolutions

pyhrf.tools.misc.get_2Dtable_string(val, rownames, colnames, precision=4, col_sep='|', line_end='', line_start='', outline_char=None)

Return a nice tabular string representation of a 2D numeric array #TODO : make colnames and rownames optional

pyhrf.tools.misc.get_cache_filename(args, path='./', prefix=None, gz=True)
pyhrf.tools.misc.get_leaf(element, branch)

Return the nested leaf element corresponding to all dictionnary keys in branch from element

pyhrf.tools.misc.group_file_series(series, group_rules=None)
pyhrf.tools.misc.has_ext(fn, ext)
pyhrf.tools.misc.hash_func_input(func, args, digest_code)
pyhrf.tools.misc.html_body(s)
pyhrf.tools.misc.html_cell(s, cell_type='d', attrs=None)
pyhrf.tools.misc.html_div(s, attrs=None)
pyhrf.tools.misc.html_doc(s)
pyhrf.tools.misc.html_head(s)
pyhrf.tools.misc.html_img(fn, attrs=None)
pyhrf.tools.misc.html_list_to_row(l, cell_types, attrs)
pyhrf.tools.misc.html_row(s)
pyhrf.tools.misc.html_style(s)
pyhrf.tools.misc.html_table(s, border=None)
pyhrf.tools.misc.icartesian_combine_args(varying_args, fixed_args=None)

Same as cartesian_combine_args but return an iterator over the list of argument combinations

pyhrf.tools.misc.inspect_default_args(args, defaults)
pyhrf.tools.misc.is_importable(module_name, func_name=None)

Return True if given module_name (str) is importable

pyhrf.tools.misc.map_dict(func, d)
pyhrf.tools.misc.montecarlo(datagen, festim, nbit=None)

Perform a Monte Carlo loop with data generator ‘datagen’ and estimation function ‘festim’. ‘datagen’ have to be iterable. ‘festim’ must return an object on which ** and + operators can be applied. If ‘nbit’ is provided then use it for the maximum iterations else loop until datagen stops.

pyhrf.tools.misc.my_func(**kwargs)
pyhrf.tools.misc.nc2DGrid(maxSize)
pyhrf.tools.misc.non_existent_canditate(f, start_idx=1)
pyhrf.tools.misc.non_existent_file(f)
pyhrf.tools.misc.now()
pyhrf.tools.misc.peelVolume3D(volume, backgroundLabel=0)
exception pyhrf.tools.misc.polyError(expression, message)

Bases: exceptions.Exception

pyhrf.tools.misc.polyFit(signal, tr=1.0, order=5)

Polynomial fit of signals. ‘signal’ is a 2D matrix with first axis being time and second being position. ‘tr’ is the time resolution (dt). ‘order’ is the order of the polynom. Return the orthogonal polynom basis matrix (P) and fitted coefficients (l), such that P.l yields fitted polynoms.

pyhrf.tools.misc.rebin(a, newshape)

Rebin an array to a new shape. Can be used to rebin a func image onto a anat image

pyhrf.tools.misc.replace_ext(fn, ext)
pyhrf.tools.misc.report_arrays_in_obj(o)
pyhrf.tools.misc.resampleSignal(s, osf)
pyhrf.tools.misc.resampleToGrid(x, y, xgrid)
pyhrf.tools.misc.rescale_values(a, v_min=0.0, v_max=1.0, axis=None)
pyhrf.tools.misc.root3(listCoeffs)
pyhrf.tools.misc.set_leaf(tree, branch, leaf, branch_classes=None)

Set the nested leaf element corresponding to all dictionnary keys defined in branch, within tree

pyhrf.tools.misc.stack_trees(trees, join_func=None)

Stack trees (python dictionnaries) with identical structures into one tree so that one leaf of the resulting tree is a list of the corresponding leaves across input trees. ‘trees’ is a list of dict

pyhrf.tools.misc.swap_layers(t, labels, l1, l2)

Create a new tree from t where layers labeled by l1 and l2 are swapped. labels contains the branch labels of t.

pyhrf.tools.misc.swapaxes(array, a1, a2)
pyhrf.tools.misc.time_diff_str(diff)
pyhrf.tools.misc.tree(branched_leaves)
pyhrf.tools.misc.treeBranches(tree, branch=None)
pyhrf.tools.misc.treeBranchesClasses(tree, branch=None)
pyhrf.tools.misc.tree_items(tree)
pyhrf.tools.misc.tree_leaves(tree)
pyhrf.tools.misc.tree_rearrange(t, oldlabels, newlabels)

Create a new tree from t where layers are rearranged following newlabels. oldlabels contains the branch labels of t.

pyhrf.tools.misc.undrift(signal, tr, order=5)

Remove the low frequency trend from ‘signal’ by a polynomial fit. Assume axis 3 of ‘signal’ is time.

pyhrf.tools.misc.unstack_trees(tree)

Return a list of tree from a tree where leaves are all lists with the same number of items