FastSurferCNN.segstats

class FastSurferCNN.segstats.HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]

Help formatter that forces line breaks in texts where the text is <br>.

Methods

format_help()

start_section(heading)

add_argument

add_arguments

add_text

add_usage

end_section

class FastSurferCNN.segstats.PVStats[source]

Dictionary of volume statistics for partial volume evaluation and global stats

Methods

clear()

copy()

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.

items()

keys()

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.

setdefault(key[, default])

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

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: 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]

values()

FastSurferCNN.segstats.add_measure_parser(subparser_callback)[source]

Add a parser that supports adding measures to the parameters.

FastSurferCNN.segstats.add_two_help_messages(parser)[source]

Adds separate help flags -h and –help to the parser for simple and detailed help. Both trigger the help action.

Parameters:
parserargparse.ArgumentParser

Parser to add the flags to.

FastSurferCNN.segstats.borders(_array, labels, max_label=None, six_connected=True, out=None)[source]

Handle to fast border computation.

This is an efficient implementation, for multiple/many classes between which borders should be computed.

Parameters:
_array_ArrayType

Input labeled image or binary image.

labelsIterable[int], bool

List of labels for which borders will be computed. If labels is True, _array is treated as a binary mask.

max_labelint, optional

The maximum label to consider. If None, the maximum label in the array is used.

six_connectedbool, default=True

If True, 6-connected borders (must share a face) are computed, otherwise 26-connected borders (must share a vertex) are computed.

outnpt.NDArray[bool], optional

Output array to store the computed borders.

Returns:
npt.NDArray[bool]

Binary mask of border voxels.

Raises:
ValueError

If labels does not fit to _array (binary mask and integer and vice-versa).

FastSurferCNN.segstats.calculate_merged_labels(merged_labels, voxel_counts, robust_voxel_counts, volumes, mins=None, maxes=None, sums=None, sums_of_squares=None, eps=1e-06)[source]

Calculate the statistics for meta-labels, i.e. labels based on other labels (merge_labels). Add respective items to table.

Parameters:
merged_labelsVirtualLabel

A dictionary of key ‘merged id’ to value list of ids it references.

voxel_countsdict[int, int]

A dict of voxel counts for labels in the image/referenced in merged_labels.

robust_voxel_countsdict[int, int]

A dict of the robust number of voxels referenced in merged_labels.

volumesdict[int, float]

A dict of the volumes associated with each label.

minsdict[int, float], optional

A dict of the minimum intensity associated with each label.

maxesdict[int, float], optional

A dict of the minimum intensity associated with each label.

sumsdict[int, float], optional

A dict of the sums of voxel intensities associated with each label.

sums_of_squaresdict[int, float], optional

A dict of the sums of squares of voxel intensities associated with each label.

epsfloat, default=1e-6

An epsilon value for numeric stability.

Yields:
PVStats

A dictionary per entry in merged_labels.

FastSurferCNN.segstats.check_shape_affine(img1, img2, name1, name2)[source]

Check whether the shape and affine of

Parameters:
img1nibabel.SpatialImage

Image 1.

img2nibabel.SpatialImage

Image 2.

name1str

Name of image 1.

name2str

Name of image 2.

Raises:
RuntimeError

If shapes or affines are not the same.

FastSurferCNN.segstats.crop_patch_to_mask(mask, sub_patch=None)[source]

Crop the patch to regions of the mask that are non-zero.

Assumes mask is always positive. Returns whether there is any mask>0 in the patch and a slicer/patch shrunk to mask>0 regions. The optional subpatch constrains this operation to the sub-region defined by a sequence of slicing operations.

Parameters:
masknpt.NDArray[_NumberType]

Mask to crop to.

sub_patchOptional[Sequence[slice]]

Subregion of mask to only consider (default: full mask).

Returns:
not_emptybool

Whether there is any voxel in the patch at all.

target_slicerSlicingSequence

Sequence of slice-objects to extract the subregion of mask that is ‘True’.

FastSurferCNN.segstats.empty(__arg)[source]

Checks if the argument is an empty list (or None).

FastSurferCNN.segstats.format_parameters(**kwargs)[source]

Formats each keyword argument passed as a pair of key and value.

Returns:
list[str]

A list of one string per keyword arg formatted as a string.

FastSurferCNN.segstats.global_stats(lab, norm, seg, out=None, robust_percentage=None)[source]

Compute Label, Number of voxels, ‘robust’ number of voxels, norm minimum, maximum, sum, sum of squares and 6-connected border of label lab (out references the border).

Parameters:
lab_IntType

Label to compute statistics for.

normnpt.NDArray[_NumberType], optional

The intensity image (default: None, do not compute intensity stats such as normMin, normMax, etc.).

segnpt.NDArray[_IntType]

