skrt.core module

Scikit-rt core data classes and functions.

class skrt.core.Archive(path: str = '', auto_timestamp=False, allow_dirs: bool = False)

Bases: Dated

Dated object associated with multiple files.

__init__(path: str = '', auto_timestamp=False, allow_dirs: bool = False)

Initialise dated object from a path and assign its timestamp. If no valid timestamp is found within the path string, it will be set automatically from the current date and time if auto_timestamp is True.

get_file_size()

Return size in bytes of associated file.

get_n_file()

Return number of data files associated with this object.

class skrt.core.Data(opts: dict | None = None, **kwargs)

Bases: object

Base class for objects serving as data containers. An object has user-defined data attributes, which may include other Data objects and lists of Data objects.

The class provides for printing attribute values recursively, to a chosen depth, and for obtaining nested dictionaries of attributes and values.

__init__(opts: dict | None = None, **kwargs)

Constructor of Data class, allowing initialisation of an arbitrary set of attributes.

Parameters:

opts: dict, default={}

Dictionary to be used in setting instance attributes (dictionary keys) and their initial values.

`**`kwargs

Keyword-value pairs to be used in setting instance attributes and their initial values.

__repr__()

Create string recursively listing attributes and values.

clone(**kwargs)

Return a clone of the Data object. All attributes of the original object will be copied by reference to the new object, with some exceptions (see parameters below).

Parameters:

data_types_to_copylist, default=None

List of types inherting from the Data class. Any objects of the types in this list that are either directly stored as an attribute or stored in a list or dict attribute will be cloned, rather than assigning the same object as to an attribute of the cloned parent object. (Note that these child Data object will be copied with data_types_to_copy=None to prevent recursion.)

copy_databool, default=True

If True, any lists, dicts, and numpy arrays will be shallow copied rather than copied by reference.

clone_attrs(obj, data_types_to_copy=None, copy_data=True)

Assign all attributes of <self> to another object, <obj>.

Parameters:

objobject

Object to which attributes of <self> will be copied.

data_types_to_copylist, default=None

List of types inherting from the Data class. Any objects of the types in this list that are either directly stored as an attribute or stored in a list or dict attribute will be cloned, rather than assigning the same object as to an attribute of the cloned parent object. (Note that these child Data object will be copied with data_types_to_copy=None to prevent recursion.)

copy_databool, default=True

If True, any lists, dicts, and numpy arrays will be shallow copied rather than copied by reference.

get_dict() dict

Return a nested dictionary of object attributes (dictionary keys) and their values.

get_item_string(item)

Return string representation of an item.

If Defaults().compress_user is set to True, the function compress_user() is called for each item corresponding to a file path, where the file or its parent directory exists.

get_print_depth() int

Retrieve the value of the object’s print depth, setting an initial value if not previously defined.

print(depth: int | None = None)

Convenience method for recursively printing object attributes and values, with recursion to a specified depth.

Parameters:

depth: integer/None, default=None

Depth to which recursion is performed. If None, the value returned by self’s get_print_depth() method is used.

set_print_depth(depth: int | None = None)

Set the object’s print depth.

Parameters:

depth: integer/None, default=None

Depth to which recursion is performed. If the value is None, the object’s print depth is set to the value of Defaults().print_depth.

class skrt.core.Dated(path: str = '', auto_timestamp=False)

Bases: PathData

PathData with an associated date and time, which can be used for sorting multiple Dateds.

__init__(path: str = '', auto_timestamp=False)

Initialise dated object from a path and assign its timestamp. If no valid timestamp is found within the path string, it will be set automatically from the current date and time if auto_timestamp is True.

copy_dicom(outdir=None, overwrite=True, sort=True, index=None)

Copy (single) source dicom file.

Derived classes may override this method, to provide for copying multiple files. See, for example:

skrt.image.Image.copy_dicom().

Parameters:

outdirpathlib.Path/str, default=None

