tramway.helper package

As of version 0.4.7, this package is frozen and is only affected by minor fixes.

tramway.helper.roi module

class tramway.helper.roi.SupportRegions(region_label=None, update_metadata=None, verbose=True)

Bases: object

A support region can be either a region of interest or the union of regions of interest. Major processing steps such as tessellation and inference may operate on support regions so that a region of interest simply acts as a window.

This class offers a base implementation for UnitRegions and GroupedRegions.

class tramway.helper.roi.UnitRegions(*args, **kwargs)

Bases: tramway.helper.roi.SupportRegions

Regions of interest are considered separately, independently of whether they overlap or not.

region_to_units(r)

Returns a dict with a single key and single-element list value.

For compatibility with : class:GroupedRegions.

class tramway.helper.roi.GroupedRegions(region_label=None, update_metadata=None, verbose=True)

Bases: tramway.helper.roi.SupportRegions

Overlapping regions of interest are pooled together and form a unique support region.

Pooling disregards which collection a ROI pertains to.

class tramway.helper.roi.RoiCollection(roi, label=None, regions=None)

Bases: object

cell_plot(i, analysis_tree, decorate=True, **kwargs)

plots the Partition for unit roi i.

get_cells(i, analysis_tree)

returns the Partition object for unit roi i.

get_map(i, analysis_tree, map_label, full=False)

returns the Map object for unit roi i.

get_tessellation(i, analysis_tree)

returns the Tessellation object for unit roi i, together with a boolean array so that the k-th element is True if microdomain k lies within roi i.

map_plot(i, analysis_tree, map_label, decorate=True, **kwargs)

plots the Maps for unit roi i.

class tramway.helper.roi.RoiCollections(group_overlapping_roi=False, rwa_file=None, autosave=True, metadata=None, verbose=True, _bw_comp=False)

Bases: tramway.helper.base.AutosaveCapable

collection of all collections of roi.

manages the analysis tree for the spt data. Modifications can be automatically saved into an .rwa file.

single_roi_label(i, collection_label=None)

for figure titles

class tramway.helper.roi.RoiHelper(input_data, roi=None, meta_label='all %Sroi', meta_label_sep=' ', rwa_file=None, autosave=True, verbose=True, group_overlapping_roi=True, _bw_comp=False)

Bases: tramway.helper.base.Helper

maintains an extra data artefact in the .rwa file to store/load roi definitions.

tramway.helper.tessellation module

tramway.helper.tessellation.cell_plot(cells, xy_layer=None, output_file=None, fig_format=None, show=None, verbose=False, figsize=None, dpi=None, location_count_hist=False, cell_dist_hist=False, location_dist_hist=False, aspect=None, delaunay=None, locations={}, voronoi=None, colors=None, title=None, cell_indices=None, segment=None, label=None, input_label=None, num=None, **kwargs)

Partition plots.

Plots a spatial representation of the tessellation and partition if data are 2D.

Parameters:
  • cells (str or Partition or tramway.core.analyses.base.Analyses) – Path to a .rwa file or Partition instance or analysis tree; files and analysis trees may require label/input_label to be defined.
  • xy_layer ({None, 'delaunay', 'voronoi'}) – Overlay Delaunay or Voronoi graph over the data points. For 2D data only. Deprecated! Please use delaunay and voronoi arguments instead.
  • output_file (str) – Path to a file in which the figure will be saved. If cells is a path and fig_format is defined, output_file is automatically set.
  • fig_format (str) – Any image format supported by matplotlib.pyplot.savefig().
  • show (bool or str) – Makes cell_plot show the figure(s) which is the default behavior if and only if the figures are not saved. If show='draw', draw() is called instead of show(). To maintain the current default behaviour in the future, set show to True from now on.
  • verbose (bool) – Verbose output.
  • figsize (pair of floats) – Passed to matplotlib.pyplot.figure(). Applies only to the spatial representation figure.
  • dpi (int) – Passed to matplotlib.pyplot.savefig(). Applies only to the spatial representation figure.
  • location_count_hist (bool) – Plot a histogram of point counts (per cell). If the figure is saved, the corresponding file will have sub-extension .hpc; deprecated.
  • cell_dist_hist (bool) – Plot a histogram of distances between neighbour centroids. If the figure is saved, the corresponding file will have sub-extension .hcd; deprecated.
  • location_dist_hist (bool) – Plot a histogram of distances between points from neighbour cells. If the figure is saved, the corresponding file will have sub-extension .hpd; deprecated.
  • aspect (str) – Aspect ratio. Can be ‘equal’.
  • locations (dict) – Keyword arguments to plot_points().
  • delaunay (bool or dict) – Overlay Delaunay graph. If dict, keyword arguments to plot_delaunay().
  • voronoi (bool or dict) – Overlay Voronoi graph (default: True). If dict, keyword arguments to plot_voronoi().
  • cell_indices (bool or dict) – True or keyworded arguments; plot cell indices instead of centroids.
  • label/input_label (int or str or list) – If cells is a filepath or an analysis tree, label of the analysis instance.
  • segment (int) – Segment index; if multiple time segments were defined, show only one segment.
  • num (int) – Figure number. Default: None (new figure for each call).

Notes

See also tramway.plot.mesh.

tramway.helper.tessellation.tessellate(xyt_data, method='gwr', output_file=None, verbose=False, scaling=False, time_scale=None, knn=None, radius=None, distance=None, ref_distance=None, rel_min_distance=None, rel_avg_distance=None, rel_max_distance=None, min_location_count=None, avg_location_count=None, max_location_count=None, rel_max_size=None, rel_max_volume=None, time_window_duration=None, time_window_shift=None, time_window_options=None, enable_time_regularization=False, time_knn=None, label=None, output_label=None, comment=None, input_label=None, inplace=False, overwrite=None, return_analyses=False, load_options=None, tessellation_options=None, partition_options=None, save_options=None, force=None, **kwargs)

