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
The human-readable description of the measure.
The short name of the measure.
The subject directory last passed to
read_subject(), orNone.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:
strA help string describing the Measure settings.
- parse_args(*args)[source]¶
Parse additional args defining the behavior of the Measure.
- Parameters:
- *args
str Each args can be a string of ‘<value>’ (arg-style) and ‘<keyword>=<value>’ (keyword-arg-style), arg-style cannot follow keyword-arg-style args.
- *args
- Raises:
ValueErrorIf there are more arguments than registered argument names.
RuntimeErrorIf an arg-style follows a keyword-arg-style argument, or if a keyword value is redefined, or a keyword is not valid.
- set_args(**kwargs)[source]¶
Set the arguments of the Measure.
- Raises:
ValueErrorIf there are unrecognized keyword arguments.
- property subject_dir[source]¶
The subject directory last passed to
read_subject(), orNone.
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
Iterable of the measures this measure depends on.
Read/Update the measures from subject_dir for all parent measures.
subject_dirThe subject directory last passed to
read_subject(), orNone.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).Return the voxel volume of the first parent measure.
help()Return a human-readable formula string for the derived measure.
Return a RuntimeError for an invalid number of parents for the
'ratio'operation.Return a RuntimeError for an invalid number of parents for
'by_vox_vol'.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.
- invalid_len_ratio()[source]¶
Return a RuntimeError for an invalid number of parents for the
'ratio'operation.- Returns:
RuntimeErrorError 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:
RuntimeErrorError 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)whereweightscales 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_dir
Path Path to the directory of the subject_dir (often subject_dir/subject_id).
- subject_dir
- Returns:
boolWhether there was an update.
Notes
Might trigger a race condition if the function hook
read_subject_on_parentsdepends 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:
- parents
str,optional Bracket-enclosed, comma-separated list of measure keys (with optional float weight prefix).
- operation
str,optional One of
'sum','ratio', or'by_vox_vol'.- **kwargs
str Additional keyword arguments forwarded to
AbstractMeasure.set_args().
- parents
- Raises:
ValueErrorIf
operationis not a validDerivedAggOperation.
- 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.
- property unit[source]¶
Property to access the unit attribute, also implements auto-generation of unit, if the stored unit is ‘from parents’.
- Returns:
strA string that identifies the unit of the Measure.
- Raises:
RuntimeErrorIf 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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
- set_args(etiv_scale_factor=None, **kwargs)[source]¶
Optionally update the eTIV scale factor and delegate to the parent.
- Parameters:
- etiv_scale_factor
str,optional New eTIV scale factor (will be cast to
float).- **kwargs
str Additional keyword arguments forwarded to
TransformMeasure.set_args().
- etiv_scale_factor
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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 that the Measure can be imported without a subject and subject_dir.
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
keyand/ormeasurefileand 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:
- get_vox_vol()[source]¶
Returns the voxel volume.
- Returns:
floatThe voxel volume associated with the imported measure.
- Raises:
RuntimeErrorIf the voxel volume was not defined.
- static read_file(path)[source]¶
Read ‘# Measure <key> <name> <description> <value> <unit>’-entries from stats files.
- set_args(key=None, measurefile=None, **kwargs)[source]¶
Optionally update
keyand/ormeasurefileand delegate to the parent.- Parameters:
- key
str,optional New key to look up in the stats file.
- measurefile
str,optional New path to the stats file.
- **kwargs
str Additional keyword arguments forwarded to
Measure.set_args().
- key
- class FastSurferCNN.utils.brainvolstats.Manager(measures, measurefile=None, segfile=None, on_missing='fail', legacy_freesurfer=False, aseg_replace=None)[source]¶
Attributes
Iterable over measures typically included stats files in correct order.
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 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 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
measuresdepend on are instantiated.items()keys()make_read_hook(read_func)Wraps an io function to buffer results, multi-thread calls, etc.
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]
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 for all pending computation processes and return their errors.
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_subjectand thewait_read_subjectpair.- 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_string
str Measure name, optionally with parameters in the format
'<name>(<param_list>)'.
- measure_string
- add_imported_measure(measure_string, **kwargs)[source]¶
Add an imported measure from the measure_string definition and default measurefile.
- Parameters:
- measure_string
str Definition of the measure.
- measure_string
- Other Parameters:
- measurefile
Path Path to the default measurefile to import from (ImportedMeasure argument).
- read_file
ReadFileHook[dict[str,MeasureTuple]] Function handle to read and parse the file (argument to ImportedMeasure).
- vox_vol
float,optional The voxel volume to associate the measure with.
- measurefile
- Raises:
RuntimeErrorIf 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:
- compute_non_derived_pv(compute_threads=None)[source]¶
Trigger computation of all non-derived, non-pv measures that are required.
- Parameters:
- compute_threads
concurrent.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.
- compute_threads
- Returns:
- default(key)[source]¶
Returns the default Measure object for the measure with key
key.- Parameters:
- key
str The key name of the Measure.
- key
- Returns:
AbstractMeasureThe Measure object initialized with default values.
Notes
Supported keys are:
lhSurfaceHoles,rhSurfaceHoles, andSurfaceHolesThe number of holes in the surfaces.lhPialTotal, andrhPialTotalThe volume enclosed in the pial surfaces.lhWhiteMatterVol, andrhWhiteMatterVolThe Volume of the white matter in the segmentation (incl. lateralized WM-hypo).lhWhiteMatterTotal, andrhWhiteMatterTotalThe volume enclosed in the white matter surfaces.lhCortex,rhCortex, andCortexThe volume between the pial and the white matter surfaces.CorpusCallosumVolThe volume of the corpus callosum in the segmentation.lhWM-hypointensities, andrhWM-hypointensitiesThe volume of unlateralized the white matter hypointensities in the segmentation, but lateralized by neighboring voxels (FreeSurfer uses talairach coordinates to re-lateralize).lhCerebralWhiteMatter,rhCerebralWhiteMatter, andCerebralWhiteMatterThe volume of the cerebral white matter in the segmentation (including corpus callosum split evenly into left and right and white matter and WM-hypo).CerebellarGMThe volume of the cerbellar gray matter in the segmentation.CerebellarWMThe volume of the cerbellar white matter in the segmentation.SubCortGrayThe volume of the subcortical gray matter in the segmentation.TotalGrayThe total gray matter volume in the segmentation.TFFCThe volume of the 3rd-5th ventricles and CSF in the segmentation.VentricleChoroidVolThe volume of the choroid plexus and inferiar and lateral ventricles and CSF.BrainSegThe volume of all brain structures in the segmentation.BrainSegNotVent, andBrainSegNotVentSurfThe brain segmentation volume without ventricles.CerebellumThe total cerebellar volume.SupraTentorial,SupraTentorialNotVent, andSupraTentorialNotVentVoxThe supratentorial brain volume/voxel count (without centricles and CSF).MaskThe volume of the brain mask.EstimatedTotalIntraCranialVolThe eTIV estimate (via talairach registration).BrainSegVol-to-eTIV, andMaskVol-to-eTIVThe 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:
- measure
str The measure string of the format ‘<name>’ or ‘<name>(<list of parameters>)’.
- measure
- Returns:
- Raises:
ValueErrorIf the string
measuredoes 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_func
callable(),optional Function to format the key and a MeasureTuple object into a string (default: function
format_measure).
- fmt_func
- Returns:
Iterable[str]An iterable of the measure strings.
- instantiate_measures(measures)[source]¶
Recursively ensure all measures that
measuresdepend on are instantiated.- Parameters:
- measures
Iterable[AbstractMeasure] The measures to check;
DerivedMeasureparents are visited recursively.
- measures
- make_read_hook(read_func)[source]¶
Wraps an io function to buffer results, multi-thread calls, etc.
- Parameters:
- read_func
Callable[[Path],T_BufferType] Function to read Measure entries/ images/ surfaces from a file.
- read_func
- Returns:
- wrapped_func
ReadFileHook[T_BufferType] The returned function takes two arguments: the path to the
file(cache) read and an optional boolblockingargument (default:True). Ifblocking=False, the data is preloaded without waiting andNoneis returned; otherwise the output ofread_funcis returned.
- wrapped_func
- needs_pv_calculation()[source]¶
Returns whether the manager has PV-dependent measures.
- Returns:
boolWhether the manager has PVMeasure children.
- print_measures(file=None)[source]¶
Print the measures to stdout or file.
- Parameters:
- file
TextIO,optional The file object to write to. If None, writes to stdout.
- file
- 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:
- measures
Iterable[AbstractMeasure] Iterable of Measures to read.
- subject_dir
Path Path to the subject directory (often subjects_dir/subject_id).
- blocking
bool, default=False Whether the execution should be parallel or not.
- measures
- Returns:
boolAlways 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_dir
Path The path to the directory of the subject (with folders ‘mri’, ‘stats’, …).
- subject_dir
- update_pv_from_table(dataframe, merged_labels)[source]¶
Update pv measures from dataframe and remove corresponding entries from the dataframe.
- Parameters:
- Returns:
pd.DataFrameA dataframe object, where label ‘groups’ used for updates and in
merged_labelsare removed, i.e. those labels added for PVMeasure objects.
- Raises:
- 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:
ExceptionThe 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_statsfile
Path The file to write the measures to.
- brainvol_statsfile
- Raises:
RuntimeErrorIf errors occurred during measure computation.
- with_subject(subjects_dir, subject_id)[source]¶
Contextmanager for the
start_read_subjectand thewait_read_subjectpair.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:
- Raises:
AssertionErrorIf 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
VolumeMeasurethat thresholds a continuous mask image to produce a binary mask.Attributes
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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:
- data
np.ndarray Input array (e.g. mask or probability image).
- data
- Returns:
np.ndarrayBoolean array,
Truewheredata > threshold.
- set_args(maskfile=None, threshold=None, **kwargs)[source]¶
Optionally update the mask file and/or threshold, then delegate to parent.
- Parameters:
- maskfile
Path,optional New path for the mask file.
- threshold
float,optional New threshold value.
- **kwargs
str Additional keyword arguments forwarded to
VolumeMeasure.set_args().
- maskfile
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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__).
- set_args(file=None, **kwargs)[source]¶
Optionally update the file path and delegate remaining kwargs to the parent.
- Parameters:
- file
str,optional New path for the data file.
- **kwargs
str Additional keyword arguments forwarded to
AbstractMeasure.set_args().
- file
- class FastSurferCNN.utils.brainvolstats.NullMeasure(name, description, unit)[source]¶
A Measure that supports no operations, always returns a value of zero.
Attributes
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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.
- class FastSurferCNN.utils.brainvolstats.PVMeasure(classes, name, description, unit='mm^3')[source]¶
Class to compute volume for segmentations (includes PV-correction).
Attributes
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe unit string of the measure, e.g.
'mm^3'or'unitless'.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.
- set_args(classes=None, **kwargs)[source]¶
Optionally update the classes and delegate to the parent.
- Parameters:
- classes
str,optional Space-separated list of integer label classes.
- **kwargs
str Additional keyword arguments forwarded to
AbstractMeasure.set_args().
- classes
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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.
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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:
- path
Path The path to the file.
- path
- Returns:
lapy.TriaMeshThe 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_file
str,optional New path for the surface file.
- **kwargs
str Additional keyword arguments forwarded to
Measure.set_args().
- surface_file
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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.
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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:
- path
Path The path to the file.
- path
- Returns:
talThe talairach transform matrix.
- set_args(lta_file=None, **kwargs)[source]¶
Optionally update the LTA file path and delegate to the parent.
- Parameters:
- lta_file
str,optional New path for the LTA or XFM transform file.
- **kwargs
str Additional keyword arguments forwarded to
Measure.set_args().
- lta_file
- 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
descriptionThe human-readable description of the measure.
nameThe short name of the measure.
subject_dirThe subject directory last passed to
read_subject(), orNone.unitThe 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).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:
floatProduct of the voxel zooms in mm³.
- static read_file(path)[source]¶
Read a volume from disk.
- Parameters:
- path
Path The path to the file to read from.
- path
- Returns:
ImageTupleA 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:
- segfile
str,optional New path for the segmentation file.
- classes
str,optional Whitespace-separated list of integer label classes.
- **kwargs
str Additional keyword arguments forwarded to
Measure.set_args().
- segfile
- 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:
- _classes
Iterable[int] An iterable of integers.
- _classes
- Returns:
strA string of sorted integers and integer ranges,
'()'if iterable is empty, or just the string conversion of_classes, if_classesis 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
# Measurestats-file line.
- 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:
- Returns:
- mask_left
np.ndarrayofbool A boolean array of the same shape as
arr, where True indicates voxels that are more likely to belong to the left hemisphere.- mask_right
np.ndarrayofbool A boolean array of the same shape as
arr, where True indicates voxels that are more likely to belong to the right hemisphere.
- mask_left
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:
- Returns:
- mask
np.ndarrayofbool A binary array, true, where elements in
arrare initems.
- mask
See also
mask_not_in_arrayInverse 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:
- Returns:
- mask
np.ndarrayofbool A binary array, true, where elements in
arrare not initems.
- mask
See also
mask_in_arrayMask 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:
- path
Path The path of the LTA file.
- path
- Returns:
- matrix
AffineMatrix4x4 Matrix of shape (4, 4).
- matrix
- FastSurferCNN.utils.brainvolstats.read_measure_file(path)[source]¶
Read ‘# Measure <key> <name> <description> <value> <unit>’-entries from stats files.
- FastSurferCNN.utils.brainvolstats.read_mesh_file(path)[source]¶
Read a mesh from disk.
- Parameters:
- path
Path The path to the file.
- path
- Returns:
lapy.TriaMeshThe mesh object read from the file.
- FastSurferCNN.utils.brainvolstats.read_transform_file(path)[source]¶
Read xfm or lta transform file.
- Parameters:
- path
Path The path to the file.
- path
- Returns:
talThe talairach transform matrix.
- FastSurferCNN.utils.brainvolstats.read_volume_file(path)[source]¶
Read a volume from disk.
- Parameters:
- path
Path The path to the file to read from.
- path
- Returns:
ImageTupleA tuple of nibabel image object and the data.
- FastSurferCNN.utils.brainvolstats.read_xfm_transform_file(path)[source]¶
Read XFM talairach transform.
- Parameters:
- Returns:
- tal
AffineMatrix4x4 The talairach transform matrix.
- tal
- Raises:
ValueErrorIf the file is of an invalid format.