Path to directory to which source file is to be copied. if None, this is set to be a directory with name equal to the modality (all upper case) of the dicom data.

overwritebool, default=True

If True, delete and recreate <outdir> before copying file. If False and <outdir> exists already, copy file only if this doesn’t mean overwriting an existing file.

sortbool, default=True

If True, the copied dicom file will be given name of form ‘MODALITY_YYMMDD_hhmmss’. If False, the file is copied with name unaltered.

indexint, default=None

Integer representing associated object position in an ordered list of objects of source data type. Used in construction of output filename if not None, otherwise Ignored.

copy_dicom_files(data_type=None, index=None, indices=None, outdir='dicom', overwrite=True, sort=True)

Copy DICOM file(s) associated with this object.

Parameters:

data_typestr, default=None

String indicting type of data associated with this object. This may be any key of the <indices> dictionary. Ignored if not a key of this dictionary, or if None.

indexint, default=None

Integer representing object position in an ordered list of objects of specified <data_type>. Ignored if None.

indicesdict, default=None

Dictionary where the keys are data types and the values are lists of indices for the objects whose data is to be written. Ignored if None.

outdirpathlib.Path/str, default=”dicom”

Path to directory to which dicom files are to be copied.

overwritebool, default=True

If True, allow copied file(s) to overwrite existing file(s), as defined in derived class’s copy_dicom() method.

sortbool, default=True

If True, files are sorted for copying, as defined in derived class’s copy_dicom() method.

get_matched_timestamps(others=None, delta_seconds=120)

Identify Dated objects that have matching timestamps, within tolerance.

Parameters:

otherslist, default=None

List of objects to be checked for matching timestamps.

delta_secondsint/float, default=120

Maximum time difference (seconds) between timestamps for the timestamps to be considered matched.

get_pandas_timestamp()

Obtain own timestamp as a pandas.Timestamp object.

in_date_interval(min_date: str | None = None, max_date: str | None = None) bool

Check whether own date falls within an interval.

class skrt.core.Defaults(opts: dict | None = None, reset: bool = False)

Bases: object

Singleton class for storing default values of parameters that may be used in object initialisation.

Implementation of the singleton design pattern is based on: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html

__init__(opts: dict | None = None, reset: bool = False)

Constructor of Defaults singleton class.

Parameters:

opts: dict, default={}

Dictionary of attribute-value pairs.

reset: bool, default=False

If True, delete all pre-existing instance attributes before adding attributes and values from opts dictionary. If False, don’t delete pre-existing instance attributes, but add to them, or modify values, from opts dictionary.

__repr__()

Print instance attributes.

instance = by_slice: union compress_user: False foreground_name: foreground foreground_threshold: -150 json_exts: ['.json'] json_names_key: roi_names json_names_to_exclude: background len_date: 8 len_time: 6 log_level: WARNING matlab_app: True matlab_runtime: None mu_water: 0.01701879 nifti_exts: ['.nii', '.nii.gz'] no_ui: False print_depth: 0 registration_engine: elastix shapely_log_level: 40 slice_stats: ['mean'] stations: {} unsorted_dicom: False
class skrt.core.DicomFile(path)

Bases: Data

Class representing files in DICOM format, with conversion to skrt objects.

Methods: - _init__() : Create instance of DicomFile class. - get_object() : Instantiate object of specified Scikit-rt class. - get_matched_attributes() : Identify objects with matched attributes. - set_dates_and_times() : Store timing for specified elements. - set_referenced_sop_instance_uids : Store UIDs of referenced objects. - set_slice_thickness : Store slice thickness for 3D imaging data.

__init__(path)

Create instance of DicomFile class.

Parameter:

pathstr/pathlib.Path

Relative or absolute path to DICOM file.

get_matched_attributes(others, attributes=None)

Identify objects with attribute values matching own attribute values.

Parameters:

otherslist

List of objects to be checked for matches.

attributeslist/str, default=None

