morphoclass.utils module¶
Miscellaneous utilities.
-
morphoclass.utils.add_metadata(checkpoint)¶ Add metadata information to the checkpoint.
The metadata information includes - A timestamp in ISO format - The name of the package (should be “morphoclass”) - The version of the package - Installed packages
- Parameters
checkpoint (dict) – The checkpoint dictionary.
-
morphoclass.utils.are_you_sure()¶ Interactive prompt asking “Are you sure? (y/N)”.
- Returns
True if the user answered with “y”, otherwise False.
- Return type
bool
-
morphoclass.utils.convert_morphologies(input_dir, old_ext, new_ext, notebook=False)¶ Convert a collection of morphologies to a new format.
All files matching the old extension will be read recursively from the input directory and its subdirectories. A new output directory will then be created by appending and underscore and the new extension to the input directory name, e.g. the directory “my_files” will become “my_files_swc” if the new extension is “swc”.
Note that there are no checks if the output directory already exists and files might be overwritten in the case that it does!
- Parameters
input_dir (str or pathlib.Path) – The directory containing the input morphologies. All subdirectories will be processed recursively.
old_ext (str) – The file extension to convert from. Only files with this extension will be considered.
new_ext (str) – The new extension to convert to. Must be a file extension supported by MorphIO.
notebook (bool) – If true then a widget progress bar will be displayed instead of an ASCII one.
-
morphoclass.utils.dict2kwargs(d)¶ Convert method parameters dict to keyword string for the HTML report.
- Parameters
d (dict, str) – Dictionary to convert or empty string if no parameters are available.
- Returns
String of dictionary shown as keywords.
- Return type
str
-
morphoclass.utils.find_point_on_branch(tree: Tree, start: int, end: int) → list[int]¶ Find all the points in a branch specified by its start and end points.
- Parameters
tree – A TMD tree.
start – Index of the starting point of the branch
end – Index of the ending point of the branch
- Returns
A list of indices of points on the given branch. The indices refer to the non-simplified tree.
- Return type
list
-
morphoclass.utils.from_morphio(root_section)¶ Convert a MorphIO root section to a TMD tree.
- Parameters
root_section – A MorphIO root section.
- Returns
tree – A TMD tree.
- Return type
tmd.Tree.Tree.Tree
-
morphoclass.utils.from_morphio_to_tmd(morphio_neuron, remove_duplicates=False)¶ Change a neuron in MorphIO format to TMD neuron format.
- Parameters
morphio_neuron – A MorphIO neuron.
remove_duplicates (bool) – Whether or not to remove duplicate points at section joints.
- Returns
A TMD neuron.
- Return type
tmd_neuron
-
morphoclass.utils.from_tmd_to_morphio(tmd_neuron)¶ Change a neuron in TMD format to MorphIO neuron format.
- Parameters
tmd_neuron – A TMD neuron.
- Returns
- Return type
A MorphIO neuron.
-
morphoclass.utils.get_loader(samples, idx, batch_size=None)¶ Create a DataLoader from a list of samples and a given index.
- Parameters
samples – A list of samples.
idx – A list of indices that specifies which samples should be included.
batch_size (int, optional) – Number of training samples per batch. By default a full batch will be used.
- Returns
A DataLoader object.
- Return type
torch_geometric.data.DataLoader
-
morphoclass.utils.get_stratified_split(dataset, val_size=None, random_state=None)¶ Get indices for a stratified train/val split.
- Parameters
dataset (morphoclass.data.MorphologyDataset) – The dataset to split.
val_size (flaot) – The relative size of the validation set.
random_state – A random state for the StratifiedShuffleSplit class.
- Returns
train_idx (list) – The indices of the training set.
val_idx – The indices of the validation set.
-
morphoclass.utils.load_var(file_name)¶ Load a serialized variable from the given file.
- Parameters
file_name (str) – The file from which to load the variable.
-
morphoclass.utils.make_torch_deterministic(make_torch_traceback_nicer=True)¶ Make GPU computations using torch deterministic.
Note that in some cases this may have a performance impact. For further information see https://pytorch.org/docs/stable/notes/randomness.html
- Parameters
make_torch_traceback_nicer (bool, optional) – make CUDA generated error tracebacks (“device-side assert triggered”) more explicit. Useful for debugging.
-
morphoclass.utils.morphio_root_section_to_tmd_tree(root_section, remove_duplicates=True)¶ Create a TMD tree class from a MorphIO root section.
- Parameters
root_section – A MorphIO root section
remove_duplicates (bool) – If true then duplicate points at section joins are removed.
- Returns
tree – A TMD tree.
- Return type
tmd.Tree.Tree.Tree
-
morphoclass.utils.no_print(function)¶ Decorate a function to suppress all output to stdout.
-
morphoclass.utils.normalize_features(samples, max_values=None)¶ Normalize all sample features by their maximum.
- Parameters
samples (iterable) – A list of samples to be normalized.
max_values (float or torch.Tensor) – A list of the max values features_wise.
- Returns
samples – The normalized samples.
max_values – The max values that were used for normalization.
-
morphoclass.utils.np_temp_seed(seed)¶ Contextmanager for setting a temporary numpy seed.
- Parameters
seed (int) – The temporary numpy seed.
-
morphoclass.utils.print_error(msg)¶ Print an error message.
-
morphoclass.utils.print_message_to_stderr(header, msg)¶ Print a message to stderr.
- Parameters
header (str) – A header to prepend to the message.
msg (str) – The message.
-
morphoclass.utils.print_warning(msg)¶ Print a warning message.
-
morphoclass.utils.read_apical_from_file(path, label, nodes_features=None, inverted_apical=True)¶ Read the neuron data from a file and constructs a torch Data object.
We extract the simplified apical trees, and use the apical distances as features.
- Parameters
path – Path to the neuron file. Supported file types are .h5, .swc, and .pickle.
label – The label to be attached to the Data class.
nodes_features – List of the nodes features.
inverted_apical (boolean) – If True, radial distances are inverted if the mean of the projections is negative.
- Returns
A sample of the type Data.
- Return type
sample
-
morphoclass.utils.read_layer_neurons_from_dir(data_dir, layer, labels_dic=None, nodes_features=None, inverted_apical=True)¶ Read all neurons corresponding to a given layer.
- Parameters
data_dir – Directory containing subdirectories L[layer]_… with neuron files.
layer – The layer for which to load the samples.
inverted_apical (boolean) – If True, radial distances are inverted if the mean of the projections is negative.
labels_dic (dict) – A mapping from integers to layer names.
nodes_features – A list of the nodes features.
- Returns
samples – A list of samples, each of type Data.
labels – A dictionary for assigning integers to layer names.
paths – A list of the corresponding paths to the neuron stored in samples.
-
morphoclass.utils.save_var(var, file_name, exist_ok=False)¶ Serialize a given variable into a file.
- Parameters
var (obj) – The variable to be pickled.
file_name (str or Path) – The filename where to write the variable.
exist_ok (bool) – If set to False existing files won’t be overwritten and an exception will be raised instead.
- Raises
FileExistsError – File already exists.
-
morphoclass.utils.str_time_delta(time_delta, short=True)¶ Create a nice string representation of a time delta.
The time delta is rounded down to whole seconds.
- Parameters
time_delta (float) – The time delta. Can be computed as the difference of results of two calls of time.time_perf().
short (bool) – Switch between a short and a long string representation.
- Returns
time_str – The string representation of the time delta.
- Return type
str
-
morphoclass.utils.suppress_print(suppress_err=False)¶ Get a context manager for suppressing output to stdout.
-
morphoclass.utils.tree_to_graph(tree)¶ Convert a TMD tree to a networkx graph.
- Parameters
tree (tmd.Tree.Tree.Tree) –
- Returns
The graph representation of the tree.
- Return type
networkx.Graph
-
morphoclass.utils.warn_if_nondeterministic(device)¶ Create a warning if PyTorch is not in deterministic mode.
- Parameters
device (str or torch.device) – The currently used device for which to check the determinism.