FastSurferCNN.utils.brainvolstats

class FastSurferCNN.utils.brainvolstats.AbstractMeasure(name, description, unit)[source]

The base class of all measures, which implements the name, description, and unit attributes as well as the methods as_tuple(), __call__(), read_subject(), set_args(), parse_args(), help(), and __str__().

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Compute and return the value of the measure.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Compiles a help message for the measure describing the measure's settings.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args(**kwargs)

Set the arguments of the Measure.

as_tuple()[source]

Return the measure as a MeasureTuple (name, description, value, unit).

help()[source]

Compiles a help message for the measure describing the measure’s settings.

Returns:
str

A help string describing the Measure settings.

parse_args(*args)[source]

Parse additional args defining the behavior of the Measure.

Parameters:
*argsstr

Each args can be a string of ‘<value>’ (arg-style) and ‘<keyword>=<value>’ (keyword-arg-style), arg-style cannot follow keyword-arg-style args.

Raises:
ValueError

If there are more arguments than registered argument names.

RuntimeError

If an arg-style follows a keyword-arg-style argument, or if a keyword value is redefined, or a keyword is not valid.

read_subject(subject_dir)[source]

Perform IO required to compute/fill the Measure.

Parameters:
subject_dirPath

Path to the directory of the subject_dir (often subject_dir/subject_id).

Returns:
bool

Whether there was an update.

set_args(**kwargs)[source]

Set the arguments of the Measure.

Raises:
ValueError

If there are unrecognized keyword arguments.

property description[source]

The human-readable description of the measure.

property name[source]

The short name of the measure.

property subject_dir[source]

The subject directory last passed to read_subject(), or None.

property unit[source]

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

class FastSurferCNN.utils.brainvolstats.DerivedMeasure(parents, name, description, unit='from parents', operation='sum', measure_host=None)[source]

A Measure whose value is derived arithmetically from one or more parent Measures.

Supports three aggregation operations: 'sum', 'ratio', and 'by_vox_vol'.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

parents

Iterable of the measures this measure depends on.

read_subject_on_parents

Read/Update the measures from subject_dir for all parent measures.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

Property to access the unit attribute, also implements auto-generation of unit, if the stored unit is 'from parents'.

Methods

__call__()

Aggregate the parent measure values using the configured operation.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

get_vox_vol()

Return the voxel volume of the first parent measure.

help()

Return a human-readable formula string for the derived measure.

invalid_len_ratio()

Return a RuntimeError for an invalid number of parents for the 'ratio' operation.

invalid_len_vox_vol()

Return a RuntimeError for an invalid number of parents for 'by_vox_vol'.

parents_items()

Iterate over (factor, measure) pairs for all parent measures.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([parents, operation])

Optionally update parents and/or operation string, then delegate to parent.

get_vox_vol()[source]

Return the voxel volume of the first parent measure.

Returns:
float, None

Voxel volume of the first parent.

help()[source]

Return a human-readable formula string for the derived measure.

invalid_len_ratio()[source]

Return a RuntimeError for an invalid number of parents for the 'ratio' operation.

Returns:
RuntimeError

Error message including the actual parent count.

invalid_len_vox_vol()[source]

Return a RuntimeError for an invalid number of parents for 'by_vox_vol'.

Returns:
RuntimeError

Error message including the actual parent count.

parents_items()[source]

Iterate over (factor, measure) pairs for all parent measures.

Returns:
Iterable[tuple[float, AbstractMeasure]]

Each item is (weight, measure) where weight scales the measure value.

read_subject(subject_dir)[source]

Perform IO required to compute/fill the Measure. Will trigger the read_subject_on_parents function hook to populate the values of parent measures.

Parameters:
subject_dirPath

Path to the directory of the subject_dir (often subject_dir/subject_id).

Returns:
bool

Whether there was an update.

Notes

Might trigger a race condition if the function hook read_subject_on_parents depends on this method finishing first, e.g. because of thread availability.

set_args(parents=None, operation=None, **kwargs)[source]

Optionally update parents and/or operation string, then delegate to parent.

Parameters:
parentsstr, optional