Tessellation from points series and partitioning.

This helper routine is a high-level interface to the various tessellation techniques implemented in TRamWAy.

In addition to knn, radius, filter and metric, arguments with prefix strict_ in their name apply to the partitioning step only, while the others apply to the tessellation step.

rel_max_size and rel_max_volume are notable exceptions in that they currently apply to the partitioning step whereas they should conceptually apply to the tessellation step instead. This may change in a future version.

Reassignment options can be provided using the reassignment_options dictionnary or keyworded arguments which names begin with ‘reassign_’ or ‘reassignment_’.

Parameters:
  • xyt_data (str or pandas.DataFrame) – Path to a .trxyt or .rwa file or raw data in the shape of pandas.DataFrame.
  • method (str) – Tessellation method or plugin name. See for example RandomMesh (’random’), RegularMesh (’grid’), HexagonalMesh (’hexagon’), KDTreeMesh (’kdtree’), KMeansMesh (’kmeans’) and GasMesh (’gas’ or ‘gwr’).
  • output_file (str) – Path to a .rwa file. The resulting tessellation and data partition will be stored in this file. If xyt_data is a path to a file and output_file is not defined, then output_file will be adapted from xyt_data with extension .rwa and possibly overwrite the input file.
  • verbose (bool or int) – Verbose output.
  • scaling (bool or str) – Normalization of the data. Any of ‘unitrange’, ‘whiten’ or other methods defined in tramway.core.scaler.
  • time_scale (bool or float) – If this argument is defined and intepretable as True, the time axis is scaled by this factor and used as a space variable for the tessellation (2D+T or 3D+T, for example). This is equivalent to manually scaling the t column and passing scaling=True.
  • knn (int or pair of ints) – After growing the tessellation, a minimum and maximum numbers of nearest neighbours of each cell center can be used instead of the entire cell population. Let us denote min_nn, max_nn = knn. Any of min_nn and max_nn can be None. If a single int is supplied instead of a pair, then knn becomes min_nn. min_nn enables cell overlap and any point may be associated with several cells. See also cell_index().
  • radius (float) – After growing the tessellation as a set of centroids, a cell will consist of the locations within this distance from the centroid. See also cell_index().
  • distance/ref_distance (float) – Supposed to be the average translocation distance. Can be modified so that the cells are smaller or larger.
  • rel_min_distance (float) – Multiplies with ref_distance to define the minimum inter-cell distance.
  • rel_avg_distance (float) – Multiplies with ref_distance to define an upper on the average inter-cell distance.
  • rel_max_distance (float) – Multiplies with ref_distance to define the maximum inter-cell distance.
  • min_location_count (int) – Minimum number of points per cell. Depending on the method, can be strictly enforced or regarded as a recommendation.
  • avg_location_count (int) – Average number of points per cell. For non-plugin method, per default, it is set to four times min_location_count.
  • max_location_count (int) – Maximum number of points per cell. This is used by kdtree and gwr.
  • rel_max_size (float) – Maximum cell diameter as a number of ref_distance. Diameter (or size) is estimated as twice the distance between the center of cell and the nearest vertex. Cells of excess size are ignored so as the associated locations.
  • rel_max_volume (float) – Maximum cell volume (or surface area in 2D) as a number of ref_distance. Cells of excess volume are ignored so as the associated locations.
  • strict_min_location_count/min_n (int) – Minimum number of points per cell in the eventual partition. Cells with insufficient points are ignored so as the associated locations.
  • strict_rel_max_size (float) – Maximum cell diameter as a number of ref_distance. Diameter (or size) is estimated as the maximum distance between any pair of locations in the cell. Cells of excess size are ignored so as the associated locations.
  • time_window_duration (float) – Window duration in seconds (or frames with time_window_options=dict(frames=True)). This time windowing combines with any other spatial tessellation method. To use the window plugin only, use method=window and its duration and shift arguments instead. See also the window plugin.
  • time_window_shift (float) – Window shift in seconds (or frames with time_window_options=dict(frames=True)). Default is no overlap, i.e. time_window_shift=time_window_duration. See also the window plugin.
  • time_window_options (dict) – Extra arguments for time windowing. See also the window plugin.
  • enable_time_regularization (bool) – Equivalent to time_window_options['time_dimension'] = enable_time_regularization.
  • time_knn (int or pair of ints) – min_nn minimum number of nearest “neighbours” of the time segment center, or (min_nn, max_nn) minimum and maximum numbers of nearest neighbours in time. See also cell_index().
  • input_label (str) – Label for the input tessellation for nesting tessellations.
  • label/output_label (int or str) – Label for the resulting analysis instance.
  • inplace (bool) – If True, label/output_label/input_label are exclusive, they all define a same analysis and the resulting analysis replaces the input analysis.
  • comment (str) – Description message for the resulting analysis.
  • overwrite (bool) – if an implicit output file already exists, overwrite it.
  • return_analyses (bool) – Return a Analyses object instead of the default Partition output.
  • load_options (dict) – Pass extra keyword arguments to load_xyt() if called.
  • tessellation_options (dict) – Pass explicit keyword arguments to the __init__ function of the tessellation class as well as to the tessellate() method, and ignore the extra input arguments.
  • partition_options (dict) – Pass explicit keyword arguments to the cell_index() method and ignore the extra input arguments.
  • reassignment_options (dict) – allowed keys are: count_threshold (int): minimum number of points for a cell not to be deleted; update_centroids (bool or int): if evaluates to True, cell centers are updated as the centers of mass for the assigned points, and then the new cells are checked again for count_threshold and so on; the number of iterations is not limited by default, and can be set passing an integer value instead of True.
  • save_options (dict) – Pass extra keyword arguments to save_rwa() if called.
Returns:

A partition of the data with its

tessellation attribute set.

Return type:

tramway.tessellation.base.Partition

Apart from the parameters defined above, extra input arguments are admitted and may be passed to the initializer of the selected tessellation method as well as to the tessellate() and cell_index() methods.

