Utils

This package provides utility functions as image operations, various decorators, path operations and time operations.

classtype_func(class_object)[source]

Decorator to Check whether the first argument of the decorated function is a subclass of a certain type

Parameters:class_object (Any) – type the first function argument should be subclassed from
Returns:
Return type:Wrapped Function
Raises:AssertionError – First argument of decorated function is not a subclass of given type
dtype_func(class_object)[source]

Decorator to Check whether the first argument of the decorated function is of a certain type

Parameters:class_object (Any) – type the first function argument should have
Returns:
Return type:Wrapped Function
Raises:AssertionError – First argument of decorated function is not of given type
make_deprecated(new_func)[source]

Decorator which raises a DeprecationWarning for the decorated object

Parameters:new_func (Any) – new function which should be used instead of the decorated one
Returns:
Return type:Wrapped Function
Raises:Deprecation Warning
numpy_array_func(func)
torch_module_func(func)
torch_tensor_func(func)
bounding_box(mask, margin=None)[source]

Calculate bounding box coordinates of binary mask

Parameters:
  • mask (SimpleITK.Image) – Binary mask
  • margin (int, default: None) – margin to be added to min/max on each dimension
Returns:

bounding box coordinates of the form (xmin, xmax, ymin, ymax, zmin, zmax)

Return type:

tuple

calculate_origin_offset(new_spacing, old_spacing)[source]

Calculates the origin offset of two spacings

Parameters:
  • new_spacing (list or np.ndarray or tuple) – new spacing
  • old_spacing (list or np.ndarray or tuple) – old spacing
Returns:

origin offset

Return type:

np.ndarray

max_energy_slice(img)[source]

Determine the axial slice in which the image energy is max

Parameters:img (SimpleITK.Image) – given image
Returns:slice index
Return type:int
sitk_copy_metadata(img_source, img_target)[source]

Copy metadata (=DICOM Tags) from one image to another

Parameters:
  • img_source (SimpleITK.Image) – Source image
  • img_target (SimpleITK.Image) – Source image
Returns:

Target image with copied metadata

Return type:

SimpleITK.Image

sitk_new_blank_image(size, spacing, direction, origin, default_value=0.0)[source]

Create a new blank image with given properties

Parameters:
  • size (list or np.ndarray or tuple) – new image size
  • spacing (list or np.ndarray or tuple) – spacing of new image
  • direction – new image’s direction
  • origin – new image’s origin
  • default_value (float) – new image’s default value
Returns:

Blank image with given properties

Return type:

SimpleITK.Image

sitk_resample_to_image(image, reference_image, default_value=0.0, interpolator=2, transform=None, output_pixel_type=None)[source]

Resamples Image to reference image

Parameters:
  • image (SimpleITK.Image) – the image which should be resampled
  • reference_image (SimpleITK.Image) – the resampling target
  • default_value (float) – default value
  • interpolator (Any) – implements the actual interpolation
  • transform (Any (default: None)) – transformation
  • output_pixel_type (Any (default:None)) – type of output pixels
Returns:

resampled image

Return type:

SimpleITK.Image

sitk_resample_to_shape(img, x, y, z, order=1)[source]

Resamples Image to given shape

Parameters:
  • img (SimpleITK.Image) –
  • x (int) – shape in x-direction
  • y (int) – shape in y-direction
  • z (int) – shape in z-direction
  • order (int) – interpolation order
Returns:

Resampled Image

Return type:

SimpleITK.Image

sitk_resample_to_spacing(image, new_spacing=(1.0, 1.0, 1.0), interpolator=2, default_value=0.0)[source]

Resamples SITK Image to a given spacing

Parameters:
  • image (SimpleITK.Image) – image which should be resampled
  • new_spacing (list or np.ndarray or tuple) – target spacing
  • interpolator (Any) – implements the actual interpolation
  • default_value (float) – default value
Returns:

resampled Image with target spacing

Return type:

SimpleITK.Image

subdirs(d)[source]

For a given directory, return a list of all subdirectories (full paths)

Parameters:d (string) – given root directory
Returns:list of strings of all subdirectories
Return type:list
now()[source]

Return current time as YYYY-MM-DD_HH-MM-SS

Returns:current time
Return type:string
class LookupConfig(file_=None, config=None, update_from_argv=False, deep=False, **kwargs)[source]

Bases: trixi.util.config.Config

Helper class to have nested lookups in all subdicts of Config

clear() → None. Remove all items from D.
contains(dict_like)

Check whether all items in a dictionary-like object match the ones in this Config.

Parameters:dict_like (dict or derivative thereof) – Returns True if this is contained in this Config.
Returns:True if dict_like is contained in self, otherwise False.
Return type:bool
copy() → a shallow copy of D
deepcopy()

Get a deep copy of this Config.

Returns:A deep copy of self.
Return type:Config
deepupdate(dict_like, ignore=None, allow_dict_overwrite=True)

Identical to update() with deep=True.

Parameters:
  • dict_like (dict or derivative thereof) – Update source.
  • ignore (iterable) – Iterable of keys to ignore in update.
  • allow_dict_overwrite (bool) – Allow overwriting with dict. Regular dicts only update on the highest level while we recurse and merge Configs. This flag decides whether it is possible to overwrite a ‘regular’ value with a dict/Config at lower levels. See examples for an illustration of the difference
difference_config(*other_configs)

Get the difference of this and any number of other configs. See difference_config_static() for more information.

Parameters:*other_configs (Config) – Compare these configs and self.
Returns:Difference of self and the other configs.
Return type:Config
static difference_config_static(*configs, only_set=False)

Make a Config of all elements that differ between N configs.

The resulting Config looks like this:

{
    key: (config1[key], config2[key], ...)
}

If the key is missing, None will be inserted. The inputs will not be modified.