List of strings corresponding to attributes whose values are to be checked. If passed as a string, this is converted to a single-element list.

get_object(cls, **kwargs)

Instantiate object of specified Scikit-rt class.

Parameters:

clsClass

Class from which object is to be instantiated. In principle this could be an arbitrary class, but this method is intended for use with: - skrt.dose.Dose; - skrt.dose.Plan; - skrt.image.Image; - skrt.patient.Study; - skrt.structures.StructureSet.

**kwrgs

Keyword arguments to be passed to contstructor of the class from which object is to be instantiated.

set_dates_and_times(elements)

Store timing information for specified elements.

Parameter:

elements: dict

Dictionary where keys are element names - for example, “study”, “item” - and values are DICOM dataset attributes to be checked, in the order listed, for date and time information.

set_referenced_sop_instance_uids()

Store SOP instance UIDs for referenced image, structure set, and plan.

set_slice_thickness()

Store slice thickness for 3D imaging data.

class skrt.core.File(path: str = '', auto_timestamp=False)

Bases: Dated

File with an associated date. Files can be sorted based on their filenames.

class skrt.core.PathData(path='')

Bases: Data

Data with an associated path or directory; has the ability to extract a list of dated objects from within this directory.

__init__(path='')

Constructor of Data class, allowing initialisation of an arbitrary set of attributes.

Parameters:

opts: dict, default={}

Dictionary to be used in setting instance attributes (dictionary keys) and their initial values.

`**`kwargs

Keyword-value pairs to be used in setting instance attributes and their initial values.

create_objects(dtype: type, subdir: str = '', timestamp_only=True, **kwargs) List[Any]

For all the files inside own directory, or own directory + <subdir> if <subdir> is given, create an object of given data type <dtype> if the filename corresponds to a timestamp. Return the created objects in a list.

Parameters:

dtypetype

Type of object to create from files in the specified directory.

subdirstr, default=””

Subdirectory from which to take files. If empty, own top-level directory will be used.

timestamp_onlybool, default=True

If True, only files whose names correspond to a timestamp will be used to initialise objects.

`**`kwargs :

Keyword arguments to pass to object creation.

Returns:

objslist

List of created objects of type <dtype>.

get_file_size()

Return size in bytes of associated file.

get_n_file()

Return number of data files associated with this object.

get_n_file_below()

Where self.path is a directory, return number of files below this.

Returns None if self.path isn’t the path to a directory. In counting files, hidden files are ignored.

print_paths(max_path=None)

Print paths of data files associated with this object.

File paths are listed in natural order, with one path per line.

Parameters: max_path: int/None, default=None

Indication of maximum number of paths to print. If a positive integer, the first <max_path> paths are printed. If a negative integer, the last <max_path> paths are printed. If None, all paths are printed.

class skrt.core.TicToc(message=None, time_format='.6f', log_level=None)

Bases: object

Singleton class for storing timing information, to allow emulation of MATLAB tic/toc functionality.

Implementation of the singleton design pattern is based on: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html

__init__(message=None, time_format='.6f', log_level=None)

Constructor of TicToc singleton class.

Parameters:

message: str/bool, default=None

Value to be assigned to skrt.core.TicToc().message, which defines the default behaviour for printing elapsed time when calling skrt.core.toc(). If a value of True is set, the string skrt.core.TicToc().default_message (initialised to “Time elapsed is “) is printed. In the first call to this method, a value of None initialises skrt.core.TicToc().message to False. In subsequent calls, a value of None is disregarded.

time_formatstr, default=None

Value to be assigned to skrt.core.TicToc().time_format, which defines the Format for printing elapsed time (seconds). In the first call to this method, a value of None initialises skrt.core.TicToc().time_format to “.6f”. In subsequent calls, a value of None is disregarded.

log_levelstr, default=None

Value to be assigned to skrt.core.TicToc().log_level, which defines the Severity level for event logging. In the first call to this method, a value of None initialises skrt.core.TicToc().time_format to Defaults().log_level. In subsequent calls, a value of None is disregarded.