See the individual documentation of these methods for more information.

tramway.helper.tessellation.tessellate0(xyt_data, method='gwr', output_file=None, verbose=False, scaling=False, time_scale=None, knn=None, radius=None, distance=None, ref_distance=None, rel_min_distance=None, rel_avg_distance=None, rel_max_distance=None, min_location_count=None, avg_location_count=None, max_location_count=None, rel_max_size=None, rel_max_volume=None, time_window_duration=None, time_window_shift=None, time_window_options=None, label=None, output_label=None, comment=None, input_label=None, inplace=False, force=None, return_analyses=False, load_options=None, tessellation_options=None, partition_options=None, save_options=None, **kwargs)

Tessellation from points series and partitioning.

This helper routine is a high-level interface to the various tessellation techniques implemented in TRamWAy.

In addition to knn, radius, filter and metric, arguments with prefix strict_ in their name apply to the partitioning step only, while the others apply to the tessellation step.

rel_max_size and rel_max_volume are notable exceptions in that they currently apply to the partitioning step whereas they should conceptually apply to the tessellation step instead. This may change in a future version.

Parameters:
  • xyt_data (str or pandas.DataFrame) – Path to a .trxyt or .rwa file or raw data in the shape of pandas.DataFrame.
  • method (str) – Tessellation method or plugin name. See for example RandomMesh (’random’), RegularMesh (’grid’), HexagonalMesh (’hexagon’), KDTreeMesh (’kdtree’), KMeansMesh (’kmeans’) and GasMesh (’gas’ or ‘gwr’).
  • output_file (str) – Path to a .rwa file. The resulting tessellation and data partition will be stored in this file. If xyt_data is a path to a file and output_file is not defined, then output_file will be adapted from xyt_data with extension .rwa and possibly overwrite the input file.
  • verbose (bool or int) – Verbose output.
  • scaling (bool or str) – Normalization of the data. Any of ‘unitrange’, ‘whiten’ or other methods defined in tramway.core.scaler.
  • time_scale (bool or float) – If this argument is defined and intepretable as True, the time axis is scaled by this factor and used as a space variable for the tessellation (2D+T or 3D+T, for example). This is equivalent to manually scaling the t column and passing scaling=True.
  • knn (int or pair of ints) – After growing the tessellation, a minimum and maximum numbers of nearest neighbours of each cell center can be used instead of the entire cell population. Let us denote min_nn, max_nn = knn. Any of min_nn and max_nn can be None. If a single int is supplied instead of a pair, then knn becomes min_nn. min_nn enables cell overlap and any point may be associated with several cells. See also cell_index().
  • radius (float) – After growing the tessellation as a set of centroids, a cell will consist of the locations within this distance from the centroid. See also cell_index().
  • distance/ref_distance (float) – Supposed to be the average translocation distance. Can be modified so that the cells are smaller or larger.
  • rel_min_distance (float) – Multiplies with ref_distance to define the minimum inter-cell distance.
  • rel_avg_distance (float) – Multiplies with ref_distance to define an upper on the average inter-cell distance.
  • rel_max_distance (float) – Multiplies with ref_distance to define the maximum inter-cell distance.
  • min_location_count (int) – Minimum number of points per cell. Depending on the method, can be strictly enforced or regarded as a recommendation.
  • avg_location_count (int) – Average number of points per cell. For non-plugin method, per default, it is set to four times min_location_count.
  • max_location_count (int) – Maximum number of points per cell. This is used by kdtree and gwr.
  • rel_max_size (float) – Maximum cell diameter as a number of ref_distance. Diameter (or size) is estimated as twice the distance between the center of cell and the nearest vertex. Cells of excess size are ignored so as the associated locations.
  • rel_max_volume (float) – Maximum cell volume (or surface area in 2D) as a number of ref_distance. Cells of excess volume are ignored so as the associated locations.
  • strict_min_location_count (int) – Minimum number of points per cell in the eventual partition. Cells with insufficient points are ignored so as the associated locations.
  • strict_rel_max_size (float) – Maximum cell diameter as a number of ref_distance. Diameter (or size) is estimated as the maximum distance between any pair of locations in the cell. Cells of excess size are ignored so as the associated locations.
  • time_window_duration (float) – Window duration in seconds (or frames with time_window_options=dict(frames=True)). This time windowing combines with any other spatial tessellation method. To use the window plugin only, use method=window and its duration and shift arguments instead. See also the window plugin.
  • time_window_shift (float) – Window shift in seconds (or frames with time_window_options=dict(frames=True)). Default is no overlap, i.e. time_window_shift=time_window_duration. See also the window plugin.
  • time_window_options (dict) – Extra arguments for time windowing. See also the window plugin.
  • input_label (str) – Label for the input tessellation for nesting tessellations.
  • label/output_label (int or str) – Label for the resulting analysis instance.
  • inplace (bool) – If True, label/output_label/input_label are exclusive, they all define a same analysis and the resulting analysis replaces the input analysis.
  • comment (str) – Description message for the resulting analysis.
  • return_analyses (bool) – Return a Analyses object instead of the default Partition output.
  • load_options (dict) – Pass extra keyword arguments to load_xyt() if called.
  • tessellation_options (dict) – Pass explicit keyword arguments to the __init__ function of the tessellation class as well as to the tessellate() method, and ignore the extra input arguments.
  • partition_options (dict) – Pass explicit keyword arguments to the cell_index() method and ignore the extra input arguments.
  • save_options (dict) – Pass extra keyword arguments to save_rwa() if called.
Returns:

A partition of the data with its

tessellation attribute set.

Return type:

tramway.tessellation.base.Partition

Apart from the parameters defined above, extra input arguments are admitted and may be passed to the initializer of the selected tessellation method as well as to the tessellate() and cell_index() methods.

See the individual documentation of these methods for more information.