Bracket-enclosed, comma-separated list of measure keys (with optional float weight prefix).

operationstr, optional

One of 'sum', 'ratio', or 'by_vox_vol'.

**kwargsstr

Additional keyword arguments forwarded to AbstractMeasure.set_args().

Raises:
ValueError

If operation is not a valid DerivedAggOperation.

property parents[source]

Iterable of the measures this measure depends on.

property read_subject_on_parents[source]

Read/Update the measures from subject_dir for all parent measures.

The object may delegate the lookup to measure_host, the Manager class that caches measures, if it is provided. This allows dependencies between measures and their automatic resolution.

Parameters:
subject_dirPath

Path to the directory of the subject_dir (often subject_dir/subject_id).

Returns:
bool

Whether there was an update in any of the parent measures.

property unit[source]

Property to access the unit attribute, also implements auto-generation of unit, if the stored unit is ‘from parents’.

Returns:
str

A string that identifies the unit of the Measure.

Raises:
RuntimeError

If unit is ‘from parents’ and some parent measures are inconsistent with each other.

class FastSurferCNN.utils.brainvolstats.ETIVMeasure(lta_file, name, description, unit, read_lta=None, etiv_scale_factor=None)[source]

Compute the eTIV based on the freesurfer talairach registration and lta.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Return a help string indicating the LTA file used.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read xfm or lta transform file.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([etiv_scale_factor])

Optionally update the eTIV scale factor and delegate to the parent.

Notes

Reimplemneted from freesurfer/mri_sclimbic_seg https://github.com/freesurfer/freesurfer/blob/ 3296e52f8dcffa740df65168722b6586adecf8cc/mri_sclimbic_seg/mri_sclimbic_seg#L627

help()[source]

Return a help string indicating the LTA file used.

set_args(etiv_scale_factor=None, **kwargs)[source]

Optionally update the eTIV scale factor and delegate to the parent.

Parameters:
etiv_scale_factorstr, optional

New eTIV scale factor (will be cast to float).

**kwargsstr

Additional keyword arguments forwarded to TransformMeasure.set_args().

class FastSurferCNN.utils.brainvolstats.ImportedMeasure(key, measurefile, name='N/A', description='N/A', unit='unitless', read_file=None, vox_vol=None)[source]

A Measure that implements reading measure values from a statsfile.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

assert_measurefile_absolute()

Assert that the Measure can be imported without a subject and subject_dir.

get_vox_vol()

Returns the voxel volume.

help()

Return a help string indicating where the measure is imported from.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read '# Measure <key> <name> <description> <value> <unit>'-entries from stats files.

read_subject(subject_dir)

Read the stats file and update the voxel volume if present.

set_args([key, measurefile])

Optionally update key and/or measurefile and delegate to the parent.

set_vox_vol(value)

Set the voxel volume.

assert_measurefile_absolute()[source]

Assert that the Measure can be imported without a subject and subject_dir.

Raises:
AssertionError
get_vox_vol()[source]

Returns the voxel volume.

Returns:
float

The voxel volume associated with the imported measure.

Raises:
RuntimeError

If the voxel volume was not defined.

help()[source]

Return a help string indicating where the measure is imported from.

static read_file(path)[source]

Read ‘# Measure <key> <name> <description> <value> <unit>’-entries from stats files.

Parameters:
pathPath

The path to the file to read from.

Returns:
dict[str, MeasureTuple]

A dictionary of Measure key to tuple of descriptors like {'<key>': ('<name>', '<description>', <value>, '<unit>')}.

read_subject(subject_dir)[source]

Read the stats file and update the voxel volume if present.

Parameters:
subject_dirPath

Path to the subject directory.

Returns:
bool

Whether the data was updated.

set_args(key=None, measurefile=None, **kwargs)[source]

Optionally update key and/or measurefile and delegate to the parent.

Parameters:
keystr, optional

New key to look up in the stats file.

measurefilestr, optional

New path to the stats file.

**kwargsstr

Additional keyword arguments forwarded to Measure.set_args().

set_vox_vol(value)[source]