__repr__()

Print instance attributes.

instance = None
skrt.core.alphanumeric(in_str: str = '') List[str]

Function that can be passed as value for list sort() method to have alphanumeric (natural) sorting

skrt.core.compress_user(path='')

If path starts with home directory, replace by ‘~’

skrt.core.download(url, outdir='.', outfile=None, binary=True, unzip=False)

Download data from specified URL.

Parameters:

urlstr

URL from which to download data.

outdirstr/pathlib.Path, default=”.”

Path to (local) directory to which data are to be downloaded.

outfilestr, default=None

Name of the file to be downloaded. If None, the name is taken to be the part of the URL following the last (non-trailing) slash.

binarybool, default=True

If True, treat downloaded file as being in binary format.

unzipbool, default=True

If True, treat downloaded file as being a zip-format archive, and unzip.

skrt.core.filter_on_paths(objs, paths_to_match=None, log_level=None)

Filter list of intances of PathData or a subclass.

objs: object/list

Instance, or list of instances, of PathData or a subclass.

paths_to_match: str/list, default=None

String, or list of strings, specifying allowed paths. The filtered list of objects will contain only objects with an allowed path. If None, no filtering is performed.

log_level: string/integer/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of Defaults().log_level.

skrt.core.filtered_dict(items=None, filters=None)

Filter a nested dictionary based on first-level keys.

This function is designed for simplifying dictionaries where first-level keys can respond to different options, as may be read from a configuration file.

Parameters:

items: dict, default=None

Dictionary to which filters are to be applied. If None, an empty dictionary is returned.

filters: dict/list, default=None

Filters to be applied.

If a dictionary, keys are selections, and values are lists of the options from which the selections are made. Application of the filter promotes second-level keys of the selection to first-level keys, and deletes all first-level keys specified as options. For example, if the dictionary for filtering is:

items = {“opt1” : {“prop1”: “val1”}, “opt2” : {“prop2”: “val2”}}

the filter {“opt1” : [“opt1”, “opt2”}} will reduce this to:

items = {“prop1”: “val1”}

If a list, elements are selections. Application of the filter promotes second-level keys of the selection to first-level keys, and deletes the selection first-level key. For example, if the dictionary for filtering is:

items = {“opt1” : {“prop1”: “val1”}, “opt2” : {“prop2”: “val2”}}

the filter [“opt1”] will reduce this to:

items = {“prop1”: “val1”, “opt2” : {“prop2”: “val2”}}

If None, the original dictionary is returned. Or if the original dictionary is None then an empty dictionary is returned.

Selections are applied in the order in which they are stored in the filter dictionary of list.

skrt.core.fullpath(path='', pathlib=False)

Evaluate full path, expanding ‘~’, environment variables, and symbolic links.

path: str/pathlib.Path, default=””

Path to be expanded.

pathlib: bool, default=False

If False, return full path as string. If True, return full path as pathlib.Path object.

skrt.core.generate_timestamp() str

Make timestamp from the current time.

skrt.core.get_associated_image(objs, voxel_selection='most')

Identify an image associated with at least one of a set of objects.

If none of the input objects has an image attribute, None is returned.

Parameters:

objslist

List of objects, which potentially have an image attribute, identifying an associated image.

voxel_selectionstr, default=”most”

Criterion used for selecting associated image is cases where there is more than one candidate. Possible values are: - None: return first image encountered; - “most”: return image with the highest number of voxels; - “least”: return image with the lowest number of voxels.

skrt.core.get_basenames(paths=None)

Return list of basenames for specified path(s), optionally with wildcards.

Parameter:

paths: list/str/pathlib.Path, default=None

Single path, or list of paths, for which basenames are to be returned. Paths may optionally include wildcards. If a path matches one or more file-system paths, the basenames for all of the matched paths are returned. Otherwise, the basename is returned with any wildcards left.