The segmentation image.

outnpt.NDArray[bool], optional

Output array to store the computed borders.

robust_percentagefloat, optional

A robustness percentile to compute the statistics with (default: None/off = 1).

Returns:
labelint

The label the stats belong to (input).

stats_GlobalStats

A tuple of number_of_voxels, number_of_within_robustness_thresholds, minimum_intensity, maximum_intensity, sum_of_intensities, sum_of_intensity_squares, and border with respect to the label.

FastSurferCNN.segstats.infer_labels_excludeid(args, lut, data)[source]

Infer the labels and excluded ids from command line arguments, the lookup table, or the segmentation image.

Parameters:
argsargparse.Namespace

The commandline arguments object.

lutpd.DataFrame

The ColorLUT lookup table object, e.g. FreeSurferColorLUT.

datanpt.NDArray[int]

The segmentation array.

Returns:
labelsnpt.NDArray[int]

The array of all labels to calculate partial volumes for.

exclude_idlist[int]

A list of labels explicitly excluded from the output table.

FastSurferCNN.segstats.infer_merged_labels(manager, used_labels, merged_labels=(), merge_labels_start=0)[source]
Parameters:
managerManager

The brainvolstats Manager object to get virtual labels.

used_labelsIterable[int]

A list of labels at that are already in use.

merged_labelsSequence[Sequence[int]], default=()

The list of merge labels (first value is SegId, then SegIds it sums across).

merge_labels_startint, default=0

Start index to start at for finding multi-class merged label groups.

Returns:
all_merged_labelsdict[int, Sequence[int]]

The dictionary of all merged labels (via PVMeasure`s as well as `merged_labels).

FastSurferCNN.segstats.main(args)[source]

Main segstats function, based on mri_segstats.

Parameters:
argsobject

Parameter object as defined by make_arguments().parse_args().

Returns:
Literal[0], str

Either as a successful return code or a string with an error message.

FastSurferCNN.segstats.make_arguments(helpformatter=False)[source]

Create an argument parser object with all parameters of the script.

Returns:
argparse.ArgumentParser

The configured argument parser.

FastSurferCNN.segstats.pad_slicer(slicer, whalf, img_size)[source]

Create two slicing tuples for indexing ndarrays/tensors that ‘grow’ and re-‘ungrow’ the patch patch by whalf (also considering the image shape).

Parameters:
slicerSequence[slice]

Input slicing tuple.

whalfint

How much to pad/grow the slicing tuple all around.

img_sizenp.ndarray, Sequence[float]

Shape of the image.

Returns:
SlicingTuple

Tuple of slice-objects to go from image to padded patch.

SlicingTuple

Tuple of slice-objects to go from padded patch to patch.

FastSurferCNN.segstats.parse_files(args, subjects_dir=None, subject_id=None, require_measurefile=False, require_pvfile=True)[source]

Parse and read paths of files.

Parameters:
argsargparse.Namespace

Parameters object from make_arguments.

subjects_dirPath, str, optional

Path to SUBJECTS_DIR, where subject directories are.

subject_idstr, optional

The subject_id string.

require_measurefilebool, default=False

Require the measurefile to exist.

require_pvfilebool, default=True

Require a pvfile or normfile to exist.

Returns:
segfilePath

Path to the segmentation file, most likely an absolute path.

pvfilePath, None

Path to the pvfile file, most likely an absolute path.

normfilePath, None

Path to the norm file, most likely an absolute path, or None if not passed.

segstatsfilePath

Path to the output segstats file, most likely an absolute path.

measurefilePath, None

Path to the measure file, most likely an absolute path, not None is not passed.

Raises:
ValueError

If there is a necessary parameter missing or invalid.

FastSurferCNN.segstats.patch_filter(patch_corner, mask, global_crop, patch_size=32)[source]

Return, whether there are mask-True voxels in the patch starting at pos with size patch_size and the resulting patch shrunk to mask-True regions.

Parameters:
patch_cornertuple[int, int, int]

The top left corner of the patch.

masknpt.NDArray[bool]

The mask of interest in the patch.

global_cropSlicingTuple

A image-wide slicing mask to constrain the ‘search space’.

patch_sizeint, default=32

The size of the patch.

Returns:
bool

Whether there is any data in the patch at all.

SlicingSequence

Sequence of slice objects that describe patches with patch_corner and patch_size.

FastSurferCNN.segstats.patch_neighbors(labels, pv_guide, seg, border_patch, borders, slicer_large_patch, slicer_patch, slicer_large_to_small, slicer_small_to_patch, slicer_large_to_patch, eps=1e-06, legacy_freesurfer=False)[source]

Calculate the neighbor statistics of labels for a specific patch.