tramway.helper.tessellation.tessellate1(xyt_data, method='gwr', output_file=None, verbose=False, scaling=False, time_scale=None, knn=None, radius=None, distance=None, ref_distance=None, rel_min_distance=None, rel_avg_distance=None, rel_max_distance=None, min_location_count=None, avg_location_count=None, max_location_count=None, rel_max_size=None, rel_max_volume=None, time_window_duration=None, time_window_shift=None, time_window_options=None, enable_time_regularization=False, time_knn=None, label=None, output_label=None, comment=None, input_label=None, inplace=False, overwrite=None, return_analyses=False, load_options=None, tessellation_options=None, partition_options=None, save_options=None, force=None, **kwargs)

Tessellation from points series and partitioning.

This helper routine is a high-level interface to the various tessellation techniques implemented in TRamWAy.

In addition to knn, radius, filter and metric, arguments with prefix strict_ in their name apply to the partitioning step only, while the others apply to the tessellation step.

rel_max_size and rel_max_volume are notable exceptions in that they currently apply to the partitioning step whereas they should conceptually apply to the tessellation step instead. This may change in a future version.

Reassignment options can be provided using the reassignment_options dictionnary or keyworded arguments which names begin with ‘reassign_’ or ‘reassignment_’.

Parameters:
  • xyt_data (str or pandas.DataFrame) – Path to a .trxyt or .rwa file or raw data in the shape of pandas.DataFrame.
  • method (str) – Tessellation method or plugin name. See for example RandomMesh (’random’), RegularMesh (’grid’), HexagonalMesh (’hexagon’), KDTreeMesh (’kdtree’), KMeansMesh (’kmeans’) and GasMesh (’gas’ or ‘gwr’).
  • output_file (str) – Path to a .rwa file. The resulting tessellation and data partition will be stored in this file. If xyt_data is a path to a file and output_file is not defined, then output_file will be adapted from xyt_data with extension .rwa and possibly overwrite the input file.
  • verbose (bool or int) – Verbose output.
  • scaling (bool or str) – Normalization of the data. Any of ‘unitrange’, ‘whiten’ or other methods defined in tramway.core.scaler.
  • time_scale (bool or float) – If this argument is defined and intepretable as True, the time axis is scaled by this factor and used as a space variable for the tessellation (2D+T or 3D+T, for example). This is equivalent to manually scaling the t column and passing scaling=True.
  • knn (int or pair of ints) – After growing the tessellation, a minimum and maximum numbers of nearest neighbours of each cell center can be used instead of the entire cell population. Let us denote min_nn, max_nn = knn. Any of min_nn and max_nn can be None. If a single int is supplied instead of a pair, then knn becomes min_nn. min_nn enables cell overlap and any point may be associated with several cells. See also cell_index().
  • radius (float) – After growing the tessellation as a set of centroids, a cell will consist of the locations within this distance from the centroid. See also cell_index().
  • distance/ref_distance (float) – Supposed to be the average translocation distance. Can be modified so that the cells are smaller or larger.
  • rel_min_distance (float) – Multiplies with ref_distance to define the minimum inter-cell distance.
  • rel_avg_distance (float) – Multiplies with ref_distance to define an upper on the average inter-cell distance.
  • rel_max_distance (float) – Multiplies with ref_distance to define the maximum inter-cell distance.
  • min_location_count (int) – Minimum number of points per cell. Depending on the method, can be strictly enforced or regarded as a recommendation.
  • avg_location_count (int) – Average number of points per cell. For non-plugin method, per default, it is set to four times min_location_count.
  • max_location_count (int) – Maximum number of points per cell. This is used by kdtree and gwr.
  • rel_max_size (float) – Maximum cell diameter as a number of ref_distance. Diameter (or size) is estimated as twice the distance between the center of cell and the nearest vertex. Cells of excess size are ignored so as the associated locations.
  • rel_max_volume (float) – Maximum cell volume (or surface area in 2D) as a number of ref_distance. Cells of excess volume are ignored so as the associated locations.
  • strict_min_location_count/min_n (int) – Minimum number of points per cell in the eventual partition. Cells with insufficient points are ignored so as the associated locations.
  • strict_rel_max_size (float) – Maximum cell diameter as a number of ref_distance. Diameter (or size) is estimated as the maximum distance between any pair of locations in the cell. Cells of excess size are ignored so as the associated locations.
  • time_window_duration (float) – Window duration in seconds (or frames with time_window_options=dict(frames=True)). This time windowing combines with any other spatial tessellation method. To use the window plugin only, use method=window and its duration and shift arguments instead. See also the window plugin.
  • time_window_shift (float) – Window shift in seconds (or frames with time_window_options=dict(frames=True)). Default is no overlap, i.e. time_window_shift=time_window_duration. See also the window plugin.
  • time_window_options (dict) – Extra arguments for time windowing. See also the window plugin.
  • enable_time_regularization (bool) – Equivalent to time_window_options['time_dimension'] = enable_time_regularization.
  • time_knn (int or pair of ints) – min_nn minimum number of nearest “neighbours” of the time segment center, or (min_nn, max_nn) minimum and maximum numbers of nearest neighbours in time. See also cell_index().
  • input_label (str) – Label for the input tessellation for nesting tessellations.
  • label/output_label (int or str) – Label for the resulting analysis instance.
  • inplace (bool) – If True, label/output_label/input_label are exclusive, they all define a same analysis and the resulting analysis replaces the input analysis.
  • comment (str) – Description message for the resulting analysis.
  • overwrite (bool) – if an implicit output file already exists, overwrite it.
  • return_analyses (bool) – Return a Analyses object instead of the default Partition output.
  • load_options (dict) – Pass extra keyword arguments to load_xyt() if called.
  • tessellation_options (dict) – Pass explicit keyword arguments to the __init__ function of the tessellation class as well as to the tessellate() method, and ignore the extra input arguments.
  • partition_options (dict) – Pass explicit keyword arguments to the cell_index() method and ignore the extra input arguments.
  • reassignment_options (dict) – allowed keys are: count_threshold (int): minimum number of points for a cell not to be deleted; update_centroids (bool or int): if evaluates to True, cell centers are updated as the centers of mass for the assigned points, and then the new cells are checked again for count_threshold and so on; the number of iterations is not limited by default, and can be set passing an integer value instead of True.
  • save_options (dict) – Pass extra keyword arguments to save_rwa() if called.