skrt.core.get_data_by_filename(data_objects=None, remove_timestamp=True, remove_suffix=True)

Create dictionary of data_objects from list.

Dictionary keys are derived from the paths to the data sources.

Parameters:

data_objectslist, default=None

List of data objects.

remove_timestampbool, default=True

If True, remove and timestamps from filenames to be used as dictionary keys.

remove_suffixbool, default=True

If True, remove any suffixes from filenames to be used as dictionary keys.

skrt.core.get_data_indices(in_value, valid_data_types)

Obtain dictionary associating indices with data types.

This is used in patient.skrt.Study.copy_dicom() to obtain dictionaries from input parameters that may be dictionaries, lists, or None.

Parameters:

in_valuedict/str/int/list/None

Specification of indices associated with data types. list of data types, or None. If a dictionary, return after removing any keys not in <valid_data_types>. If a string, return a dictionary that associates with it the value True (all file indices) if the string is in <valid_data_types>, or otherwise return an empty dictionary. If an integer, return a dictionary that associates this value with all data types of <valid_data_types>. If a list, return a dictionary that associates the value True with each listed data type that is in <valid_data_types>. If None, return a dictionary that associates the value True with all data types of <valid_data_types>.

valid_data_typeslist

List of valid data_types.

skrt.core.get_day_in_week(timestamp)

Return a timestamp’s day in week, including fractional part.

Parameter:

timestamppandas.Timestamp

Timestamp for which day in week is to be returned.

skrt.core.get_dict_permutations(in_dict=None)

Get list of permuations of key-value pairs from dictionary of lists.

Parameter:

in_dict: dict, default=None

Dictionary of lists for which a list of permutations of key-value pairs is to be obtained. In case the object passed as in_dict isn’t a dictionary, a list containing an empty dictionary is returned.

As an example, the list of permuations for the dictionary:

{“A”: [1, 2], “B”: [3, 4]}

is:

[{“A”: 1, “B”: 3}, {“A”: 1, “B”: 4}, {“A”: 2, “B”: 3}, {“A”: 2, “B”: 4}]

skrt.core.get_file_size(objs=None)

Return size in bytes of data files associated with listed objects.

Parameter:

objslist, default=None

List of objects for which file sizes are to be summed.

skrt.core.get_float(obj, attribute, default=None)

Return object attribute as a float.

Parameters:

obj : Object to be considered.

attributestr

Name of object attribute to be returned as float.

defaultValue to be returned in case object attribute

can’t be converted to float.

skrt.core.get_hour_in_day(timestamp)

Return a timestamp’s hour in day, including fractional part.

Parameter:

timestamppandas.Timestamp

Timestamp for which hour in day is to be returned.

skrt.core.get_hour_in_week(timestamp)

Return a timestamp’s hour in week, including fractional part.

Parameter:

timestamppandas.Timestamp

Timestamp for which hour in week is to be returned.

skrt.core.get_indexed_objs(objs, indices=True)

Select subset of objects from a list.

Parameters: objs : list

List of objects.

indicesbool/list/int

Specification of objects to select from list:

  • True: select all objects;

  • False: select no objects;

  • integer: select object with index equal to given integer;

  • list of integers: select objects with indices equal to given integers.

skrt.core.get_interval_in_days(timestamp1, timestamp2)

Return interval in days between two timestamps.

Parameters:

timestamp1pandas.Timestamp

Timestamp corresponding to start of interval.

timestamp2pandas.Timestamp

Timestamp corresponding to end of interval.

skrt.core.get_interval_in_whole_days(timestamp1, timestamp2)

Return interval in whole days between two timestamps.

Parameters:

timestamp1pandas.Timestamp

Timestamp corresponding to start of interval.

timestamp2pandas.Timestamp

Timestamp corresponding to end of interval.

skrt.core.get_logger(name='', log_level=None, identifier='name')

Retrieve named event logger.

Parameters:

name: string, default=””