The patch is defined by slicer_large_patch, slicer_large_to_small, slicer_small_to_patch, and slicer_large_to_patch.

Parameters:
labelsSequence[int]

A sequence of all labels that we want to compute the PV for.

pv_guidenumpy.ndarray

The (full) image with intensities to guide the PV calculation.

segnumpy.typing.NDArray[int]

The segmentation (full image) defining the labels.

border_patchnpt.NDArray[bool]

Binary mask for the current patch, True, where a voxel is considered to be a border voxel.

bordersdict[_IntType, npt.NDArray[bool]]

Dictionary containing the borders for each label.

slicer_large_patchSlicingTuple

Slicing tuple to obtain a patch of shape like the patch but padded to the large filter size.

slicer_patchSlicingTuple

Tuple of slice-objects to extract the patch from the full image.

slicer_large_to_smallSlicingTuple

Tuple of slice-objects to extract the small patch (patch plus small filter window) from the large patch (patch plus large filter window).

slicer_small_to_patchSlicingTuple

Tuple of slice-objects to extract the patch from the patch padded by the small filter size.

slicer_large_to_patchSlicingTuple

Tuple of slice-objects to extract the patch from the patch padded by the large filter size.

epsfloat, default=1e-6

Epsilon for considering a voxel being in the neighborhood.

legacy_freesurferbool, default=False

Whether to use the legacy freesurfer mri_segstats formula or the corrected formula.

Returns:
pat_is_bordernpt.NDArray[bool]

Array indicating whether each label is on the patch border.

pat_is_nbrnpt.NDArray[bool]

Array indicating whether each label is a neighbor in the patch.

pat_label_countnpt.NDArray[float]

Array containing label counts in the patch (divided by the neighborhood size).

pat_label_sumsnpt.NDArray[float]

Array containing the sum of normalized values for each label in the patch.

FastSurferCNN.segstats.preproc_image(ops, data)[source]

Apply preprocessing operations to data. Performs, –mul, –abs, –sqr, –sqrt operations in that order.

Parameters:
opsSequence[str]

Sequence of operations to perform from ‘mul=<factor>’, ‘div=<factor>’, ‘sqr’, ‘abs’, and ‘sqrt’.

datanp.ndarray

Data to perform operations on.

Returns:
np.ndarray

Data after ops are performed on it.

FastSurferCNN.segstats.pv_calc(seg, pv_guide, norm, labels, patch_size=32, vox_vol=1.0, eps=1e-06, robust_percentage=None, merged_labels=None, threads=-1, return_maps=False, legacy_freesurfer=False)[source]

Compute volume effects.

Parameters:
segnp.ndarray

Segmentation array with segmentation labels.

pv_guidenp.ndarray

Image to use to calculate partial volume effects from.

normnp.ndarray

Intensity image to use to calculate image statistics from.

labelsarray_like

Which labels are of interest.

patch_sizeint, default=32

Size of patches.

vox_volfloat, default=1.0

Volume per voxel.

epsfloat, default=1e-6

Threshold for computation of equality.

robust_percentagefloat, optional

Fraction for robust calculation of statistics.

merged_labelsVirtualLabel, optional

Defines labels to compute statistics for that are.

threadsint, concurrent.futures.Executor, default=-1

Number of parallel threads to use in calculation, alternatively an executor object.

return_mapsbool, default=False

Returns a dictionary containing the computed maps.

legacy_freesurferbool, default=False

Whether to use a freesurfer legacy compatibility mode to exactly replicate freesurfer.

Returns:
pv_statslist[PVStats]

Table (list of dicts) with keys SegId, NVoxels, Volume_mm3, Mean, StdDev, Min, Max, and Range.

mapsdict[str, np.ndarray], optional

Only returned, if return_maps is True: A dictionary with the 5 meta-information pv-maps: nbr: The alternative labels that were considered instead of the voxel’s label. nbr_means: The local mean intensity of the label nbr at the specific voxel. seg_means: The local mean intensity of the primary label at the specific voxel. mixing_coeff: The partial volume of the primary label at the location. nbr_mixing_coeff: The partial volume of the alternative (nbr) label.

FastSurferCNN.segstats.pv_calc_patch(slicer_patch, global_crop, borders, seg, pv_guide, border, full_pv=None, full_ipv=None, full_nbr_label=None, full_seg_mean=None, full_nbr_mean=None, eps=1e-06, legacy_freesurfer=False)[source]

Calculate PV for patch.

If full* keyword arguments are passed, the function also fills in per voxel results for the respective voxels in the patch.

Parameters:
slicer_patchSlicingTuple

Tuple of slice-objects, with indexing origin at the image origin.

global_cropSlicingTuple

Tuple of slice-objects, a global mask to limit computing to relevant parts of the image.