Returns:

A partition of the data with its

tessellation attribute set.

Return type:

tramway.tessellation.base.Partition

Apart from the parameters defined above, extra input arguments are admitted and may be passed to the initializer of the selected tessellation method as well as to the tessellate() and cell_index() methods.

See the individual documentation of these methods for more information.

tramway.helper.inference module

tramway.helper.inference.infer(cells, mode='degraded.d', output_file=None, partition={}, verbose=False, localization_error=None, diffusivity_prior=None, potential_prior=None, jeffreys_prior=None, max_cell_count=None, dilation=None, worker_count=None, min_diffusivity=None, store_distributed=False, new_cell=None, new_group=None, constructor=None, include_empty_cells=False, cell_sampling=None, merge_threshold_count=False, grad=None, rgrad=None, input_label=None, output_label=None, comment=None, return_cells=None, profile=None, overwrite=None, inplace=False, priorD=None, priorV=None, force=None, **kwargs)

Inference helper.

Parameters:
  • cells (str or Partition or tramway.core.analyses.base.Analyses) – data partition or path to partition file
  • mode (str or callable) – plugin name; see for example d ('d'), df ('df'), dd ('dd'), dv ('dv'); can be also a function suitable for run()
  • output_file (str) – desired path for the output map file
  • verbose (bool or int) – verbosity level
  • localization_error/sigma (float) – localization error (see also sigma2)
  • diffusivity_prior/diffusion_prior (float) – hyperparameter of the prior on the diffusivity/diffusion
  • potential_prior (float) – hyperparameter of the prior on the potential energy
  • jeffreys_prior (float) – Jeffreys’ prior
  • max_cell_count (int) – if defined, divide the mesh into convex subsets of cells
  • dilation (int) – overlap of side cells if max_cell_count is defined
  • worker_count (int) – number of parallel processes to be spawned
  • min_diffusivity (float) – (possibly negative) lower bound on local diffusivities
  • store_distributed (bool) – store the Distributed object in the map file
  • new_cell (callable) – see also distributed()
  • new_group (callable) – see also distributed()
  • constructor (callable) – deprecated; see also distributed(); please use new_group instead
  • include_empty_cells (bool) – do not discard cells with no (trans-)locations
  • cell_sampling (str) – either None, 'individual', 'group' or 'connected'; may ignore max_cell_count and dilation
  • merge_threshold_count (int) – Merge cells that are have a number of (trans-)locations lower than the number specified; each smaller cell is merged together with the nearest large-enough neighbour cell.
  • grad (callable or str) – spatial gradient function; admits a callable (see grad()) or any of ‘grad1’, ‘gradn
  • rgrad (None or 'delta' or 'delta1') – alternative space/time “gradient” implementation for the regularization priors; if defined, inference modes that would otherwise use grad() will use local_variation() instead
  • input_label (list) – label path to the input Tessellation object in cells if the latter is an Analyses or filepath
  • output_label (str) – label for the resulting analysis instance
  • comment (str) – description message for the resulting analysis
  • return_cells (bool) – return a tuple with a Partition object as extra element
  • profile (bool or str) – profile each child job if any; if str, dump the output stats into .prof files; if tuple, print a report with print_stats() and tuple elements as input arguments.
  • overwrite (bool) – if an implicit output file already exists, overwrite it.
  • inplace (bool) – replace the input analysis by the output one.
  • snr_extensions (bool) – add snr extensions for Bayes factor calculation.
Returns:

Return type:

Maps or pandas.DataFrame or tuple

priorD and priorV are legacy arguments. They are deprecated and diffusivity_prior/diffusion_prior and potential_prior respectively should be used instead.

tramway.helper.inference.infer0(cells, mode='D', output_file=None, partition={}, verbose=False, localization_error=None, diffusivity_prior=None, potential_prior=None, jeffreys_prior=None, max_cell_count=None, dilation=None, worker_count=None, min_diffusivity=None, store_distributed=False, new_cell=None, new_group=None, constructor=None, cell_sampling=None, merge_threshold_count=False, grad=None, priorD=None, priorV=None, input_label=None, output_label=None, comment=None, return_cells=None, profile=None, force=False, **kwargs)

Inference helper.

Parameters:
  • cells (str or Partition or tramway.core.analyses.base.Analyses) – data partition or path to partition file
  • mode (str or callable) – plugin name; see for example d ('d'), df ('df'), dd ('dd'), dv ('dv'); can be also a function suitable for run()
  • output_file (str) – desired path for the output map file
  • partition (dict) – keyword arguments for find_partition() if cells is a path; deprecated
  • verbose (bool or int) – verbosity level
  • localization_error (float) – localization error
  • diffusivity_prior (float) – prior diffusivity
  • potential_prior (float) – prior potential
  • jeffreys_prior (float) – Jeffreys’ prior
  • max_cell_count (int) – if defined, divide the mesh into convex subsets of cells
  • dilation (int) – overlap of side cells if max_cell_count is defined
  • worker_count (int) – number of parallel processes to be spawned
  • min_diffusivity (float) – (possibly negative) lower bound on local diffusivities
  • store_distributed (bool) – store the Distributed object in the map file
  • new_cell (callable) – see also distributed()
  • new_group (callable) – see also distributed()
  • constructor (callable) – deprecated; see also distributed(); please use new_group instead
  • cell_sampling (str) – either None, 'individual', 'group' or 'connected'; may ignore max_cell_count and dilation
  • merge_threshold_count (int) – Merge cells that are have a number of (trans-)locations lower than the number specified; each smaller cell is merged together with the nearest large-enough neighbour cell.
  • grad (callable or str) – spatial gradient function; admits a callable (see grad()) or any of ‘grad1’, ‘gradn
  • input_label (list) – label path to the input Tessellation object in cells if the latter is an Analyses or filepath
  • output_label (str) – label for the resulting analysis instance
  • comment (str) – description message for the resulting analysis
  • return_cells (bool) – return a tuple with a Partition object as extra element
  • profile (bool or str) – profile each child job if any; if str, dump the output stats into .prof files; if tuple, print a report with print_stats() and tuple elements as input arguments.