Parameters:
  • configs (Config) – Any number of Configs
  • only_set (bool) – If only the set of different values hould be returned or for each config the
  • one (corresponding) –
Returns:

Possibly empty Config

Return type:

Config

dump(file_, indent=4, separators=(', ', ': '), **kwargs)

Write config to file using json.dump().

Parameters:
  • file (str or File) – Write to this location.
  • indent (int) – Formatting option.
  • separators (iterable) – Formatting option.
  • **kwargs – Will be passed to json.dump().
dumps(indent=4, separators=(', ', ': '), **kwargs)

Get string representation using json.dumps().

Parameters:
  • indent (int) – Formatting option.
  • separators (iterable) – Formatting option.
  • **kwargs – Will be passed to json.dumps().
flat(keep_lists=True, max_split_size=10)

Returns a flattened version of the Config as dict.

Nested Configs and lists will be replaced by concatenated keys like so:

{
    "a": 1,
    "b": [2, 3],
    "c": {
        "x": 4,
        "y": {
            "z": 5
        }
    },
    "d": (6, 7)
}

Becomes:

{
    "a": 1,
    "b": [2, 3], # if keep_lists is True
    "b.0": 2,
    "b.1": 3,
    "c.x": 4,
    "c.y.z": 5,
    "d": (6, 7)
}

We return a dict because dots are disallowed within Config keys.

Parameters:
  • keep_lists – Keeps list along with unpacked values
  • max_split_size – List longer than this will not be unpacked
Returns:

A flattened version of self

Return type:

dict

fromkeys()

Returns a new dict with keys from iterable and values equal to value.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
hasattr_not_none(key)
static init_objects(config)

Returns a new Config with types converted to instances.

Any value that is a Config and contains a type key will be converted to an instance of that type:

{
    "stuff": "also_stuff",
    "convert_me": {
        type: {
            "param": 1,
            "other_param": 2
        },
        "something_else": "hopefully_useless"
    }
}

becomes:

{
    "stuff": "also_stuff",
    "convert_me": type(param=1, other_param=2)
}

Note that additional entries can be lost as shown above.

Parameters:config (Config) – New Config will be built from this one
Returns:A new config with instances made from type entries.
Return type:Config
items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
load(file_, raise_=True, decoder_cls_=<class 'trixi.util.util.ModuleMultiTypeDecoder'>, **kwargs)

Load config from file using json.load().

Parameters:
  • file (str or File) – Read from this location.
  • raise (bool) – Raise errors.
  • decoder_cls (type) – Class that is used to decode JSON string.
  • **kwargs – Will be passed to json.load().
loads(json_str, decoder_cls_=<class 'trixi.util.util.ModuleMultiTypeDecoder'>, **kwargs)

Load config from JSON string using json.loads().

Parameters:
  • json_str (str) – Interpret this string.
  • decoder_cls (type) – Class that is used to decode JSON string.
  • **kwargs – Will be passed to json.loads().
nested_get(key, *args, **kwargs)[source]

Returns all occurances of key in self and subdicts

Parameters:
  • key (str) – the key to search for
  • *args – positional arguments to provide default value
  • **kwargs – keyword arguments to provide default value
Raises:

KeyError – Multiple Values are found for key (unclear which value should be returned) OR No Value was found for key and no default value was given

Returns:

value corresponding to key (or default if value was not found)

Return type:

Any

pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

set_from_string(str_, stringify_value=False)

Set a value from a single string, separated with “=”. Uses :meth:´set_with_decode´.

Parameters:str (str) – String that looks like “key=value”.
set_with_decode(key, value, stringify_value=False)

Set single value, using ModuleMultiTypeDecoder to interpret key and value strings by creating a temporary JSON string.

Parameters:
  • key (str) – Config key.
  • value (str) – New value key will map to.
  • stringify_value (bool) – If True, will insert the value into the temporary JSON as a real string. See examples!

Examples

Example for when you need to set stringify_value=True:

config.set_with_decode("key", "__type__(trixi.util.config.Config)", stringify_value=True)

Example for when you need to set stringify_value=False:

config.set_with_decode("key", "[1, 2, 3]")
setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
to_cmd_args_str()

Create a string representing what one would need to pass to the command line. Does not yet use JSON encoding!

Returns:Command line string
Return type:str
update(dict_like, deep=False, ignore=None, allow_dict_overwrite=True)

Update entries in the Config.

Parameters:
  • dict_like (dict or derivative thereof) – Update source.
  • deep (bool) – Make deep copies of all references in the source.
  • ignore (iterable) – Iterable of keys to ignore in update.
  • allow_dict_overwrite (bool) – Allow overwriting with dict. Regular dicts only update on the highest level while we recurse and merge Configs. This flag decides whether it is possible to overwrite a ‘regular’ value with a dict/Config at lower levels. See examples for an illustration of the difference

Examples

The following illustrates the update behaviour if :obj:allow_dict_overwrite is active. If it isn’t, an AttributeError would be raised, originating from trying to update “string”:

config1 = Config(config={
    "lvl0": {
        "lvl1": "string",
        "something": "else"
    }
})

config2 = Config(config={
    "lvl0": {
        "lvl1": {
            "lvl2": "string"
        }
    }
})

config1.update(config2, allow_dict_overwrite=True)

>>>config1
{
    "lvl0": {
        "lvl1": {
            "lvl2": "string"
        },
        "something": "else"
    }
}
update_missing(dict_like, deep=False, ignore=None)

Recursively insert values that do not yet exist.

Parameters:
  • dict_like (dict or derivative thereof) – Update source.
  • deep (bool) – Make deep copies of all references in the source.
  • ignore (iterable) – Iterable of keys to ignore in update.
values() → an object providing a view on D's values