bordersdict[int, npt.NDArray[bool]]

Dictionary containing the borders for each label.

segnumpy.typing.NDArray[int]

The segmentation (full image) defining the labels.

pv_guidenumpy.ndarray

The (full) image with intensities to guide the PV calculation.

bordernpt.NDArray[bool]

Binary mask, True, where a voxel is considered to be a border voxel.

full_pvnpt.NDArray[float], optional

PV image to fill with values for debugging.

full_ipvnpt.NDArray[float], optional

IPV image to fill with values for debugging.

full_nbr_labelnpt.NDArray[_IntType], optional

NBR image to fill with values for debugging.

full_seg_meannpt.NDArray[float], optional

Mean pv_guide-values for current segmentation label-image to fill with values for debugging.

full_nbr_meannpt.NDArray[float], optional

Mean pv_guide-values for nbr label-image to fill with values for debugging.

epsfloat, default=1e-6

Epsilon for considering a voxel being in the neighborhood.

legacy_freesurferbool, default=False

Whether to use the legacy freesurfer mri_segstats formula or the corrected formula.

Returns:
dict[int, float]

Dictionary of per-label PV-corrected volume of affected voxels in the patch.

FastSurferCNN.segstats.seg_borders(_array, label, out=None, cmp_dtype='int8')[source]

Handle to fast 6-connected border computation.

Parameters:
_arraynumpy.ndarray

Image to compute borders from, typically either a label image or a binary mask.

labelint, bool

Which classes to consider for border computation (True/False for binary mask).

outnt.NDArray[bool], optional

The array for inplace computation.

cmp_dtypenpt.DTypeLike, default=int8

The data type to use for border laplace computation.

Returns:
npt.NDArray[bool]

A binary mask with border voxels as True.

FastSurferCNN.segstats.table_to_dataframe(table, report_empty=True, must_keep_ids=None)[source]

Convert the list of PVStats dictionaries into a dataframe.

Parameters:
tablelist[PVStats]

List of partial volume stats dictionaries.

report_emptybool, default=True

Whether empty regions should be part of the dataframe.

must_keep_idsContainer[int], optional

Specifies a list of segids to never remove from the table.

Returns:
pandas.DataFrame

The DataFrame object of all columns and rows in table.

FastSurferCNN.segstats.uniform_filter(data, filter_size, fillval=0.0, slicer_patch=None)[source]

Apply a uniform filter (with kernel size filter_size) to input.

The uniform filter is normalized (weights add to one).

Parameters:
data_ArrayType

Data to perform uniform filter on.

filter_sizeint

Size of the filter.

fillvalfloat, default=0

Value to fill around the image.

slicer_patchSlicingTuple, optional

Sub_region of data to crop to (e.g. to undo the padding (default: full image).

Returns:
_ArrayType

The filtered data.

FastSurferCNN.segstats.update_structnames(table, lut, merged_labels=None)[source]

Update StructNames from lut and merged_labels in table.

Parameters:
tablelist[PVStats]

List of partial volume stats dictionaries.

lutpandas.DataFrame

A pandas DataFrame object containing columns ‘ID’ and ‘LabelName’, which serves as a lookup table for the structure names.

merged_labelsdict[int, Sequence[int]], optional

The dictionary with merged labels.

FastSurferCNN.segstats.write_statsfile(segstatsfile, dataframe, vox_vol, exclude=None, segfile=None, normfile=None, pvfile=None, lut=None, report_empty=False, extra_header=(), norm_name='norm', norm_unit='MR', volume_precision='1', legacy_freesurfer=False)[source]

Write a segstatsfile very similar and compatible with mri_segstats output.

Parameters:
segstatsfilePath, str

Path to the output file.

dataframepd.DataFrame

Data to write into the file.

vox_volfloat

Voxel volume for the header.

excludeSequence[Union[int, str]], optional

Sequence of ids and class names that were excluded from the pv analysis (default: None).

segfilePath, str, optional

Path to the segmentation file (default: empty).

normfilePath, str, optional

Path to the bias-field corrected image (default: empty).

pvfilePath, str, optional

Path to file used to compute the PV effects (default: empty).

lutPath, str, optional

Path to the lookup table to find class names for label ids (default: empty).

report_emptybool, default=False

Do not skip non-empty regions in the lut.

extra_headerSequence[str], default=()

Sequence of additional lines to add to the header. The initial # and newline characters will be added. Should not include newline characters (expect at the end of strings).

norm_namestr, default=”norm”

Name of the intensity image.

norm_unitstr, default=”MR”

Unit of the intensity image.

volume_precisionstr, default=”1”

Number of digits after the comma for volume. Forced to 1 for legacy_freesurfer.

legacy_freesurferbool, default=False

Whether the script ran with the legacy freesurfer option.