Name of logger (see documentation of logging module)

log_level: string/integer/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of Defaults().log_level.

identifier: str, default=”name”

Attribute to use to identify logger messages. Possibilities include “name”, “filename”, “funcName”. For a list of available attributes, not all of which make sense as identifiers, see: https://docs.python.org/3/library/logging.html#logrecord-attributes

skrt.core.get_n_file(objs=None)

Return number of data files associated with listed objects.

Parameter:

objslist, default=None

List of objects for which numbers of files are to be summed.

skrt.core.get_n_file_below(indir)

Return number of files below a directory, ignoring hidden files.

Returns None if indir isn’t the path to a directory.

Parameter: indir: str, pathlib.Path

Path to directory below which files are to be counted.

skrt.core.get_qualified_class_name(cls)

Determine qualified name of class <cls>.

skrt.core.get_referenced_image(referrer=None, image_types=None)

Retrieve from <image_types> image object referred to by <referrer>.

Parameters:

referrerobject, default=None

Object that references an image object via its SOP instance UID.

image_typesdict, default=None

Dictionary where keys are imaging modalities and values are lists of image objects for this modality.

skrt.core.get_referenced_object(referrer, others, tag, omit_slice=False)

Retrieve from <others> object referred to via <tag> by <referrer>.

Parameters:

referrerobject

Object that references another object via a tag. This tag should be a reference to a SOP instance UID.

otherslist

List of objects to be considered for identifying referenced object.

tagstr

String identifying object attribute that references a SOP instance UID. Valid values are those defined in skrt.DicomFile.set_referenced_sop_instance_uids(), namely: ‘referenced_image_sop_instance_uid’; ‘referenced_structure_set_sop_instance_uid’; ‘referenced_plan_sop_instance_uid’.

omit_slicebool, default=False

If True, disregard the last part of all UIDs, meaning the part from the last dot onwards. For imaging data, this part distinguishes between different slices.

skrt.core.get_single_path(path, allowed_suffixes=None, excluded_suffixes=None, pathlib=True, include_hidden=False)

Get full path to a single file, filtering on file suffixes.

Parameters:

path, str/pathlib

Path to check for identifying a single file. If path is for a file, the full path to this file is returned. If path is for a directory that contains a single file, after filtering on suffixes, the full path to this file is returned. In all other cases, None is returned.

allowed_suffixes: list, default=None

List of allowed suffixes, when filtering directory contents. If None, all suffixes are allowed.

excluded_suffixes: list, default=None

List of excluded suffixes, when filtering directory contents. If None, no suffixes are excluded. Filtering on excluded suffixes is performed after filtering on allowed suffixes, so if a suffix is listed as both allowed and excluded it will be excluded.

pathlib: bool, default=True

If True, return file path as a pathlib.Path object. If False, return as a string.

include_hidden: bool, default=False

If True, include files having names that begin with a dot when filtering directory contents. If False, disregard these files.

skrt.core.get_stat(values=None, value_for_none=None, stat='mean', **kwargs)

Calculate statistic(s) for values in a list or dictionary.

If input values are lists or tuples, a list is returned with element-by-element statistics.

Parameters:

values: list/tuple/dict

Values for which to calculate statistic(s). If a dictionary, the dictionary values are used.

value_for_none: int/float/None, default=None

Value to be substituted for any None values, before calculation of statistic(s). If None, None values are omitted, rather than being substituted.

stat: str, default=”mean”

Statistic(s) to be calculated. This should be the name of the function for calculation of the statistic(s) in the Python statistics module:

Available options include: “mean”, “median”, “mode”, “stdev”, “quantiles”.

kwargsdict, default=None

Keyword arguments to be passed to the relevant function of the Python statistics module:

For example, if quantiles are required for 10 intervals, rather than for the default of 4, this can be specified using:

kwargs={“n” : 10}

skrt.core.get_stat_functions()

Get names of statistical functions implemented in Python statistics module.