Returns:

Return type:

Maps or pandas.DataFrame or tuple

priorD and priorV are legacy arguments. They are deprecated and diffusivity_prior and potential_prior should be used instead respectively.

tramway.helper.inference.infer1(cells, mode='degraded.d', output_file=None, partition={}, verbose=False, localization_error=None, diffusivity_prior=None, potential_prior=None, jeffreys_prior=None, max_cell_count=None, dilation=None, worker_count=None, min_diffusivity=None, store_distributed=False, new_cell=None, new_group=None, constructor=None, include_empty_cells=False, cell_sampling=None, merge_threshold_count=False, grad=None, rgrad=None, input_label=None, output_label=None, comment=None, return_cells=None, profile=None, overwrite=None, inplace=False, priorD=None, priorV=None, force=None, **kwargs)

Inference helper.

Parameters:
  • cells (str or Partition or tramway.core.analyses.base.Analyses) – data partition or path to partition file
  • mode (str or callable) – plugin name; see for example d ('d'), df ('df'), dd ('dd'), dv ('dv'); can be also a function suitable for run()
  • output_file (str) – desired path for the output map file
  • verbose (bool or int) – verbosity level
  • localization_error/sigma (float) – localization error (see also sigma2)
  • diffusivity_prior/diffusion_prior (float) – hyperparameter of the prior on the diffusivity/diffusion
  • potential_prior (float) – hyperparameter of the prior on the potential energy
  • jeffreys_prior (float) – Jeffreys’ prior
  • max_cell_count (int) – if defined, divide the mesh into convex subsets of cells
  • dilation (int) – overlap of side cells if max_cell_count is defined
  • worker_count (int) – number of parallel processes to be spawned
  • min_diffusivity (float) – (possibly negative) lower bound on local diffusivities
  • store_distributed (bool) – store the Distributed object in the map file
  • new_cell (callable) – see also distributed()
  • new_group (callable) – see also distributed()
  • constructor (callable) – deprecated; see also distributed(); please use new_group instead
  • include_empty_cells (bool) – do not discard cells with no (trans-)locations
  • cell_sampling (str) – either None, 'individual', 'group' or 'connected'; may ignore max_cell_count and dilation
  • merge_threshold_count (int) – Merge cells that are have a number of (trans-)locations lower than the number specified; each smaller cell is merged together with the nearest large-enough neighbour cell.
  • grad (callable or str) – spatial gradient function; admits a callable (see grad()) or any of ‘grad1’, ‘gradn
  • rgrad (None or 'delta' or 'delta1') – alternative space/time “gradient” implementation for the regularization priors; if defined, inference modes that would otherwise use grad() will use local_variation() instead
  • input_label (list) – label path to the input Tessellation object in cells if the latter is an Analyses or filepath
  • output_label (str) – label for the resulting analysis instance
  • comment (str) – description message for the resulting analysis
  • return_cells (bool) – return a tuple with a Partition object as extra element
  • profile (bool or str) – profile each child job if any; if str, dump the output stats into .prof files; if tuple, print a report with print_stats() and tuple elements as input arguments.
  • overwrite (bool) – if an implicit output file already exists, overwrite it.
  • inplace (bool) – replace the input analysis by the output one.
  • snr_extensions (bool) – add snr extensions for Bayes factor calculation.
Returns:

Return type:

Maps or pandas.DataFrame or tuple

priorD and priorV are legacy arguments. They are deprecated and diffusivity_prior/diffusion_prior and potential_prior respectively should be used instead.

tramway.helper.inference.map_plot(maps, cells=None, clip=None, output_file=None, fig_format=None, figsize=None, dpi=None, aspect=None, show=None, verbose=False, alpha=None, point_style=None, feature=None, variable=None, segment=None, label=None, input_label=None, mode=None, title=True, inferencemap=False, use_bokeh=None, **kwargs)

Plot scalar/vector 2D maps.

For consistency with InferenceMAP, the effective potential is showed in \(µm^{-1}\) while – using unit='std' – the colorbar mentions \(k_{B}T\), whereas no conversion factor is applied.

Parameters:
  • maps (str or tramway.core.analyses.base.Analyses or pandas.DataFrame or Maps) – maps as a path to a rwa map file, an analysis tree, a dataframe or a Maps; filepaths and analysis trees may require label (or equivalently input_label) to be defined; dataframes and encapsulated maps require cells to be defined
  • cells (Partition or Tessellation or Distributed) – mesh with optional partition
  • clip (float) – clips map values by absolute values; if clip < 1, it is the quantile at which to clip absolute values of the map; otherwise it defines: threshold = median + clip * (third_quartile - first_quartile)
  • output_file (str) – path to output file
  • fig_format (str) – for example ‘.png
  • figsize (bool or (float, float)) – figure size (width, height) in inches; figsize is defined if multiple figures are drawn or the figures are printed to files, which opens a new figure for each plot; this can be prevented setting figsize to False
  • dpi (int) – dots per inch
  • aspect (float or str) – aspect ratio or ‘equal
  • show (bool or str) – call show(); if show='draw', call draw() instead. show is True if the figures are not printed to files; to maintain this default behaviour in future releases, set show to True from now on.
  • verbose (bool) – verbosity level
  • alpha (float) – alpha value for scalar maps; useful in combination with point_style; if False, the alpha value is not explicitly set
  • point_style (dict) – if defined, points are overlaid
  • feature/variable (str) – feature name (e.g. ‘diffusivity’, ‘force’)
  • segment (int) – segment index; if multiple time segments were defined, show only this segment
  • label/input_label (int or str) – analysis instance label
  • mode (bool or str) – inference mode; can be False so that mode information from files, analysis trees and encapsulated maps are not displayed
  • title (bool or str) – add titles to the figures, based on the feature name; from version 0.4, the inference mode is no longer appended
  • inferencemap (bool) – scales the arrows wrt to cell size only; for field maps only
  • xlim (array-like) – min and max values for the x-axis; this argument is keyworded only
  • ylim (array-like) – min and max values for the y-axis; this argument is keyworded only
  • zlim (array-like) – min and max values for the z-axis; this argument is keyworded only; applies only to scalar maps that are consequently plotted in 3D
  • clim (array-like) – min and max values for the colormap; this argument is keyworded only
  • unit (str) – colorbar label; can be 'std' to take usual units, with space coordinates in µm and and times in s