Set the voxel volume.

Parameters:
valuefloat

Voxel volume in mm³.

class FastSurferCNN.utils.brainvolstats.Manager(measures, measurefile=None, segfile=None, on_missing='fail', legacy_freesurfer=False, aseg_replace=None)[source]

Attributes

default_measures

Iterable over measures typically included stats files in correct order.

voxel_class

A callable initializing a Volume-based Measure object with the legacy mode.

executor

Methods

add_computed_measure(measure_string)

Add a computed measure from the measure-string definition.

add_imported_measure(measure_string, **kwargs)

Add an imported measure from the measure_string definition and default measurefile.

assert_measure_need_subject()

Assert whether the measure expects a definition of the subject_dir.

clear()

Clear the file buffers.

compute_non_derived_pv([compute_threads])

Trigger computation of all non-derived, non-pv measures that are required.

copy()

default(key)

Returns the default Measure object for the measure with key key.

extract_key_args(measure)

Extract the name and options from a string like '<name>(<options_list>)'.

format_measures([fmt_func])

Formats all measures as strings and returns them as an iterable of str.

fromkeys(iterable[, value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

get_imported_all_measures()

Get the measures imported through the 'all' keyword.

get_virtual_labels(label_pool)

Get the virtual substitute labels that are required.

instantiate_measures(measures)

Recursively ensure all measures that measures depend on are instantiated.

items()

keys()

make_read_hook(read_func)

Wraps an io function to buffer results, multi-thread calls, etc.

needs_pv_calculation()

Returns whether the manager has PV-dependent measures.

pop(key[, default])

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem(/)

Remove and return a (key, value) pair as a 2-tuple.

print_measures([file])

Print the measures to stdout or file.

read_subject_parents(measures, subject_dir)

Multi-threaded iteration through measures and application of read_subject, also implementation for the read_subject_on_parents function hook.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

start_read_subject(subject_dir)

Start the threads to read the subject in subject_dir, pairs with wait_read_subject.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

update_measures()

Get the values to all measures (including imported via 'all').

update_pv_from_table(dataframe, merged_labels)

Update pv measures from dataframe and remove corresponding entries from the dataframe.

values()

wait_compute()

Wait for all pending computation processes and return their errors.

wait_read_subject()

Wait for all threads to finish reading the 'current' subject.

wait_write_brainvolstats(brainvol_statsfile)

Wait for measure computation to finish and write results to brainvol_statsfile.

with_subject(subjects_dir, subject_id)

Contextmanager for the start_read_subject and the wait_read_subject pair.

add_computed_measure(measure_string)[source]

Add a computed measure from the measure-string definition.

If a measure with the same key was previously added as imported, it is replaced by the computed version. Parsed arguments override the default configuration.

Parameters:
measure_stringstr

Measure name, optionally with parameters in the format '<name>(<param_list>)'.

add_imported_measure(measure_string, **kwargs)[source]

Add an imported measure from the measure_string definition and default measurefile.

Parameters:
measure_stringstr

Definition of the measure.

Other Parameters:
measurefilePath

Path to the default measurefile to import from (ImportedMeasure argument).

read_fileReadFileHook[dict[str, MeasureTuple]]

Function handle to read and parse the file (argument to ImportedMeasure).

vox_volfloat, optional

The voxel volume to associate the measure with.

Raises:
RuntimeError

If trying to replace a computed Measure of the same key.

assert_measure_need_subject()[source]

Assert whether the measure expects a definition of the subject_dir.

Raises:
AssertionError
clear()[source]

Clear the file buffers.

compute_non_derived_pv(compute_threads=None)[source]

Trigger computation of all non-derived, non-pv measures that are required.

Parameters:
compute_threadsconcurrent.futures.Executor, optional

An Executor object to perform the computation of measures, if an Executor object is passed, the computation of measures is submitted to the Executor object. If not, measures are computed in the main thread.

Returns:
list[Future[int | float]]

For each non-derived and non-PV measure, a future object that is associated with the call to the measure.

default(key)[source]

Returns the default Measure object for the measure with key key.

Parameters:
keystr

The key name of the Measure.

Returns:
AbstractMeasure

The Measure object initialized with default values.

Notes

Supported keys are: lhSurfaceHoles, rhSurfaceHoles, and SurfaceHoles The number of holes in the surfaces. lhPialTotal, and rhPialTotal The volume enclosed in the pial surfaces. lhWhiteMatterVol, and rhWhiteMatterVol The Volume of the white matter in the segmentation (incl. lateralized WM-hypo). lhWhiteMatterTotal, and rhWhiteMatterTotal The volume enclosed in the white matter surfaces. lhCortex, rhCortex, and Cortex The volume between the pial and the white matter surfaces. CorpusCallosumVol The volume of the corpus callosum in the segmentation. lhWM-hypointensities, and rhWM-hypointensities The volume of unlateralized the white matter hypointensities in the segmentation, but lateralized by neighboring voxels (FreeSurfer uses talairach coordinates to re-lateralize). lhCerebralWhiteMatter, rhCerebralWhiteMatter, and CerebralWhiteMatter The volume of the cerebral white matter in the segmentation (including corpus callosum split evenly into left and right and white matter and WM-hypo). CerebellarGM The volume of the cerbellar gray matter in the segmentation. CerebellarWM The volume of the cerbellar white matter in the segmentation. SubCortGray The volume of the subcortical gray matter in the segmentation. TotalGray The total gray matter volume in the segmentation. TFFC The volume of the 3rd-5th ventricles and CSF in the segmentation. VentricleChoroidVol The volume of the choroid plexus and inferiar and lateral ventricles and CSF. BrainSeg The volume of all brain structures in the segmentation. BrainSegNotVent, and BrainSegNotVentSurf The brain segmentation volume without ventricles. Cerebellum The total cerebellar volume. SupraTentorial, SupraTentorialNotVent, and SupraTentorialNotVentVox The supratentorial brain volume/voxel count (without centricles and CSF). Mask The volume of the brain mask. EstimatedTotalIntraCranialVol The eTIV estimate (via talairach registration). BrainSegVol-to-eTIV, and MaskVol-to-eTIV The ratios of the brain segmentation volume and the mask volume with respect to the eTIV estimate.

extract_key_args(measure)[source]

Extract the name and options from a string like ‘<name>(<options_list>)’.

The ‘<option_list>’ is optional and is similar to python parameters. It starts with numbered parameters, followed by key-value pairs.

Examples: 'Mask(mri/aseg.mgz)' returns: ('Mask', ['mri/aseg.mgz', 'classes=[2, 4]']) 'TotalGray(mri/aseg.mgz, classes=[2, 4])' returns: ('TotalGray', ['mri/aseg.mgz', 'classes=[2, 4]']) 'BrainSeg(segfile=mri/aseg.mgz, classes=[2, 4])' returns: ('BrainSeg', ['segfile=mri/aseg.mgz', 'classes=[2, 4]'])

Parameters:
measurestr

The measure string of the format ‘<name>’ or ‘<name>(<list of parameters>)’.

Returns:
keystr

The name of the measure.

argslist[str]

A list of options.

Raises:
ValueError

If the string measure does not conform to the format requirements.

format_measures(fmt_func=<function format_measure>)[source]

Formats all measures as strings and returns them as an iterable of str.

In the output, measures are ordered in the order they are added to the Manager object. Finally, the “all”-imported Measures are appended.

Parameters:
fmt_funccallable(), optional

Function to format the key and a MeasureTuple object into a string (default: function format_measure).

Returns:
Iterable[str]

An iterable of the measure strings.

get_imported_all_measures()[source]

Get the measures imported through the ‘all’ keyword.

Returns:
dict[str, MeasureTuple]

A dictionary of Measure keys and tuples of name, description, value, unit.

get_virtual_labels(label_pool)[source]

Get the virtual substitute labels that are required.

Parameters:
label_poolIterable[int]

An iterable over available labels.

Returns:
dict[int, list[int]]

A dictionary of key-value pairs of new label and a list of labels this represents.

instantiate_measures(measures)[source]

Recursively ensure all measures that measures depend on are instantiated.

Parameters:
measuresIterable[AbstractMeasure]

The measures to check; DerivedMeasure parents are visited recursively.

make_read_hook(read_func)[source]

Wraps an io function to buffer results, multi-thread calls, etc.

Parameters:
read_funcCallable[[Path], T_BufferType]

Function to read Measure entries/ images/ surfaces from a file.

Returns:
wrapped_funcReadFileHook[T_BufferType]

The returned function takes two arguments: the path to the file (cache) read and an optional bool blocking argument (default: True). If blocking=False, the data is preloaded without waiting and None is returned; otherwise the output of read_func is returned.

needs_pv_calculation()[source]

Returns whether the manager has PV-dependent measures.

Returns:
bool

Whether the manager has PVMeasure children.

print_measures(file=None)[source]

Print the measures to stdout or file.

Parameters:
fileTextIO, optional

The file object to write to. If None, writes to stdout.

read_subject_parents(measures, subject_dir, blocking=False)[source]

Multi-threaded iteration through measures and application of read_subject, also implementation for the read_subject_on_parents function hook. Guaranteed to return independent of state and thread availability to avoid a race condition.

Parameters:
measuresIterable[AbstractMeasure]

Iterable of Measures to read.

subject_dirPath

Path to the subject directory (often subjects_dir/subject_id).

blockingbool, default=False

Whether the execution should be parallel or not.

Returns:
bool

Always returns True.

start_read_subject(subject_dir)[source]

Start the threads to read the subject in subject_dir, pairs with wait_read_subject.

Parameters:
subject_dirPath

The path to the directory of the subject (with folders ‘mri’, ‘stats’, …).

update_measures()[source]

Get the values to all measures (including imported via ‘all’).

Returns:
dict[str, Union[float, int]]

A dictionary of ‘<key>’ (the Measure key) and the associated value.

update_pv_from_table(dataframe, merged_labels)[source]

Update pv measures from dataframe and remove corresponding entries from the dataframe.

Parameters:
dataframepd.DataFrame

The dataframe object with the PV values.

merged_labelsdict[int, list[int]]

Mapping from PVMeasure proxy label to list of labels it merges.

Returns:
pd.DataFrame

A dataframe object, where label ‘groups’ used for updates and in merged_labels are removed, i.e. those labels added for PVMeasure objects.

Raises:
RuntimeError
wait_compute()[source]

Wait for all pending computation processes and return their errors.

Also resets the internal compute futures.

Returns:
Sequence[BaseException]

The errors raised in the computations.

wait_read_subject()[source]

Wait for all threads to finish reading the ‘current’ subject.

Raises:
Exception

The first exception encountered during the read operation.

wait_write_brainvolstats(brainvol_statsfile)[source]

Wait for measure computation to finish and write results to brainvol_statsfile.

Parameters:
brainvol_statsfilePath

The file to write the measures to.

Raises:
RuntimeError

If errors occurred during measure computation.

with_subject(subjects_dir, subject_id)[source]

Contextmanager for the start_read_subject and the wait_read_subject pair.

If one value is None, it is assumed the subject_dir and subject_id are not needed, for example because all file names are given by absolute paths.

Parameters:
subjects_dirPath, None

The path to the directory of the subject (with folders ‘mri’, ‘stats’, …).

subject_idstr, None

The subject_id identifying folder of the subjects_dir.

Raises:
AssertionError

If subjects_dir and or subject_id are needed.

property default_measures[source]

Iterable over measures typically included stats files in correct order.

Returns:
Iterable[str]

An ordered iterable of the default Measure keys.

property voxel_class[source]

A callable initializing a Volume-based Measure object with the legacy mode.

Returns:
type[AbstractMeasure]

A callable to create an object to perform a Volume-based Measure.

class FastSurferCNN.utils.brainvolstats.MaskMeasure(maskfile, name, description, unit='unitless', threshold=0.5, read_file=None)[source]

A VolumeMeasure that thresholds a continuous mask image to produce a binary mask.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

get_vox_vol()

Return the voxel volume from the image header.

help()

Return a help string describing the classes/condition and source file.

mask(data)

Generate a binary mask by thresholding data.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read a volume from disk.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([maskfile, threshold])

Optionally update the mask file and/or threshold, then delegate to parent.

mask(data)[source]

Generate a binary mask by thresholding data.

Parameters:
datanp.ndarray

Input array (e.g. mask or probability image).

Returns:
np.ndarray

Boolean array, True where data > threshold.

set_args(maskfile=None, threshold=None, **kwargs)[source]

Optionally update the mask file and/or threshold, then delegate to parent.

Parameters:
maskfilePath, optional

New path for the mask file.

thresholdfloat, optional

New threshold value.

**kwargsstr

Additional keyword arguments forwarded to VolumeMeasure.set_args().

class FastSurferCNN.utils.brainvolstats.Measure(file, name, description, unit, read_hook)[source]

Class to buffer computed values, buffers computed values. Implements a value buffering interface for computed measure values and implement the read_subject pattern.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Compiles a help message for the measure describing the measure's settings.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([file])

Optionally update the file path and delegate remaining kwargs to the parent.

read_subject(subject_dir)[source]

Perform IO required to compute/fill the Measure. Delegates file reading to read_hook (set in __init__).

Parameters:
subject_dirPath

Path to the directory of the subject (often subjects_dir/subject_id).

Returns:
bool

Whether there was an update to the data.

set_args(file=None, **kwargs)[source]

Optionally update the file path and delegate remaining kwargs to the parent.

Parameters:
filestr, optional

New path for the data file.

**kwargsstr

Additional keyword arguments forwarded to AbstractMeasure.set_args().

class FastSurferCNN.utils.brainvolstats.NullMeasure(name, description, unit)[source]

A Measure that supports no operations, always returns a value of zero.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Compute and return the value of the measure.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Compiles a help message for the measure describing the measure's settings.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args(**kwargs)

Set the arguments of the Measure.

help()[source]

Compiles a help message for the measure describing the measure’s settings.

Returns:
str

A help string describing the Measure settings.

class FastSurferCNN.utils.brainvolstats.PVMeasure(classes, name, description, unit='mm^3')[source]

Class to compute volume for segmentations (includes PV-correction).

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

vox_vol

Voxel volume in mm³ used to convert voxel counts to physical volume.

read_file

Methods

__call__()

Return the partial-volume corrected measure value.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Return a help string describing the PV label classes.

labels()

Return the list of segmentation label classes for this measure.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([classes])

Optionally update the classes and delegate to the parent.

update_data(value)

Store the PV result row from the segmentation stats DataFrame.

help()[source]

Return a help string describing the PV label classes.

labels()[source]

Return the list of segmentation label classes for this measure.

Returns:
list[int]

The label indices.

set_args(classes=None, **kwargs)[source]

Optionally update the classes and delegate to the parent.

Parameters:
classesstr, optional

Space-separated list of integer label classes.

**kwargsstr

Additional keyword arguments forwarded to AbstractMeasure.set_args().

update_data(value)[source]

Store the PV result row from the segmentation stats DataFrame.

Parameters:
valuepd.Series

A row from the PV stats DataFrame containing at least 'NVoxels' and 'Volume_mm3' columns.

property vox_vol[source]

Voxel volume in mm³ used to convert voxel counts to physical volume.

class FastSurferCNN.utils.brainvolstats.ReadFileHook(*args, **kwargs)[source]

Protocol for a buffered file-reading hook returned by Manager.make_read_hook().

Methods

__call__(file[, b])

Call self as a function.

class FastSurferCNN.utils.brainvolstats.SurfaceHoles(surface_file, name, description, unit, read_mesh=None)[source]

Measure computing the number of topological holes of a surface.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Return a help string indicating the source surface file.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read a mesh from disk.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([surface_file])

Optionally update the surface file path and delegate to the parent.

help()[source]

Return a help string indicating the source surface file.

class FastSurferCNN.utils.brainvolstats.SurfaceMeasure(surface_file, name, description, unit, read_mesh=None)[source]

Class to implement default surface IO and shared surface-measure initialization.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Compiles a help message for the measure describing the measure's settings.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read a mesh from disk.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([surface_file])

Optionally update the surface file path and delegate to the parent.

static read_file(path)[source]

Read a mesh from disk.

Parameters:
pathPath

The path to the file.

Returns:
lapy.TriaMesh

The mesh object read from the file.

set_args(surface_file=None, **kwargs)[source]

Optionally update the surface file path and delegate to the parent.

Parameters:
surface_filestr, optional

New path for the surface file.

**kwargsstr

Additional keyword arguments forwarded to Measure.set_args().

class FastSurferCNN.utils.brainvolstats.SurfaceVolume(surface_file, name, description, unit, read_mesh=None)[source]

Measure computing the enclosed volume of a closed surface mesh.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Return a help string indicating the source surface file.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read a mesh from disk.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([surface_file])

Optionally update the surface file path and delegate to the parent.

help()[source]

Return a help string indicating the source surface file.

class FastSurferCNN.utils.brainvolstats.TransformMeasure(lta_file, name, description, unit, read_lta=None)[source]

Abstract base class for measures derived from an affine transform file (LTA or XFM).

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

help()

Compiles a help message for the measure describing the measure's settings.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read xfm or lta transform file.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([lta_file])

Optionally update the LTA file path and delegate to the parent.

static read_file(path)[source]

Read xfm or lta transform file.

Parameters:
pathPath

The path to the file.

Returns:
tal

The talairach transform matrix.

set_args(lta_file=None, **kwargs)[source]

Optionally update the LTA file path and delegate to the parent.

Parameters:
lta_filestr, optional

New path for the LTA or XFM transform file.

**kwargsstr

Additional keyword arguments forwarded to Measure.set_args().

class FastSurferCNN.utils.brainvolstats.VolumeMeasure(segfile, classes_or_cond, name, description, unit='unitless', read_file=None)[source]

Counts voxels belonging to a class (or condition expression) in a segmentation volume.

Attributes

description

The human-readable description of the measure.

name

The short name of the measure.

subject_dir

The subject directory last passed to read_subject(), or None.

unit

The unit string of the measure, e.g. 'mm^3' or 'unitless'.

Methods

__call__()

Return the cached computed value, re-computing if the subject has changed.

as_tuple()

Return the measure as a MeasureTuple (name, description, value, unit).

get_vox_vol()

Return the voxel volume from the image header.

help()

Return a help string describing the classes/condition and source file.

parse_args(*args)

Parse additional args defining the behavior of the Measure.

read_file(path)

Read a volume from disk.

read_subject(subject_dir)

Perform IO required to compute/fill the Measure.

set_args([segfile, classes])

Optionally update the segmentation file and/or classes, then delegate to parent.

get_vox_vol()[source]

Return the voxel volume from the image header.

Returns:
float

Product of the voxel zooms in mm³.

help()[source]

Return a help string describing the classes/condition and source file.

static read_file(path)[source]

Read a volume from disk.

Parameters:
pathPath

The path to the file to read from.

Returns:
ImageTuple

A tuple of nibabel image object and the data.

set_args(segfile=None, classes=None, **kwargs)[source]

Optionally update the segmentation file and/or classes, then delegate to parent.

Parameters:
segfilestr, optional

New path for the segmentation file.

classesstr, optional

Whitespace-separated list of integer label classes.

**kwargsstr

Additional keyword arguments forwarded to Measure.set_args().

class FastSurferCNN.utils.brainvolstats.VoxelClassGenerator(*args, **kwargs)[source]

Generator for voxel-based metric Measures.

Methods

__call__(classes, name, description, unit)

Create a voxel-based Measure for the given label classes.

FastSurferCNN.utils.brainvolstats.format_classes(_classes)[source]

Formats an iterable of classes. This compresses consecutive integers into ranges. >>> format_classes([1, 2, 3, 6]) # ‘1-3,6’

Parameters:
_classesIterable[int]

An iterable of integers.

Returns:
str

A string of sorted integers and integer ranges, '()' if iterable is empty, or just the string conversion of _classes, if _classes is not an iterable.

Notes

This function will likely be moved to a different file.

FastSurferCNN.utils.brainvolstats.format_measure(key, data)[source]

Format a single measure entry as a # Measure stats-file line.

Parameters:
keystr

The measure key.

dataMeasureTuple

A tuple of (name, description, value, unit).

Returns:
str

A formatted string '# Measure <key>, <name>, <description>, <value>, <unit>'.

FastSurferCNN.utils.brainvolstats.hemi_masks_from_aseg(arr, window_size=7)[source]

Determine for each voxel if it is more likely left hemisphere or right hemisphere.

Parameters:
arrndarray of int

An array with segmentation labels.

window_sizeint, default=7

The size of the smoothing filter to use for left/right voting.

Returns:
mask_leftnp.ndarray of bool

A boolean array of the same shape as arr, where True indicates voxels that are more likely to belong to the left hemisphere.

mask_rightnp.ndarray of bool

A boolean array of the same shape as arr, where True indicates voxels that are more likely to belong to the right hemisphere.

Notes

Classes (2, 3, 4, 5, 7, 8, 10, 11, 12, 13, 17, 18, 26, 28, 30, 31) vote left and classes (41, 42, 43, 44, 46, 47, 49, 50, 51, 52, 53, 54, 58, 60, 62, 63) vote right.

FastSurferCNN.utils.brainvolstats.mask_in_array(arr, items, /, max_index=None)[source]

Efficient function to generate a mask of elements in arr, which are also in items.

Parameters:
arrndarray of int

An array with data, most likely int.

itemsnpt.ArrayLike

Which elements of arr in arr should yield True.

max_indexint, optional

The maximum value of arr and items for performance, uses maximum value if None.

Returns:
masknp.ndarray of bool

A binary array, true, where elements in arr are in items.

See also

mask_not_in_array

Inverse mask, true where elements are not in items.

FastSurferCNN.utils.brainvolstats.mask_not_in_array(arr, items, /, max_index=None)[source]

Inverse of mask_in_array.

Parameters:
arrndarray of int

An array with data, most likely int.

itemsnpt.ArrayLike

Which elements of arr in arr should yield False.

max_indexint, optional

The maximum value of arr and items for performance, uses maximum value if None.

Returns:
masknp.ndarray of bool

A binary array, true, where elements in arr are not in items.

See also

mask_in_array

Mask where elements are in items.

FastSurferCNN.utils.brainvolstats.read_lta_transform_file(path)[source]

Read and extract the first lta transform from an LTA file.

Parameters:
pathPath

The path of the LTA file.

Returns:
matrixAffineMatrix4x4

Matrix of shape (4, 4).

FastSurferCNN.utils.brainvolstats.read_measure_file(path)[source]

Read ‘# Measure <key> <name> <description> <value> <unit>’-entries from stats files.

Parameters:
pathPath

The path to the file to read from.

Returns:
dict[str, MeasureTuple]

A dictionary of Measure key to tuple of descriptors like {'<key>': ('<name>', '<description>', <value>, '<unit>')}.

FastSurferCNN.utils.brainvolstats.read_mesh_file(path)[source]

Read a mesh from disk.

Parameters:
pathPath

The path to the file.

Returns:
lapy.TriaMesh

The mesh object read from the file.

FastSurferCNN.utils.brainvolstats.read_transform_file(path)[source]

Read xfm or lta transform file.

Parameters:
pathPath

The path to the file.

Returns:
tal

The talairach transform matrix.

FastSurferCNN.utils.brainvolstats.read_volume_file(path)[source]

Read a volume from disk.

Parameters:
pathPath

The path to the file to read from.

Returns:
ImageTuple

A tuple of nibabel image object and the data.

FastSurferCNN.utils.brainvolstats.read_xfm_transform_file(path)[source]

Read XFM talairach transform.

Parameters:
pathstr | Path

The filename/path of the transform file.

Returns:
talAffineMatrix4x4

The talairach transform matrix.

Raises:
ValueError

If the file is of an invalid format.