For details of statistics module, see:

https://docs.python.org/3/library/statistics.html

skrt.core.get_subdir_paths(parent)

Return paths to a directory’s sub-directories.

Parameter:

parentpathlib.Path/str

Path to directory for which sub-directory paths are to be found.

skrt.core.get_time_and_date(timestamp: str = '') Tuple[str, str]

Extract time and date separately from timestamp.

skrt.core.get_time_separated_objects(objs, min_delta=4, unit='hour', most_recent=True)

Return ordered list of dated objects, filtering for minimum time separation.

objslist

List of dated objects.

min_deltaint/pandas.Timedelta, default=4

Minimum time interval required between objects. If an integer, the unit must be specified.

unitstr, default=’hour’

Unit of min_delta if the latter is specified as an integer; ignored otherwise. Valid units are any accepted by pandas.Timedelta: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.html

most_recentbool, default=True

When objects aren’t separated by the minimum time interval, keep the most recent if True, or the least recent otherwise.

skrt.core.get_uid_without_slice(uid)

Obtain copy of <uid>, truncated to before final dot.

skrt.core.get_value_from_json(path, key, default=None, array_type=<class 'tuple'>)

Get value from a JSON file.

Parameters: path: str/pathlib.Path

Path to JSON file from which value is to be read.

key: str

Key in dictionary read from JSON file for which value is to be returned.

default: any, default=None

Value to be returned if <key> not found in dictionary read from JSON file.

array_type: sequence, default=tuple

Type to which to convert a JSON array.

skrt.core.hu_to_mu(hu, mu_water=None)

Convert value(s) in Hounsfield units to linear attenuation coefficient(s).

Parameters:

hufloat/numpy.ndarray

Radiodensity, or array of radiodensities, in Hounsfield Units, to be converted to linear attenuation coefficient(s).

mu_waterfloat, default=None

Value to be used for the linear attenuation coefficient of water. If None, set to the value of skrt.core.Defaults().mu_water

Note: The linar attenuation coefficient(s) returned will be in the same units as <mu_water>. For consistency with the units used for image voxel dimensions, it’s recommended that <mu_water> be specified in units of mm^-1. This is the case if the default value is used.

skrt.core.is_list(var: Any) bool

Check whether a variable is a list, tuple, or array.

skrt.core.is_timestamp(string: str = '') bool

Check whether a string is a valid timestamp.

skrt.core.load_json(path)

Load to dictionary data from a JSON file.

Parameter: path: str/pathlib.Path

Path to JSON file from which data are to be loaded. If the specified file isn’t found, an empty dictionary is returned.

skrt.core.load_toml(toml_path, filters=None)

Load TOML-formatted data from file, and return a dictionary.

For information about TOMO (Tom’s Obvious Minimal Language), see: https://toml.io/

Parameters:

toml_path: str/pathlib.Path

Path to file containing data formatted using TOML.

filters: dict, default=None

Filters to be applied to the dictionary created from the TOML-formatted input. If None, no filters are applied. For information about filters, see documentation for skrt.core.filtered_dict().

skrt.core.make_dir(path='.', overwrite=True, require_empty=False)

Create a directory if it doesn’t exist already, or if overwriting allowed.

Parameters:

pathpathlib.Path/str, default=”.”

Path to directory.

overwritebool, default=True

If True, delete any pre-existing directory and its contents. If False, leave unaltered any pre-existing directory and its contents.

require_emptybool, default=False

If True, return None if the directory already exists, the directory isn’t empty, and <overwrite> is False.

skrt.core.matches_suffix(path, suffixes=None)

Determine whether a file path ends with an allowed value.

If a match with a single allowed value is found, this value is returned. If multiple matches are found, the longest match is returned. If no match is found, an empty string is returned.

Parameters:

path: str/pathlib.Path

Path to be checked.

suffixes: str/list, default=None

String, or list of strings, specifying allowed path endings. Different from a suffix in the contest of pathlib, a path ending may contain no dots, or may contain multiple dots.