Extra keyword arguments may be passed to scalar_map_2d(), field_map_2d() and scalar_map_3d(). They can be dictionnaries with feature names as keys and the corresponding values for the parameters.

tramway.helper.inference.map_plot1(maps, cells=None, clip=None, output_file=None, fig_format=None, figsize=None, dpi=None, aspect=None, show=None, verbose=False, alpha=None, point_style=None, feature=None, variable=None, segment=None, label=None, input_label=None, mode=None, title=True, inferencemap=False, use_bokeh=None, **kwargs)

Plot scalar/vector 2D maps.

For consistency with InferenceMAP, the effective potential is showed in \(µm^{-1}\) while – using unit='std' – the colorbar mentions \(k_{B}T\), whereas no conversion factor is applied.

Parameters:
  • maps (str or tramway.core.analyses.base.Analyses or pandas.DataFrame or Maps) – maps as a path to a rwa map file, an analysis tree, a dataframe or a Maps; filepaths and analysis trees may require label (or equivalently input_label) to be defined; dataframes and encapsulated maps require cells to be defined
  • cells (Partition or Tessellation or Distributed) – mesh with optional partition
  • clip (float) – clips map values by absolute values; if clip < 1, it is the quantile at which to clip absolute values of the map; otherwise it defines: threshold = median + clip * (third_quartile - first_quartile)
  • output_file (str) – path to output file
  • fig_format (str) – for example ‘.png
  • figsize (bool or (float, float)) – figure size (width, height) in inches; figsize is defined if multiple figures are drawn or the figures are printed to files, which opens a new figure for each plot; this can be prevented setting figsize to False
  • dpi (int) – dots per inch
  • aspect (float or str) – aspect ratio or ‘equal
  • show (bool or str) – call show(); if show='draw', call draw() instead. show is True if the figures are not printed to files; to maintain this default behaviour in future releases, set show to True from now on.
  • verbose (bool) – verbosity level
  • alpha (float) – alpha value for scalar maps; useful in combination with point_style; if False, the alpha value is not explicitly set
  • point_style (dict) – if defined, points are overlaid
  • feature/variable (str) – feature name (e.g. ‘diffusivity’, ‘force’)
  • segment (int) – segment index; if multiple time segments were defined, show only this segment
  • label/input_label (int or str) – analysis instance label
  • mode (bool or str) – inference mode; can be False so that mode information from files, analysis trees and encapsulated maps are not displayed
  • title (bool or str) – add titles to the figures, based on the feature name; from version 0.4, the inference mode is no longer appended
  • inferencemap (bool) – scales the arrows wrt to cell size only; for field maps only
  • xlim (array-like) – min and max values for the x-axis; this argument is keyworded only
  • ylim (array-like) – min and max values for the y-axis; this argument is keyworded only
  • zlim (array-like) – min and max values for the z-axis; this argument is keyworded only; applies only to scalar maps that are consequently plotted in 3D
  • clim (array-like) – min and max values for the colormap; this argument is keyworded only
  • unit (str) – colorbar label; can be 'std' to take usual units, with space coordinates in µm and and times in s

Extra keyword arguments may be passed to scalar_map_2d(), field_map_2d() and scalar_map_3d(). They can be dictionnaries with feature names as keys and the corresponding values for the parameters.

tramway.helper.animation module

tramway.helper.animation.animate_trajectories_2d_helper(input_data, *args, **kwargs)

Animate 2D trajectories.

Parameters:
  • input_data (pandas.DataFrame or tramway.core.analyses.base.Analyses or str) – nxyt data, or analysis tree, or path to xyt file.
  • columns (str or list) – (comma-separated) list of column names if input data are to be loaded; keyworded-only; see also load_xyt().

The other arguments are passed to animate_trajectories_2d().

tramway.helper.animation.animate_map_2d_helper(input_data, output_file=None, label=None, feature=None, variable=None, **kwargs)

Animate 2D maps.

Parameters:
  • input_data (tramway.core.analyses.base.Analyses or str) – analysis tree or path to rwa file.
  • output_file (str) – path to .mp4 file; if None, the video stream is dumped into a temporary file that is deleted after being played.
  • label (str or list) – path to the maps as a (comma-separated) list of labels.
  • feature/variable (str) – name of the mapped feature to be rendered.

The other keyword arguments are passed to animate_map_2d().

tramway.helper.simulation module

tramway.helper.simulation.categoricaltrap module

class tramway.helper.simulation.categoricaltrap.generate_trajectories(lambda_=1, sigma_=0.4, sigma_noise_=0.01, dt_=0.025, n_short_=1000, N_mean_=7, n_trajs_=100, L_=0.5, density_=2.0, D0_=0.1, amplitude_D_=0.025, amplitude_V_=0, mode_D='linear', mode_V='potential_force', mode_gamma='equilibrium', name_file_out='trajectories.txt', verbose=True)