skrt.core.mu_to_hu(mu, mu_water=None)

Convert linear attenuation coefficient(s) to Hounsfield units.

Parameters:

mufloat/numpy.ndarray

Attenuation value(s) to be converted to Hounsfield units.

mu_waterfloat, default=None

Value to be used for the linear attenuation coefficient of water. If None, set to the value of skrt.core.Defaults().mu_water

Note: The linar attenuation coefficients <mu> and <mu_water> should have the same units. For consistency with the units used for image voxel dimensions, it’s recommended that linear attenuation coefficients be specified in units of mm^-1. This is the case for <mu_water> if the default value is used.

skrt.core.prepend_path(variable, path, path_must_exist=True)

Prepend path to environment variable.

Parameters:

variablestr

Environment variable to which path is to be prepended.

pathstr/pathlib.Path

Path to be prepended.

path_must_existbool, default=True

If True, only append path if it exists.

skrt.core.print_paths(data_dir, max_path=None)

Print paths to files below a directory, ignoring hidden files.

File paths are listed in natural order, with one path per line.

Parameters: data_dir: str, pathlib.Path

Path to directory below which file paths are to be printed.

max_path: int/None, default=None

Indication of maximum number of paths to print. If a positive integer, the first <max_path> paths are printed. If a negative integer, the last <max_path> paths are printed. If None, all paths are printed.

skrt.core.qualified__name(cls)

Return qualified name of a class.

Parameter:

clsclass

Class for which qualified name is to be determined. If non-class is passed as argument, None is returned.

skrt.core.qualified_name(cls=None)

Return qualified name of a class.

Return None if non-class given as input.

skrt.core.relative_path(path, nlevel=None)

Return relative path.

The returned path will be relative to the user’s top-level directory, or will include a specified number of directory levels.

Parameter:

nlevelint, default=None

If None, indicates that the returned path should be relative to the user’s top-level directory. Otherwise, this specifies the number of directory levels to include in the returned path. If nlevel is positive, the top-most nlevels, up to the number of directory levels in the path, are omitted. If nlevel is negative, the bottom-most abs(nlevels), up to the number of directory levels in the path, are retained.

skrt.core.set_matlab_runtime(matlab_runtime=None, log_level=None)

Set environment to allow use of MATLAB runtime installation in subprocess.

Parameters:

matlab_runtime: str/pathlib.Path, default=None

Path to root directory of MATLAB runtime installation. It the value is None, matlab_runtime is set to the value of Defaults().log_level.

log_level: string/integer/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of Defaults().log_level.

skrt.core.tic()

Set timer start time.

skrt.core.to_list(val, n_item=3, keep_none_single=True)

Ensure that a value is a list of n_item items.

skrt.core.toc(message=None, time_format=None)

Record, and optionally report, time since corresponding call to tic().

Each call to tic() adds a start time to the list skrt.core.TicToc().tics. Each call to toc() removes the last start time from the list, and records the time elapsed since that start time. If the list is empty, the call to toc() records the time elapsed since the last call to tic(). This allows for nested timings, and for cumulative timings.

For example:

tic() # tic_1 for idx in range(5)

tic() # tic_idx # do something toc() # time since tic_idx

toc() # time since tic_1 # do something toc() # time since tic_1

Parameters:

messagestr/bool, default=None

If at least one of message and skrt.core.TicToc().message evaluates to True, elapsed time will be printed, preceded by message if this is a string, by skrt.core.TicToc().message (initialised to False) if this is a string, otherwise by skrt.core.TicToc().default_message (initialised to “Elapsed time is “).

time_formatstr, default=None

Format for printing elapsed time (seconds). If None, use skrt.core.TicToc().time_format, which is initialised to “.6f”

skrt.core.year_fraction(timestamp)

Convert from timestamp to year, including fractional part.

Parameter:

timestamppandas.Timestamp

Timestamp to be converted.