Bases: object

create_traj()
diffusion_gaussian_bump(x, y)
diffusion_gaussian_trap(x, y)
diffusion_linear(x, y)
generate_the_actual_trajectories()
give_diffusion_drift_gamma(u, v)
give_gamma_equilibirum(D)
give_gamma_fixed_value()
noisify()
potential_drift(x, y)
potential_trap(x, y)
print_traj()
random_start()
traj_duration()
update_position(u_, v_, t_)
tramway.helper.simulation.categoricaltrap.random_walk_2d(*args, **kwargs)

Generate 2D trajectories.

Parameters:
  • lambda (float) – stochastic integral lambda = 0 ito, 1/2 stratonovich, 1 klimintovitch(?)
  • sigma (float) – width of the trap
  • sigma_noise (float) – positioning noise
  • dt (float) – time between frames
  • n_short (int) – number of small time steps between the returned time steps
  • N_mean (int) – mean duration of the trajectories in number of points
  • n_trajs (int) – number of individual trajectories
  • L (float) – size of the trap in microns (half)
  • density (float) – effective density of the random walks
  • D0 (float) – local diffusivity
  • amplitude_D (float) – amplitude of diffusivity variation
  • amplitude_V (float) – ampltiude of the trap or slope
  • mode_D (str) – any of ‘linear’, ‘gaussian_trap’, ‘gaussian_bump
  • mode_V (str) – any of ‘potential_force’, ‘potential_linear
  • mode_gamma (str) – any of ‘equilibrium’, ‘fixed
  • verbose (bool) – print trajectory index (default is False)
Returns:

column ‘n’ is trajectory index, columns ‘x’ and ‘y’ are spatial coordinates (in micrometers) and column ‘t’ is time (in seconds).

Return type:

pandas.DataFrame

See also generate_trajectories for default values.

tramway.helper.simulation.functional module

tramway.helper.simulation.functional.random_walk(diffusivity=None, force=None, friction=None, drift=None, trajectory_mean_count=100, trajectory_count_sd=0, turnover=None, initial_trajectory_count=None, new_trajectory_count=None, lifetime_tau=None, lifetime=None, single=False, box=(0.0, 0.0, 1.0, 1.0), duration=10.0, time_step=0.05, minor_step_count=99, reflect=False, full=False, count_outside_trajectories=None, viscosity=None)

Generate random walks.

Consider also the alternative generator random_walk_2d().

The trajectory_mean_count and trajectory_count_sd arguments are not compatible with the initial_trajectory_count and new_trajectory_count arguments. Use either pair of arguments.

new in 0.6: argument friction replaces viscosity, and a warning is issued if viscosity is used.

The units for force and friction can be adapted as long as the ratio of force over friction is expressed as \(\mu m s^{-1}\) (and drift is not defined).

Parameters:
  • diffusivity (callable or float) – if callable, takes a coordinate vector (ndarray) and time (float), and returns the local diffusivity (float) with \(\mu m^2.s^{-1}\) as a unit
  • force (callable) – takes a coordinate vector (ndarray) and time (float) and returns the local force vector (ndarray) with \(k_{\rm{B}}T\mu m^{-1}\) as a unit
  • friction (callable or float) – if callable, takes a coordinate vector (ndarray) and time (float), and returns the local friction (float) divided by \(k_{\rm{B}}T\), equal to the inverse of the diffusivity under equilibrium
  • drift (callable) – takes a coordinate vector (ndarray) and time (float) if force is not defined, or the same two arguments plus the diffusivity (float) and force (ndarray) otherwise, and returns the local drift; this lets friction unevaluated
  • trajectory_mean_count (int or float) – average number of active trajectories at any time
  • trajectory_count_sd (int or float) – standard deviation of the number of active trajectories
  • turnover (float) – fraction of trajectories that will end at each time step; deprecated
  • initial_trajectory_count (int) – initial number of active trajectories
  • new_trajectory_count (int or callable) – number of newly generated trajectories; if new_trajectory_count is callable, then it takes the time of a step as input and returns the count for this step as an int
  • lifetime_tau (float) – trajectory lifetime constant in seconds
  • lifetime (callable or float) – trajectory lifetime in seconds; if lifetime is a float, then it acts like lifetime_tau; if lifetime is callable, then it takes as input the initial time of the trajectory
  • single (bool) – allow single-point trajectories
  • box (array-like) – origin and size of the space bounding box
  • duration (float) – duration of the simulation in seconds
  • time_step (float) – duration between two consecutive observations
  • minor_step_count (int) – number of intermediate unobserved steps
  • reflect (bool) – reflect the minor steps that would otherwise leave the bounding box
  • full (bool) – include locations that are outside the bounding box and times that are posterior to duration
  • count_outside_trajectories (bool) – include trajectories that have left the bounding box in determining the number of trajectories at each observation step; deprecated
Returns:

simulated trajectories with ‘n’ the trajectory index,

’t’ the time and with other columns for location coordinates

Return type:

pandas.DataFrame

tramway.helper.simulation.functional.truth(cells, t=None, diffusivity=None, force=None, potential=None, **kwargs)

Generate maps for the true diffusivity/force distribution.

If cells is a Partition object, distributed() is called on cells and with the trailing keyword arguments to build a FiniteElements object.

Parameters:
  • cells (Partition or FiniteElements) – distributed data ready for inference
  • t (float) – time as understood by diffusivity and force
  • diffusivity (callable) – admits the coordinates of a single location (array-like) and time (float, if t is defined) and returns the local diffusivity (float)
  • force (callable) – admits the coordinates of a single location (array-like) and time (float, if t is defined) and returns the local force (array-like)
  • potential (callable) – admits the coordinates of a single location (array-like) and time (float, if t is defined) and returns the local potential energy (float)
Returns:

diffusivity/force maps

Return type:

pandas.DataFrame