Miscellaneous

A collection of useful miscellaneous functions, implemented in the fredtools.Miscellaneous subpackage.

General purpose

fredtools.mergePDF(PDFFileNames: Iterable[PathLike | str], mergedPDFFileName: PathLike | str, removeSource: bool = False, displayInfo: bool = False) → str

Merge multiple PDF files to a single PDF.

The function merges multiple PDF files given as a list of path strings to a single PDF.

Parameters:
  • PDFFileNames (list of strings) – List of path strings to PDF files to be merged.

  • mergedPDFFileName (string) – Path string where the merged PDF will be saved.

  • removeSource (bool, optional) – Determine if the source PDF files should be removed after the merge. (def. False)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Absolute path of the saved merged PDF.

Return type:

str

Raises:
  • TypeError – If PDFFileNames is a single path instead of a list of paths.

  • FileNotFoundError – If any of the PDF files to be merged does not exist.

fredtools.getLineFromFile(pattern: str, fileName: PathLike | str, kind: Literal['all', 'first', 'last'] = 'all', startLine: int = 1, removeEoL: bool = True, comment: str = '#') → tuple[tuple[int, ...], tuple[str, ...]] | tuple[int, str] | None

Read the line and line number from an ASCII file.

The function searches an ASCII file for lines matching a pattern and returns the line or lines number and the line strings. The pattern follows the Python regular expression [PythonRe].

Parameters:
  • pattern (string) – A string describing the regular expression. It is recommended the string be a raw string, starting with r’…’.

  • fileName (string) – Path String to ASCII file.

  • kind ({'all', 'first', 'last'}, optional) – Determine which line is to be returned: the first only, the last, or all the lines. (def. ‘all’)

  • startLine (int, optional) – The line number to start the search (def. 1)

  • removeEoL (bool, optional) – Determine if the end-of-line should be removed from each returned line. (def. True)

  • comment (string, optional) – If not None or an empty string, then no lines starting with this string (leading white spaces are removed) will be returned. (def. ‘#’)

Returns:

If kind=’all’: a tuple of two tuples, where the first is the matched line numbers and the second is the line strings. If kind=’first’ or kind=’last’: a two-element tuple with the first or last matched line number and the line string. None is returned if no line matches the pattern.

Return type:

tuple or None

Raises:

AttributeError – If the kind parameter cannot be recognised.

fredtools.getHistogram(dataX: Iterable[int | float | number], dataY: Iterable[int | float | number] | None = None, bins: Iterable[int | float | number] | None = None, kind: str = 'mean', returnBinCenters: bool = True) → tuple[NDArray, NDArray]

Get histogram or differential histogram.

The function creates a histogram data from a given dataX iterable in the defined bins. It is possible to generate a differential histogram where the values of the histogram (usually Y-axis on a plot) are a given quantity, instead of frequency of dataX values occurrence.

Parameters:
  • dataX (1D array_like) – 1D array-like iterable with the data to calculate histogram. For instance, it can be: a single-column pandas DataFrame, pandas Series, 1D numpy array, 1D list, 1D tuple etc.

  • dataY (1D array_like, optional) – 1D array-like iterable with the data to calculate differential histogram. It must be of the same size as dataX. For instance, it can be: a single-column pandas DataFrame, pandas Series, 1D numpy array, 1D list, 1D tuple etc. (def. None)

  • bins (1D array_like, optional) – 1D array-like iterable with the bins’ edges to calculate histogram. If None, then the bins will be generated automatically between the minimum and maximum value of dataX in 100 steps linearly. (def. None)

  • kind ({'mean', 'sum', 'std', 'median', 'min', 'max', 'mean-std', 'mean+std'}, optional) – Determine the dataY quantity evaluation for a differential histogram. It can be: mean, standard deviation, median, minimum, maximum, sum value or mean +/- standard deviation. (def. ‘mean’)

  • returnBinCenters (bool, optional) – Determine if the first element of the returned list is going to be the bin centers (True) or bin edges (False). (def. True)

Returns:

A two-element tuple of 1D numpy ndarrays, where the first element is a list of bin centers (or edges) and the second is a list of histogram values.

Return type:

tuple of two ndarrays

Raises:
  • TypeError – If dataX, dataY or bins is not an iterable.

  • ValueError – If dataX or dataY is not one-dimensional, dataY is not of the same length as dataX, or the kind parameter cannot be recognised.

fredtools.sigma2fwhm(sigma: int | float | number | Iterable[int | float | number]) → int | float | number | Iterable[int | float | number]

Convert sigma to FWHM.

The function recalculates the sigma parameter of a Gaussian distribution to full width at half maximum (FWHM).

Parameters:

sigma (scalar or array_like) – Sigma value(s).

Returns:

FWHM value(s).

Return type:

scalar or array_like

See also

fwhm2sigma

convert FWHM to sigma.

fredtools.fwhm2sigma(fwhm: int | float | number | Iterable[int | float | number]) → int | float | number | Iterable[int | float | number]

Convert FWHM to sigma.

The function recalculates full width at half maximum (FWHM) of a Gaussian distribution to sigma.

Parameters:

fwhm (scalar or array_like) – FWHM value(s).

Returns:

Sigma value(s).

Return type:

scalar or array_like

See also

sigma2fwhm

convert sigma to FWHM.

fredtools.wrapAngle(angle: int | float | number | Iterable[int | float | number], deg: bool = False) → int | float | number | Iterable[int | float | number]

Wrap angle(s) to [0, 2pi) or [0, 360) range.

The function wraps angle(s) given in radians to the [0, 2*pi) range.

Parameters:
  • angle (scalar or iterable of scalars) – Angle(s) in radians to be wrapped.

  • deg (bool, optional) – If True, the output angle(s) will be in degrees [0, 360). (def. False)

Returns:

Wrapped angle(s) as a numpy array (a 0-dimensional array for scalar input).

Return type:

numpy.ndarray

fredtools.roundToMultiple(values: int | float | number | Iterable[int | float | number], roundNumber: int | float | number) → int | float | number | Iterable[int | float | number]

Round number(s) to the nearest multiple of a number.

The function rounds a single number or an iterable of numbers to the nearest multiple of a given number. For instance, 3.03 rounded to the nearest multiple of 0.25 is 3.0, whereas 3.17 is rounded to 3.25. Halfway cases are rounded according to the round-half-to-even rule, following the numpy rounding routines.

Parameters:
  • values (scalar or array_like) – Value(s) to be rounded.

  • roundNumber (scalar) – A positive number to the nearest multiple of which the value(s) will be rounded.

Returns:

Rounded value(s) as a float scalar for a scalar input, or a numpy array for an iterable input.

Return type:

scalar or numpy.ndarray

Raises:
  • TypeError – If values is not a scalar or an iterable of scalars, or roundNumber is not a scalar.

  • ValueError – If roundNumber is not positive.

Examples

Rounding a single number and an iterable of numbers to the nearest multiple of 0.25.

>>> fredtools.roundToMultiple(3.03, 0.25)
3.0
>>> fredtools.roundToMultiple([3.03, 3.17, -3.17], 0.25)
array([ 3.  ,  3.25, -3.25])
fredtools.getCPUNo(CPUNo: Literal['auto'] | Annotated[int, Ge(ge=0)] = 'auto') → Annotated[int, Ge(ge=0)]

Get a number of CPU cores.

The function returns the number of CPU cores. Usually, it is used in functions utilising multiprocessing.

Parameters:

CPUNo ({'auto'} or integer, optional) – A string of ‘auto’ for all the available CPU cores, or a positive integer showing the number of CPU cores. (def. ‘auto’)

Returns:

Number of CPU cores.

Return type:

integer

Raises:

ValueError – If the number of CPU cores could not be determined automatically, or the CPUNo parameter cannot be recognised.

DICOM UIDs

Functions for reading the UIDs identifying the dicoms and the references between them, and for checking that the dicoms describing a single patient treatment plan are consistent. When many dicoms are to be matched to each other, it is recommended to read them once with getDicomsInfo and to answer all the consecutive queries from the returned information, instead of calling the checkUID_* functions for every pair of dicoms.

fredtools.getDicomsInfo(searchFolder: PathLike | str | Iterable[PathLike | str], recursive: bool = True, readReferences: bool = True, readFrameOfReferenceUID: bool = True, displayInfo: bool = False) → DataFrame

Read the identity and the references of all the dicoms in a folder in a single pass.

The function reads every dicom of a folder (or of an iterable of folders and files) only once and collects the tags which describe the identity of the dicom and its references to other dicoms. All the consecutive queries, in particular matching the dicoms to each other by their UIDs, can then be answered from the resulting index without reading any file again. This is the recommended way of working with a large number of dicoms, for which calling the checkUID_* functions for every pair of dicoms becomes expensive.

The information is collected in at most two passes over each dicom. The first pass reads the type, the SOPInstanceUID and, if requested, the FrameOfReferenceUID of every dicom. The second pass is performed only for the structure set (RS), plan (RN) and dose (RD) dicoms, which are the only ones referencing other dicoms, and reads their references, beam numbers and related tags. Therefore the cost of indexing a folder dominated by image (e.g. CT) dicoms is essentially the cost of a single read of each image dicom.

The function never raises for a dicom which cannot be read. Such a dicom is indexed with the ‘dicomType’ set to ‘Unknown’ and the description of the problem in the ‘error’ column.

Parameters:
  • searchFolder (path or iterable of paths) – A path to a folder to be searched for dicoms, a path to a single dicom file, or an iterable mixing both.

  • recursive (bool, optional) – Determine if the folders should be searched recursively. (def. True)

  • readReferences (bool, optional) – Determine if the references of the RS/RN/RD dicoms should be read in the second pass. Set to False to only classify the dicoms. (def. True)

  • readFrameOfReferenceUID (bool, optional) – Determine if the FrameOfReferenceUID should be read. Setting it to False is substantially faster, because only the dicom file meta information is read in the first pass, but the ‘FrameOfReferenceUID’ column is then filled only for the RS dicoms read in the second pass. (def. True)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A pandas DataFrame with a single row for each dicom found and the columns: ‘fileName’, ‘folderName’, ‘SOPClassUID’, ‘dicomTypeName’, ‘dicomType’, ‘SOPInstanceUID’, ‘FrameOfReferenceUID’, ‘referencedSOPInstanceUIDs’, ‘referencedSeriesNo’, ‘beamNumbers’, ‘referencedBeamNumber’, ‘doseSummationType’, ‘structureSetDate’, ‘structureSetTime’, ‘SeriesInstanceUID’, ‘StudyInstanceUID’ and ‘error’. The rows are given in the order the dicoms were found and are not sorted.

Return type:

DataFrame

See also

sortDicomsFromInfo

group the dicoms information by the dicom type.

matchDicomsByUID

match the plan, structure set, image and dose dicoms by their UIDs.

sortDicoms

sort dicom files in a folder by type.

checkDicomsUID

check the UID matching of all the dicoms describing a single patient plan.

Examples

Index a patient folder once and find the structure set referenced by a plan without reading any dicom file again.

>>> dicomsInfo = ft.getDicomsInfo('/path/to/patient')
>>> RNrow = dicomsInfo[dicomsInfo.dicomType == 'RN'].iloc[0]
>>> dicomsInfo[dicomsInfo.SOPInstanceUID == RNrow.referencedSOPInstanceUIDs[0]].fileName
fredtools.sortDicomsFromInfo(dicomsInfo: DataFrame, collapseSingle: bool = True, displayInfo: bool = False) → DottedDict

Group the file names of the dicoms information by the dicom type.

The function groups the file names of the dicoms information produced by getDicomsInfo by the dicom type, producing the same structure as sortDicoms but without reading any dicom file. It is used to implement sortDicoms and is useful whenever the dicoms information has already been read for other purposes.

Parameters:
  • dicomsInfo (DataFrame) – The dicoms information produced by getDicomsInfo.

  • collapseSingle (bool, optional) – Determine if a group holding exactly one file name should be collapsed to that bare file name instead of a single element list. This is the behaviour of sortDicoms and is kept for compatibility. (def. True)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A dictionary with the keys ‘CTfileNames’, ‘RSfileNames’, ‘RNfileNames’, ‘RDfileNames’, ‘PETfileNames’ and ‘Unknown’.

Return type:

dict

See also

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicoms

sort dicom files in a folder by type.

fredtools.matchDicomsByUID(dicomsInfo: DataFrame, groupImagesBy: Literal['folderName', 'SeriesInstanceUID'] = 'folderName', displayInfo: bool = False) → DataFrame

Match the plan, structure set, image and dose dicoms by their UIDs.

The function matches every plan (RN) dicom of the dicoms information to the structure set (RS) dicom it references, to the image (e.g. CT) dicoms referenced by that structure set, and to all the dose (RD) dicoms referencing the plan. The matching is performed entirely on the given information, therefore no dicom file is read. The results of the UID checks are equivalent to the ones of checkDicomsUID, performed for every plan at once.

The image dicoms are grouped, by default by the folder they are stored in, which is used as a proxy for a single image series export. A group matches the structure set only if the SOPInstanceUIDs of all its dicoms are exactly the ones referenced by the structure set.

Parameters:
  • dicomsInfo (DataFrame) – The dicoms information produced by getDicomsInfo. The FrameOfReferenceUID must have been read for the ‘UIDFoR’ check to be performed.

  • groupImagesBy ({'folderName', 'SeriesInstanceUID'}, optional) – The column used to group the image dicoms into series. (def. ‘folderName’)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A pandas DataFrame with a single row for each plan (RN) dicom of the index and the columns: ‘RNfileName’, ‘RSfileName’, ‘CTfileNames’, ‘RDfileNames’, ‘RSfolderName’, ‘CTfolderName’, ‘RDfolderNames’, ‘UIDRNtoRS’, ‘UIDRStoCT’, ‘UIDRNtoRD’, ‘UIDFoR’ and ‘RDbeamNumbers’. The checks which could not be performed are set to None, i.e. ‘UIDRStoCT’ when no structure set was matched and ‘UIDRNtoRD’/’RDbeamNumbers’ when no dose dicom was matched. Note that the dose dicoms are matched to the plan by their UIDs, therefore ‘UIDRNtoRD’ is never False, unlike in checkDicomsUID where the dose dicoms are given explicitly.

Return type:

DataFrame

See also

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

checkDicomsUID

check the UID matching of all the dicoms describing a single patient plan.

fredtools.getSOPInstanceUID(dicomVars: PathLike | str | Dataset | FileDataset | Iterable[PathLike | str | Dataset | FileDataset], displayInfo: bool = False) → UID | List[UID]

Get the SOPInstanceUID from dicoms.

The function reads the SOPInstanceUID tag from a dicom or an iterable of dicoms of any type (CT, RS, RN, RD, etc.), given as paths to dicom files or as dicom tags already read by pydicom.dcmread. The UIDs are returned as instances of pydicom.uid.UID, which is a subclass of str, therefore the UIDs can be compared directly with the ‘==’ operator.

Parameters:
  • dicomVars (path, tags or iterable of paths or tags) – A path to a dicom file, a dicom tag structure read by pydicom.dcmread, or an iterable of those. No file is read for the dicoms given as tags.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A single UID if a single dicom was given, or a list of UIDs (possibly empty) if an iterable of dicoms was given.

Return type:

UID or list of UIDs

Raises:

ValueError – If the tag ‘SOPInstanceUID’ cannot be found in any of the dicoms.

See also

getRNReferencedStructureSetUID

get the SOPInstanceUID of the structure set (RS) referenced in a plan (RN) dicom.

getRSReferencedImageUIDs

get the SOPInstanceUIDs of the images (e.g. CT) referenced in a structure set (RS) dicom.

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicoms

sort dicom files in a folder by type.

fredtools.getFrameOfReferenceUID(dicomVars: PathLike | str | Dataset | FileDataset | Iterable[PathLike | str | Dataset | FileDataset], displayInfo: bool = False) → UID | List[UID]

Get the FrameOfReferenceUID from dicoms.

The function reads the FrameOfReferenceUID tag from a dicom or an iterable of dicoms of any type (CT, RS, RN, RD, etc.), given as paths to dicom files or as dicom tags already read by pydicom.dcmread. For structure set (RS) dicoms without a top-level FrameOfReferenceUID, the UID is read from the first item of the ReferencedFrameOfReferenceSequence. The UIDs are returned as instances of pydicom.uid.UID and should be the same for all the dicoms describing the same treatment plan.

Parameters:
  • dicomVars (path, tags or iterable of paths or tags) – A path to a dicom file, a dicom tag structure read by pydicom.dcmread, or an iterable of those. No file is read for the dicoms given as tags.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A single UID if a single dicom was given, or a list of UIDs (possibly empty) if an iterable of dicoms was given.

Return type:

UID or list of UIDs

Raises:

ValueError – If no FrameOfReferenceUID can be found in any of the dicoms.

See also

getSOPInstanceUID

get the SOPInstanceUID from dicoms.

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicoms

sort dicom files in a folder by type.

fredtools.getRNReferencedStructureSetUID(dicomVar: PathLike | str | Dataset | FileDataset, displayInfo: bool = False) → UID

Get the SOPInstanceUID of the structure set referenced in a plan dicom.

The function reads the ReferencedSOPInstanceUID of the structure set (RS) dicom referenced in a dicom with an RT plan (RN), given as a path to a dicom file or as dicom tags already read by pydicom.dcmread. The UID is returned as an instance of pydicom.uid.UID and should match the SOPInstanceUID of the structure set dicom that the plan was created for.

Parameters:
  • dicomVar (path or tags) – A path to a dicom file with an RT plan (RN file), or a dicom tag structure read by pydicom.dcmread. No file is read for tags.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

The SOPInstanceUID of the referenced structure set.

Return type:

UID

Raises:
  • TypeError – If the dicom is not of an RT plan (RN) type.

  • ValueError – If no ‘ReferencedStructureSetSequence’ item can be found in the dicom.

See also

getSOPInstanceUID

get the SOPInstanceUID from dicoms.

getRSReferencedImageUIDs

get the SOPInstanceUIDs of the images (e.g. CT) referenced in a structure set (RS) dicom.

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicoms

sort dicom files in a folder by type.

fredtools.getRSReferencedImageUIDs(dicomVar: PathLike | str | Dataset | FileDataset, displayInfo: bool = False) → List[UID]

Get the SOPInstanceUIDs of the images referenced in a structure set dicom.

The function reads the ReferencedSOPInstanceUIDs of all the images (usually CT slices) referenced in the contour image sequences of a dicom with a structure set (RS), given as a path to a dicom file or as dicom tags already read by pydicom.dcmread. The UIDs are returned as instances of pydicom.uid.UID and should match the SOPInstanceUIDs of the image dicoms that the structure set was created for.

Parameters:
  • dicomVar (path or tags) – A path to a dicom file with a structure set (RS file), or a dicom tag structure read by pydicom.dcmread. No file is read for tags.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A list (possibly empty) of the SOPInstanceUIDs of the referenced images.

Return type:

list of UIDs

Raises:
  • TypeError – If the dicom is not of a structure set (RS) type.

  • ValueError – If the tag ‘ReferencedFrameOfReferenceSequence’ cannot be found in the dicom.

See also

getSOPInstanceUID

get the SOPInstanceUID from dicoms.

getRNReferencedStructureSetUID

get the SOPInstanceUID of the structure set (RS) referenced in a plan (RN) dicom.

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicoms

sort dicom files in a folder by type.

fredtools.getRDReferencedPlanUID(dicomVar: PathLike | str | Dataset | FileDataset, displayInfo: bool = False) → UID

Get the SOPInstanceUID of the plan referenced in a dose dicom.

The function reads the ReferencedSOPInstanceUID of the plan (RN) dicom referenced in a dicom with a dose distribution (RD), given as a path to a dicom file or as dicom tags already read by pydicom.dcmread. The UID is returned as an instance of pydicom.uid.UID and should match the SOPInstanceUID of the plan dicom that the dose was calculated for.

Parameters:
  • dicomVar (path or tags) – A path to a dicom file with a dose distribution (RD file), or a dicom tag structure read by pydicom.dcmread. No file is read for tags.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

The SOPInstanceUID of the referenced plan.

Return type:

UID

Raises:
  • TypeError – If the dicom is not of a dose (RD) type.

  • ValueError – If no ‘ReferencedRTPlanSequence’ item can be found in the dicom.

See also

getSOPInstanceUID

get the SOPInstanceUID from dicoms.

getRNReferencedStructureSetUID

get the SOPInstanceUID of the structure set (RS) referenced in a plan (RN) dicom.

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicoms

sort dicom files in a folder by type.

fredtools.checkUID_RNtoRS(RNfileName: PathLike | str, RSfileName: PathLike | str) → bool

Check if the structure set referenced by a plan dicom matches a structure set dicom.

The function validates that the given files are of the correct dicom type, then compares the ReferencedSOPInstanceUID of the structure set (RS) dicom referenced in the plan (RN) dicom, obtained with getRNReferencedStructureSetUID, with the SOPInstanceUID of the given RS dicom, obtained with getSOPInstanceUID. The comparison result is logged at the debug level only; no info or warning is logged by this function, so it is up to the calling code to log accordingly.

Parameters:
  • RNfileName (path) – Path to a dicom file with an RT plan (RN file).

  • RSfileName (path) – Path to a dicom file with a structure set (RS file).

Returns:

True if the RN dicom references the given RS dicom, False otherwise.

Return type:

bool

Raises:
  • TypeError – If RNfileName is not an RT plan dicom, or RSfileName is not a structure set dicom.

  • ValueError – If the RN dicom does not contain a ReferencedStructureSetSequence, or if the SOPInstanceUID tag cannot be found in the RS dicom.

See also

checkUID_RStoCT

check if the images referenced by a structure set dicom match a set of CT dicoms.

checkUID_RNtoRD

check if the plan referenced by dose dicoms matches a plan dicom.

getRNReferencedStructureSetUID

get the SOPInstanceUID of the structure set referenced in a plan dicom.

getSOPInstanceUID

get the SOPInstanceUID from dicom files.

fredtools.checkUID_RStoCT(RSfileName: PathLike | str, CTfileNames: PathLike | str | Iterable[PathLike | str]) → bool

Check if the images referenced by a structure set dicom match a set of CT dicoms.

The function validates that the given files are of the correct dicom type, then compares the SOPInstanceUIDs of the images referenced in the contour image sequences of the structure set (RS) dicom, obtained with getRSReferencedImageUIDs, with the SOPInstanceUIDs of the given CT dicoms, obtained with getSOPInstanceUID. The comparison is order-independent (both UID lists are sorted before comparing). The comparison result is logged at the debug level only, so it is up to the calling code to log the result accordingly. However, a warning is logged if the CT dicoms contain images not referenced in the RS dicom or if duplicated SOPInstanceUIDs are found among the CT dicoms.

Parameters:
  • RSfileName (path) – Path to a dicom file with a structure set (RS file).

  • CTfileNames (path or iterable of paths) – A path or an iterable of paths to CT image dicom files.

Returns:

True if the set of CT dicoms exactly matches the images referenced by the RS dicom, False otherwise.

Return type:

bool

Raises:
  • TypeError – If RSfileName is not a structure set dicom, or any of CTfileNames is not a CT image dicom.

  • ValueError – If the RS dicom does not contain a ReferencedFrameOfReferenceSequence, or if the SOPInstanceUID tag cannot be found in a CT dicom.

See also

checkUID_RNtoRS

check if the structure set referenced by a plan dicom matches a structure set dicom.

checkUID_RNtoRD

check if the plan referenced by dose dicoms matches a plan dicom.

getRSReferencedImageUIDs

get the SOPInstanceUIDs of the images referenced in a structure set dicom.

getSOPInstanceUID

get the SOPInstanceUID from dicom files.

fredtools.checkUID_RNtoRD(RNfileName: PathLike | str, RDfileNames: PathLike | str | Iterable[PathLike | str]) → bool

Check if the plan referenced by dose dicoms matches a plan dicom.

The function validates that the given files are of the correct dicom type, then compares the ReferencedSOPInstanceUID of the plan (RN) dicom referenced in each dose (RD) dicom, obtained with getRDReferencedPlanUID, with the SOPInstanceUID of the given RN dicom, obtained with getSOPInstanceUID. The comparison result is logged at the debug level only; no info or warning is logged by this function, so it is up to the calling code to log accordingly.

Parameters:
  • RNfileName (path) – Path to a dicom file with an RT plan (RN file).

  • RDfileNames (path or iterable of paths) – A path or an iterable of paths to dose (RD) dicom files.

Returns:

True if every RD dicom references the given RN dicom, False otherwise.

Return type:

bool

Raises:
  • TypeError – If RNfileName is not an RT plan dicom, or any of RDfileNames is not a dose dicom.

  • ValueError – If no RD file names are provided, if an RD dicom does not contain a ReferencedRTPlanSequence, or if the SOPInstanceUID tag cannot be found in the RN dicom.

See also

checkUID_RNtoRS

check if the structure set referenced by a plan dicom matches a structure set dicom.

checkUID_RStoCT

check if the images referenced by a structure set dicom match a set of CT dicoms.

getRDReferencedPlanUID

get the SOPInstanceUID of the plan referenced in a dose dicom.

getSOPInstanceUID

get the SOPInstanceUID from dicom files.

Model fitting

General purpose fitting of a model function to data with the least squares method. The model is an ordinary python function of the positions and of the parameters, and the data can be given as numpy arrays of any dimension (e.g. a profile, a 2D or a 3D array, or a list of points) or as a SimpleITK image, for which the positions are the physical positions of the voxel centers. The parameters can be limited or fixed, and data points can be excluded from the fit with a mask, with a range of the data values, or by setting them to NaN. The excluded points are removed before the fit, so they do not influence the uncertainties of the parameters, but the fitted model is still returned for all the data points, in the format of the input data (an array of the same shape or an image with the same frame of reference). The result of the fit holds the fitted values of the parameters with their uncertainties and can calculate the fitted model and its uncertainty at any positions, quantities derived from the parameters with their uncertainties, and a text summary of the fit. The fit is made with scipy.optimize.least_squares.

fredtools.fit(func: Callable[[...], Any], data: ArrayLike | Image, pos: ArrayLike | tuple[ArrayLike, ...] | None = None, params: Mapping[str, int | float | number | fitParam] | None = None, mask: ArrayLike | Image | None = None, dataRange: Sequence[int | float | number | None] | None = None, dataError: int | float | number | ArrayLike | Image | None = None, absoluteError: bool = False, solverOptions: dict[str, Any] | None = None, displayInfo: bool = False) → fitResult

Fit a model function to data.

The function fits a model function, defined by the user as an ordinary python function, to data of any dimension with the least squares method, i.e. it searches for the values of the model parameters giving the smallest sum of the squared differences between the data and the model. The data can be given as a numpy array with the positions of the data points, or as a SimpleITK image, for which the positions are the physical positions of the voxel centers. Data points can be excluded from the fit with a mask, with a range of the data values, or by setting them to NaN. The parameters can be limited or fixed. The fit result holds the fitted values of the parameters with their uncertainties, the statistics of the fit, and the fitted model in the format of the input data.

Parameters:
  • func (callable) – Model function in the form func(x, y, …, parameterA, parameterB, …). The first N arguments are the positions and all the following arguments are the parameters of the model, where N is the number of the position arrays given in pos or the dimension of the image. The function is always called with one-dimensional float64 numpy arrays of the same length as the positions (one element for each point) and with numbers as the parameters, and must return an array with one value for each point (or a single number for all the points). The position arrays are read-only, therefore, the function must not modify them in place.

  • data (array_like or SimpleITK Image) – Data to be fitted: an array of any shape or a SimpleITK image of a scalar pixel type. The masked elements of a numpy masked array are not used.

  • pos (array_like or tuple of array_like, optional) – Positions of the data points. It is required when data is an array, in the form of a single array for a model of a single position argument, or of a tuple of N arrays for a model of N position arguments. Each array must be of the shape of data or of a shape that can be broadcast to it (see e.g. numpy.meshgrid). It must be None when data is a SimpleITK image: the positions are then the physical positions of the voxel centers (see getVoxelCentersGrid), and N is always equal to the image dimension, e.g. a model function of a 3D image is func(x, y, z, …). (def. None)

  • params (dict, optional) – Dictionary of the parameter names and their start values, given as numbers or as fitParam objects with the start value, the limits and the flag telling if the parameter is varied. A parameter not present in the dictionary takes the default value defined in the signature of func as the start value. (def. None)

  • mask (array_like or SimpleITK Image, optional) – Mask of the data points to be used in the fit. When data is an array, it is a boolean array of the shape of data (True for the points to be used). When data is a SimpleITK image, it is a SimpleITK image describing a binary mask with the same frame of reference as data. (def. None)

  • dataRange (sequence of two scalars or None, optional) – Range (min, max) of the data values to be used in the fit: only the data points with the values between min and max, including both, are used. None can be given for min or max to not limit the range from this side. (def. None)

  • dataError (scalar, array_like or SimpleITK Image, optional) – Uncertainties (standard deviations) of the data points, given as a single number for all the points or, when data is an array, as an array of the shape of data or, when data is a SimpleITK image, as a SimpleITK image with the same frame of reference as data. The points with smaller uncertainties have more influence on the fit. If None, all the data points have the same influence. (def. None)

  • absoluteError (bool, optional) – Determine the meaning of dataError. If False, they are relative weights only: the uncertainties of the parameters are scaled by the scatter of the data around the fitted model and do not depend on the overall scale of dataError. If True, they are the real standard deviations of the data and the uncertainties of the parameters follow from them directly. (def. False)

  • solverOptions (dict, optional) – Additional options given to scipy.optimize.least_squares, e.g. {“max_nfev”: 1000} to change the maximum number of the solver steps or {“loss”: “soft_l1”, “method”: “trf”} for a fit less sensitive to outliers. The options ‘fun’, ‘x0’, ‘bounds’, ‘args’ and ‘kwargs’ cannot be given. See Notes for the options set by the function. (def. None)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

An object of the fitResult class with the results of the fit.

Return type:

fitResult

Raises:
  • TypeError – If func is not callable or its arguments cannot be recognised (e.g. it takes a variable number of arguments), if data is a vector or a label SimpleITK image, if the mask image is not a binary mask, or if data, pos, params, mask, dataError or solverOptions are of a wrong type (e.g. not numbers, or an array given with an image or an image given with an array).

  • ValueError – If data is empty or is a single number, if pos is missing for an array, is given for an image, or cannot be broadcast to the shape of the data, if the number of the positions and the parameters does not match the arguments of func, if a parameter is unknown, has no start value, has a start value which is not finite or is outside the limits, or has the lower limit not smaller than the upper limit, if no parameter is varied, if mask or dataError do not match the shape or the frame of reference of data, if dataRange is not a pair (min, max), if absoluteError is True without dataError, if an option in solverOptions is not recognised or not allowed (also the method ‘lm’ for parameters with limits and the option ‘jac’ equal to ‘cs’), if the number of the used data points is not larger than the number of the varied parameters, or if the model function returns values of a wrong shape or non-finite values for the start values of the parameters.

  • Exception – Any error raised by the model function for the start values of the parameters.

See also

fitParam

parameter of a model function.

fitResult

result of a fit.

getVoxelCentersGrid

get physical positions of voxel centers as a grid.

scipy.optimize.least_squares

the solver used by the function.

Notes

Excluded data points. The following data points are not used in the fit: the points outside the mask, the points with the data values outside the dataRange, the points with non-finite data values or positions (NaN or infinite), the points with a non-finite, zero or negative dataError, and the masked elements when the data, the positions or dataError are numpy masked arrays. They are removed from the data before the fit, therefore, they are not counted in the number of data points and do not influence the uncertainties of the parameters. The fitted model (bestFit of the result) is nevertheless calculated for all the data points, and usedMask of the result shows which points were used.

Algorithm. The fit is made with scipy.optimize.least_squares. If no varied parameter has a limit, the Levenberg-Marquardt algorithm of MINPACK is used (method ‘lm’). Otherwise, the Trust Region Reflective algorithm is used (method ‘trf’), which keeps the parameters inside the limits during the whole fit. The derivatives of the model over the parameters are calculated numerically, with a step of about 1.5e-8 of the parameter value, but not smaller than 1.5e-8. The step is enlarged when the model does not change measurably for it, e.g. for a parameter starting from zero in data of very large values. The same steps are used for the uncertainties. Therefore, the parameters on which the model depends non-linearly should not be smaller than about 1e-6 (e.g. a width should not be given as 1e-9 m but as 1 nm). For smaller parameters, steps relative to the parameter values can be requested with solverOptions, e.g. {“diff_step”: 1e-8}. The algorithm, its tolerances and the calculation of the derivatives can be changed with solverOptions.

Uncertainties. The uncertainties of the parameters (stderr) are one standard deviation, calculated from the covariance matrix of the varied parameters. Without dataError or with absoluteError equal to False, the covariance matrix is scaled by the reduced chi-square of the fit, i.e. the uncertainties of the data are estimated from the scatter of the data around the fitted model. With absoluteError equal to True, it is not scaled. A parameter which ended on its limit has no uncertainty (NaN) and is marked with atLimit. A parameter is taken as ended on a limit when it is closer to the limit than a tenth of its uncertainty (calculated for the other parameters kept fixed) and the fit without the limit would go beyond it. The uncertainties of the other parameters are then calculated as if it was fixed at the limit. If the data do not determine all the parameters (e.g. the rotation of a round spot), no uncertainties are given and a warning is logged.

No convergence. If the fit does not converge, e.g. the maximum number of the solver steps is reached or the model function raises an error during the fit, no error is raised: a warning is logged and the result has success equal to False, with the best values of the parameters found so far and without uncertainties. Parameter values for which the model function returns non-finite values (e.g. outside the domain of a square root or a logarithm) are not accepted by the solver, which then tries a smaller step, so the fit goes on.

Solver options. The function sets some options of scipy.optimize.least_squares differently from its defaults, unless they are given in solverOptions: the parameters are scaled with x_scale equal to ‘jac’, and with the methods ‘trf’ and ‘dogbox’ the fit is not ended by the tolerance of the gradient (gtol equal to None), because this tolerance is absolute and would stop the fit of data of very small values at the start values. The option max_nfev limits the number of the solver steps, and the model function is calculated more often, also for the derivatives. The derivatives are calculated by SciPy, and not by this function, when the option jac (‘2-point’, ‘3-point’ or a function) or the option diff_step is given. A function given as jac takes an array with the values of the varied parameters, in the order of varNames of the result, and must return the derivatives of the residuals over these parameters, as an array of the shape (number of the used data points, number of the varied parameters), where the residuals are the model minus the data for the used data points, divided by dataError when it is given. A loss other than ‘linear’ needs the method ‘trf’ or ‘dogbox’, and the uncertainties of the parameters are then not corrected for the smaller influence of the outliers.

Memory. The data, the positions and dataError given as arrays are copied, so the result does not change when they are changed after the fit. The model function is calculated for the used data points only, but the derivatives need an array of the number of the used points times the number of the varied parameters (and a few times more with limits), which can be gigabytes for an image of tens of millions of voxels.

Examples

Fit a Gaussian to a profile given as arrays of positions and values, with the center fixed to zero and with the sigma limited to positive values.

>>> def gauss(x, amplitude, center, sigma):
...     return amplitude * numpy.exp(-(x - center)**2 / (2 * sigma**2))
>>> result = fredtools.fit(gauss, vec, pos, params={"amplitude": vec.max(),
...                                                 "center": fredtools.fitParam(0, vary=False),
...                                                 "sigma": fredtools.fitParam(3, min=1E-6)})
>>> result.bestValues
{'amplitude': 7.056627306323629, 'center': 0.0, 'sigma': 2.5089330349459655}
>>> result.params["sigma"]
fitParam(value=2.5089330349459655, stderr=0.01597807978481477, initValue=3.0, min=1e-06, max=inf, vary=True)
>>> result.bestFit.shape == vec.shape
True

Fit a 2D Gaussian to a 2D SimpleITK image, using only the voxels with the values above half of the maximum. The positions are taken from the image and the fitted model is an image.

>>> def gauss2D(x, y, amplitude, centerX, centerY, sigmaX, sigmaY):
...     return amplitude * numpy.exp(-(x - centerX)**2 / (2 * sigmaX**2) - (y - centerY)**2 / (2 * sigmaY**2))
>>> valueMax = fredtools.getStatistics(img).GetMaximum()
>>> result = fredtools.fit(gauss2D, img, dataRange=(0.5 * valueMax, None),
...                        params={"amplitude": valueMax, "centerX": 0, "centerY": 0,
...                                "sigmaX": fredtools.fitParam(3, min=1E-6),
...                                "sigmaY": fredtools.fitParam(3, min=1E-6)})
>>> imgModel = result.bestFit
>>> imgUsed = result.usedMask

Fit a plane-like function a + b*x + c*y + d*z to a 3D array, with the positions given by the vectors of the x, y and z coordinates of the array axes.

>>> X, Y, Z = numpy.meshgrid(xs, ys, zs, indexing="ij", sparse=True)
>>> result = fredtools.fit(lambda x, y, z, a, b, c, d: a + b * x + c * y + d * z,
...                        arr, (X, Y, Z), params={"a": 0, "b": 1, "c": 1, "d": 1})
class fredtools.fitParam(value: int | float | number, min: int | float | number = -inf, max: int | float | number = inf, vary: bool = True)

Parameter of a model function fitted with fit.

The class describes a single parameter of a model function: its start value, the limits and whether it is varied in the fit. The fit function takes the parameters as a dictionary of the parameter names and the objects of this class (or just numbers, when only the start value is to be given), and returns them in the same form in the fit result, with the fitted values and their uncertainties.

Parameters:
  • value (scalar) – Start value of the parameter. For a parameter which is not varied, it is the value used in the fit.

  • min (scalar, optional) – Lower limit of the parameter. (def. -inf)

  • max (scalar, optional) – Upper limit of the parameter. (def. inf)

  • vary (bool, optional) – Determine if the parameter is varied in the fit (True) or kept at value (False). (def. True)

Variables:
  • value (scalar) – Value of the parameter: the start value before the fit and the fitted value in a fit result.

  • min (scalar) – Lower limit of the parameter.

  • max (scalar) – Upper limit of the parameter.

  • vary (bool) – True if the parameter is varied in the fit.

  • stderr (float) – Uncertainty (one standard deviation) of the fitted value. It is NaN before the fit and when the uncertainty could not be calculated (e.g. when the parameter ended on a limit or the fit did not converge), and it is 0 for a parameter which was not varied.

  • initValue (float) – Start value used in the fit (NaN before the fit).

  • atLimit (bool) – True if the fitted value ended on the lower or the upper limit.

See also

fit

fit a model function to data.

fitResult

result of a fit.

Notes

The value, the limits and vary are stored as given and can be changed at any time. They are checked by fit, which raises an error for values which are not numbers, for a start value which is not finite or is outside the limits, and for a lower limit which is not smaller than the upper limit. In a fit result, the value and the limits are floats.

Examples

A parameter with a start value of 3, which must be positive.

>>> fredtools.fitParam(3, min=0)
fitParam(value=3.0, min=0.0, max=inf, vary=True)

A parameter fixed to zero.

>>> fredtools.fitParam(0, vary=False)
fitParam(value=0.0, min=-inf, max=inf, vary=False)
class fredtools.fitResult

Result of a fit made with fit.

The class holds the results of fitting a model function to data: the fitted parameters with their uncertainties, the statistics of the fit, the data and the fitted model in the format of the input data (numpy arrays or SimpleITK images). Its methods calculate the fitted model and its uncertainty at any positions (eval, evalStd), quantities derived from the parameters with their uncertainties (derive) and a text summary of the fit (report). The objects of this class are created by the fit function.

Variables:
  • func (callable) – The fitted model function.

  • data (numpy.array or SimpleITK Image) – The data given to the fit: a float64 numpy array (a copy of the given data, with NaN for the masked elements of a masked array), or the SimpleITK image.

  • pos (numpy.array, tuple of numpy.array or None) – The positions of the data points given to the fit, as float64 numpy arrays (copies). It is None when the data is a SimpleITK image.

  • dataError (float, numpy.array, SimpleITK Image or None) – The uncertainties of the data points given to the fit: a float, a float64 numpy array (a copy of the given array, with NaN for the masked elements of a masked array), or the SimpleITK image.

  • params (dict) – Dictionary of the parameter names and fitParam objects, holding the fitted values, their uncertainties, the start values, the limits and the flags telling if a parameter was varied and if it ended on a limit, in the order of the model function arguments.

  • varNames (tuple of str) – Names of the varied parameters. The rows and columns of covar and correl are in this order.

  • covar (numpy.array or None) – Covariance matrix of the varied parameters. The rows and columns of the parameters which ended on a limit are NaN. It is None when the uncertainties could not be calculated.

  • correl (numpy.array or None) – Correlation matrix of the varied parameters, in the same form as covar.

  • chiSquare (float) – Sum of the squared residuals of the used data points, each divided by its uncertainty when dataError was given.

  • redChiSquare (float) – Reduced chi-square, i.e. chiSquare divided by nFree.

  • nData (int) – Number of the data points used in the fit, i.e. without the excluded points.

  • nVarys (int) – Number of the varied parameters.

  • nFree (int) – Number of the degrees of freedom, i.e. nData - nVarys.

  • nFev (int) – Number of the evaluations of the model function during the fit.

  • success (bool) – True if the fit converged.

  • message (str) – Description of how the fit ended.

  • method (str) – Algorithm used by the fit: ‘lm’ (Levenberg-Marquardt), ‘trf’ (Trust Region Reflective) or ‘dogbox’.

See also

fit

fit a model function to data.

fitParam

parameter of a model function.

property bestFit: NDArray | Image

Fitted model at the positions of all the data points, also of the points excluded from the fit, as an array of the shape of the data or, when the data is a SimpleITK image, as a float64 image with the frame of reference of the data.

Type:

numpy.array or SimpleITK Image

property bestValues: dict[str, float]

Fitted values of all the parameters (for a parameter which was not varied, its fixed value).

Type:

dict

derive(func: Callable[[...], Any]) → tuple[float, float] | tuple[NDArray, NDArray]

Calculate a quantity derived from the fitted parameters with its uncertainty.

The method calculates the value of a function of the fitted parameters, e.g. the full width at half maximum from the sigma of a Gaussian or a ratio of two parameters, and its uncertainty (one standard deviation), which follows from the uncertainties of the parameters and the correlations between them.

Parameters:

func (callable) – Function calculating the quantity from the parameters. Its arguments must be named as the parameters of the fitted model, and it can take any subset of them, e.g. lambda sigma: 2.355 * sigma. It must return a number or an array of numbers.

Returns:

The value of the quantity and its uncertainty, as two floats or, when func returns an array, as two float64 numpy arrays of the shape of the returned array. The uncertainty is NaN when the uncertainties of the parameters could not be calculated (covar is None).

Return type:

tuple

Raises:
  • TypeError – If func is not callable, its arguments cannot be recognised or it does not return numbers.

  • ValueError – If an argument of func is not a parameter of the fitted model.

See also

evalStd

calculate the standard deviation of the fitted model at given positions.

Notes

The uncertainty is calculated with the linear propagation of the covariance matrix of the parameters, with the derivatives of func over the parameters calculated numerically. It is a good estimate when func is close to linear within the uncertainties of the parameters. The parameters which were not varied or which ended on a limit do not contribute to it.

Examples

The full width at half maximum of a fitted Gaussian with its uncertainty.

>>> result.derive(lambda sigma: 2.355 * sigma)
(5.876487797286922, 0.0365737380390084)

The ratio of the two widths of a fitted 2D Gaussian. The correlation between the two parameters is taken into account.

>>> ratio, ratioError = result.derive(lambda sigmaX, sigmaY: sigmaX / sigmaY)
eval(pos: ArrayLike | tuple[ArrayLike, ...] | Image | None = None) → NDArray | Image

Calculate the fitted model at given positions.

The method calculates the model function with the fitted values of the parameters at the positions of the data points, at any other positions or at the voxel centers of a SimpleITK image.

Parameters:

pos (array_like, tuple of array_like, SimpleITK Image or None, optional) –

Positions at which the model is calculated:

  • None: the positions of the data points, which gives bestFit.

  • array_like or tuple of array_like: the positions in the same form as in fit, i.e. a single array for a model of a single position argument, or a tuple of N arrays for a model of N position arguments. The arrays must be of the same shape or of shapes that can be broadcast to a common shape.

  • SimpleITK Image: the centers of the voxels of the image, which must be of the dimension equal to the number of the position arguments of the model.

(def. None)

Returns:

The model values: for None in the same form as bestFit, for arrays as a float64 array of the (broadcast) shape of the positions, and for an image as a float64 image with the frame of reference of that image.

Return type:

numpy.array or SimpleITK Image

Raises:
  • TypeError – If pos is not an array of numbers, a tuple of such arrays or a SimpleITK image.

  • ValueError – If the number of the position arrays or the dimension of the image is different from the number of the position arguments of the model, or if the position arrays cannot be broadcast to a common shape.

See also

evalStd

calculate the standard deviation of the fitted model at given positions.

Examples

Calculate the fitted model of a profile on a finer grid of positions.

>>> profileFine = result.eval(numpy.linspace(-20, 20, 401))

Calculate the fitted model of an image on the voxels of another image.

>>> imgModel = result.eval(imgOther)
evalStd(pos: ArrayLike | tuple[ArrayLike, ...] | Image | None = None) → NDArray | Image

Calculate the standard deviation of the fitted model at given positions.

The method calculates the standard deviation, i.e. the uncertainty, of the fitted model, which follows from the uncertainties of the fitted parameters and the correlations between them, at the positions of the data points, at any other positions or at the voxel centers of a SimpleITK image. It describes how well the fitted curve or surface itself is known (often shown as a band around the fitted curve), not the scatter of the single data points around it.

Parameters:

pos (array_like, tuple of array_like, SimpleITK Image or None, optional) – Positions at which the standard deviation is calculated, in the same form as in eval: None for the positions of the data points, an array or a tuple of arrays for any positions, or a SimpleITK image for the centers of its voxels. (def. None)

Returns:

The standard deviation of the model, in the same form as the result of eval for the same pos. All the values are NaN when the uncertainties of the parameters could not be calculated (covar is None).

Return type:

numpy.array or SimpleITK Image

Raises:
  • TypeError – If pos is not an array of numbers, a tuple of such arrays or a SimpleITK image.

  • ValueError – If the number of the position arrays or the dimension of the image is different from the number of the position arguments of the model, or if the position arrays cannot be broadcast to a common shape.

See also

eval

calculate the fitted model at given positions.

derive

calculate a quantity derived from the fitted parameters with its uncertainty.

Notes

The standard deviation is calculated with the linear propagation of the covariance matrix of the parameters, with the derivatives of the model over the parameters calculated numerically. The parameters which were not varied or which ended on a limit do not contribute to it.

Examples

Calculate the fitted model of a profile and its standard deviation on a fine grid of positions, to plot the fitted curve with its uncertainty band.

>>> posFine = numpy.linspace(-20, 20, 401)
>>> model, modelStd = result.eval(posFine), result.evalStd(posFine)
>>> matplotlib.pyplot.plot(posFine, model)
>>> matplotlib.pyplot.fill_between(posFine, model - modelStd, model + modelStd, alpha=0.3)
property initValues: dict[str, float]

Start values of all the parameters.

Type:

dict

report() → str

Get a summary of the fit as a text.

The method prepares a readable summary of the fit: how the fit ended, the number of the data points, the chi-square statistics, the fitted values of the parameters with their uncertainties, start values and limits, and the correlations between the parameters. The same text is logged by the fit function called with displayInfo equal to True.

Returns:

The summary of the fit. The lines after the first one are indented with tabulators, as in the other summaries displayed by FREDtools. Only the correlations with the absolute value of at least 0.1 are listed.

Return type:

str

Examples

>>> print(result.report())
Fit of the model function 'gauss' with the method 'trf': converged
        message:              `ftol` termination condition is satisfied.
        data points used/all: 81/81
        varied parameters:    3
        model evaluations:    29
        chi-square:           0.673
        reduced chi-square:   0.008629
        parameters:
                amplitude = 7.09689 +/- 0.0383 (0.54%), start value 5
                center    = 1.51582 +/- 0.0155 (1%), start value 0
                sigma     = 2.49532 +/- 0.0155 (0.62%), start value 4, limits [1e-06, inf]
        correlations:
                amplitude, sigma = -0.577
property residual: NDArray | Image

Difference between the data and the fitted model (data - bestFit) at all the data points, in the same form as bestFit. It is not divided by the uncertainties of the data.

Type:

numpy.array or SimpleITK Image

property usedMask: NDArray | Image

Data points used in the fit, as a boolean array of the shape of the data or, when the data is a SimpleITK image, as a binary mask image with the frame of reference of the data.

Type:

numpy.array or SimpleITK Image

Built-in models

Ready model functions which can be given to fredtools.fit, each with a function guessing the start values of its parameters from the data. The guessed parameters are returned in the form taken by fredtools.fit and can be changed before the fit, e.g. to fix some of them. The Gaussian models include a constant offset (background), which is fitted by default and can be fixed when its value is known.

fredtools.modelGauss1D(x: ArrayLike, amplitude: int | float | number, center: int | float | number, sigma: int | float | number, offset: int | float | number = 0) → NDArray

Model of a one-dimensional Gaussian with a constant offset.

The function calculates a Gaussian on a constant background, defined as: amplitude * exp(-(x - center)^2 / (2 * sigma^2)) + offset. It can be used as a model function in fit, with the start values of the parameters guessed with guessGauss1D.

Parameters:
  • x (array_like) – Positions at which the model is calculated.

  • amplitude (scalar) – Height of the Gaussian above the offset.

  • center (scalar) – Position of the maximum of the Gaussian.

  • sigma (scalar) – Width of the Gaussian given as one standard deviation.

  • offset (scalar, optional) – Constant value added to the Gaussian (background). (def. 0)

Returns:

Values of the model at the positions x, of the shape of x.

Return type:

numpy.array

See also

guessGauss1D

guess the start values of the parameters of the one-dimensional Gaussian model.

modelGauss2D

model of a two-dimensional rotated Gaussian with a constant offset.

fit

fit a model function to data.

Examples

Fit the model to a profile given as arrays of positions and values, with the start values guessed from the data and with the offset fitted together with the other parameters.

>>> params = fredtools.guessGauss1D(vec, pos)
>>> result = fredtools.fit(fredtools.modelGauss1D, vec, pos, params=params)

Fit the model without the background, i.e. with the offset fixed to zero.

>>> params = fredtools.guessGauss1D(vec, pos, offset=0)
>>> result = fredtools.fit(fredtools.modelGauss1D, vec, pos, params=params)
fredtools.guessGauss1D(data: ArrayLike, pos: ArrayLike, mask: ArrayLike | None = None, dataRange: Sequence[int | float | number | None] | None = None, offset: int | float | number | None = None) → dict[str, fitParam]

Guess the start values of the parameters of the one-dimensional Gaussian model.

The function estimates the parameters of the modelGauss1D model from data given as arrays of values and positions, and returns them in the form to be given to fit as params. The returned parameters can be changed before the fit, e.g. to fix some of them or to change their limits.

Parameters:
  • data (array_like) – Data to be fitted, as in fit.

  • pos (array_like) – Positions of the data points, as in fit.

  • mask (array_like, optional) – Mask of the data points to be used, as in fit. (def. None)

  • dataRange (sequence of two scalars or None, optional) – Range (min, max) of the data values to be used, as in fit. (def. None)

  • offset (scalar, optional) – Known value of the constant offset (background), e.g. 0 for data without a background. The offset is then fixed to this value and not varied in the fit. If None, the start value of the offset is estimated from the data and the offset is varied in the fit. (def. None)

Returns:

Dictionary of the parameter names (‘amplitude’, ‘center’, ‘sigma’ and ‘offset’) and fitParam objects with the start values. The amplitude is limited to non-negative values and the sigma to positive values.

Return type:

dict

Raises:
  • TypeError – If data, pos, mask or offset are of a wrong type.

  • ValueError – If data is not given with a single array of positions, if fewer than 3 data points are to be used, if offset is not finite, or if the data have no peak above the offset.

See also

modelGauss1D

model of a one-dimensional Gaussian with a constant offset.

guessGauss2D

guess the start values of the parameters of the two-dimensional Gaussian model.

fit

fit a model function to data.

Notes

The same mask and dataRange should be given here and to fit. The estimation assumes a single peak of positive values, sampled at positions which are spaced more or less regularly: the start value of the offset is the 5th percentile of the used data values, the amplitude is the maximum above the offset, and the center and the sigma are calculated from the positions of the points with the values above half of the amplitude, weighted with their values.

When only the top of the peak is used (e.g. the points below half of the maximum are excluded with dataRange), the data do not show the background, and the offset should be given with offset.

Examples

>>> params = fredtools.guessGauss1D(vec, pos)
>>> params
{'amplitude': fitParam(value=7.202721887846977, min=0.0, max=inf, vary=True),
 'center': fitParam(value=1.6643742053579433, min=-inf, max=inf, vary=True),
 'sigma': fitParam(value=2.548979782983144, min=2.548979782983144e-06, max=inf, vary=True),
 'offset': fitParam(value=-0.12459074777693419, min=-inf, max=inf, vary=True)}
>>> result = fredtools.fit(fredtools.modelGauss1D, vec, pos, params=params)
>>> result.bestValues
{'amplitude': 7.0977605233129255, 'center': 1.5158130529044276, 'sigma': 2.4959199288306975, 'offset': -0.0012157684494673584}
fredtools.modelGauss2D(x: ArrayLike, y: ArrayLike, amplitude: int | float | number, centerX: int | float | number, centerY: int | float | number, sigmaX: int | float | number, sigmaY: int | float | number, rotation: int | float | number = 0, offset: int | float | number = 0) → NDArray

Model of a two-dimensional rotated Gaussian with a constant offset.

The function calculates a two-dimensional Gaussian of different widths along its two axes, rotated by any angle, on a constant background. It is defined as: amplitude * exp(-u^2 / (2 * sigmaX^2) - v^2 / (2 * sigmaY^2)) + offset, where u = (x - centerX) * cos(rotation) + (y - centerY) * sin(rotation) and v = (x - centerX) * sin(rotation) - (y - centerY) * cos(rotation) are the positions along the two axes of the Gaussian. It can be used as a model function in fit, with the start values of the parameters guessed with guessGauss2D.

Parameters:
  • x (array_like) – X positions at which the model is calculated.

  • y (array_like) – Y positions at which the model is calculated, of the shape of x or of a shape that can be broadcast with it.

  • amplitude (scalar) – Height of the Gaussian above the offset.

  • centerX (scalar) – X position of the maximum of the Gaussian.

  • centerY (scalar) – Y position of the maximum of the Gaussian.

  • sigmaX (scalar) – Width of the Gaussian, given as one standard deviation, along its first axis, which is the X axis rotated by rotation.

  • sigmaY (scalar) – Width of the Gaussian, given as one standard deviation, along its second axis, which is perpendicular to the first one.

  • rotation (scalar, optional) – Angle in degrees between the X axis and the first axis of the Gaussian, counted from the X axis towards the Y axis. (def. 0)

  • offset (scalar, optional) – Constant value added to the Gaussian (background). (def. 0)

Returns:

Values of the model at the given positions, of the (broadcast) shape of x and y.

Return type:

numpy.array

See also

guessGauss2D

guess the start values of the parameters of the two-dimensional Gaussian model.

modelGauss1D

model of a one-dimensional Gaussian with a constant offset.

fit

fit a model function to data.

Notes

The same Gaussian is described by more than one set of the parameters: the rotation changed by 180 degrees gives the same shape, and so does the rotation changed by 90 degrees with sigmaX and sigmaY swapped. For a round Gaussian (sigmaX equal to sigmaY), the shape does not depend on the rotation, so the rotation cannot be fitted and should be fixed.

Examples

Fit the model to a 2D SimpleITK image of a spot, with the start values guessed from the image.

>>> params = fredtools.guessGauss2D(img)
>>> result = fredtools.fit(fredtools.modelGauss2D, img, params=params)

Fit a Gaussian with the axes along the X and Y directions and without the background, i.e. with the rotation and the offset fixed to zero.

>>> params = fredtools.guessGauss2D(img, offset=0)
>>> params["rotation"] = fredtools.fitParam(0, vary=False)
>>> result = fredtools.fit(fredtools.modelGauss2D, img, params=params)
fredtools.guessGauss2D(data: ArrayLike | Image, pos: tuple[ArrayLike, ...] | None = None, mask: ArrayLike | Image | None = None, dataRange: Sequence[int | float | number | None] | None = None, offset: int | float | number | None = None) → dict[str, fitParam]

Guess the start values of the parameters of the two-dimensional Gaussian model.

The function estimates the parameters of the modelGauss2D model from data given as a 2D SimpleITK image or as arrays of values and positions, and returns them in the form to be given to fit as params. The returned parameters can be changed before the fit, e.g. to fix some of them or to change their limits.

Parameters:
  • data (array_like or SimpleITK Image) – Data to be fitted, as in fit: an array of any shape or a 2D SimpleITK image.

  • pos (tuple of two array_like, optional) – X and Y positions of the data points, as in fit. It is required when data is an array, and it must be None when data is a SimpleITK image. (def. None)

  • mask (array_like or SimpleITK Image, optional) – Mask of the data points to be used, as in fit. (def. None)

  • dataRange (sequence of two scalars or None, optional) – Range (min, max) of the data values to be used, as in fit. (def. None)

  • offset (scalar, optional) – Known value of the constant offset (background), e.g. 0 for data without a background. The offset is then fixed to this value and not varied in the fit. If None, the start value of the offset is estimated from the data and the offset is varied in the fit. (def. None)

Returns:

Dictionary of the parameter names (‘amplitude’, ‘centerX’, ‘centerY’, ‘sigmaX’, ‘sigmaY’, ‘rotation’ and ‘offset’) and fitParam objects with the start values. The amplitude is limited to non-negative values and the sigmas to positive values. The start value of the rotation is in the range from -45 to 45 degrees, i.e. sigmaX is the width along the axis of the Gaussian which is closer to the X axis.

Return type:

dict

Raises:
  • TypeError – If data, pos, mask or offset are of a wrong type.

  • ValueError – If data is not a 2D image or is not given with two arrays of positions, if fewer than 6 data points are to be used, if offset is not finite, or if the data have no peak above the offset.

See also

modelGauss2D

model of a two-dimensional rotated Gaussian with a constant offset.

guessGauss1D

guess the start values of the parameters of the one-dimensional Gaussian model.

fit

fit a model function to data.

Notes

The same mask and dataRange should be given here and to fit. The estimation assumes a single peak of positive values, sampled at positions which are spaced more or less regularly (e.g. the voxels of an image): the start value of the offset is the 5th percentile of the used data values, the amplitude is the maximum above the offset, and the center, the sigmas and the rotation are calculated from the positions of the points with the values above half of the amplitude, weighted with their values.

When only the top of the peak is used (e.g. the voxels below half of the maximum are excluded with dataRange), the data do not show the background, and the offset should be given with offset.

Examples

Fit a spot in a 2D SimpleITK image without a background, using only the voxels with the values above half of the maximum.

>>> valueMax = fredtools.getStatistics(img).GetMaximum()
>>> params = fredtools.guessGauss2D(img, dataRange=(0.5 * valueMax, None), offset=0)
>>> result = fredtools.fit(fredtools.modelGauss2D, img, params=params, dataRange=(0.5 * valueMax, None))
fredtools.modelPolynomial(degree: Annotated[int, Ge(ge=0)]) → Callable[[...], NDArray]

Create a model of a polynomial of a given degree.

The function creates a model function of a polynomial of a given degree, defined as: c0 + c1 * x + c2 * x^2 + … + cN * x^N, where N is the degree. The created function has the form polynomial(x, c0, c1, …, cN) and can be used as a model function in fit, with the start values of the parameters guessed with guessPolynomial.

Parameters:

degree (int) – Degree of the polynomial, not negative. For instance, the degree 0 gives a constant, 1 a straight line and 2 a parabola.

Returns:

Model function polynomial(x, c0, c1, …, cN) with degree + 1 parameters, where x is an array of positions and c0, c1, …, cN are the coefficients, starting from the constant term. It returns an array of the shape of x.

Return type:

callable

Raises:
  • TypeError – If degree is not an integer.

  • ValueError – If degree is negative.

See also

guessPolynomial

guess the start values of the parameters of the polynomial model.

fit

fit a model function to data.

Examples

Create a model of a parabola and calculate it for the coefficients c0=1, c1=0 and c2=2.

>>> parabola = fredtools.modelPolynomial(2)
>>> parabola([0, 1, 2], 1, 0, 2)
array([1., 3., 9.])

Fit the parabola to data given as arrays of positions and values.

>>> params = fredtools.guessPolynomial(vec, pos, 2)
>>> result = fredtools.fit(parabola, vec, pos, params=params)
>>> result.bestValues
{'c0': 1.0823631508167932, 'c1': 0.006599407074944046, 'c2': 1.9998406980262358}
fredtools.guessPolynomial(data: ArrayLike, pos: ArrayLike, degree: Annotated[int, Ge(ge=0)], mask: ArrayLike | None = None, dataRange: Sequence[int | float | number | None] | None = None) → dict[str, fitParam]

Guess the start values of the parameters of the polynomial model.

The function calculates the coefficients of the polynomial of a given degree, i.e. of the model created with modelPolynomial, from data given as arrays of values and positions, and returns them in the form to be given to fit as params. The returned parameters can be changed before the fit, e.g. to fix some of them.

Parameters:
  • data (array_like) – Data to be fitted, as in fit.

  • pos (array_like) – Positions of the data points, as in fit.

  • degree (int) – Degree of the polynomial, not negative.

  • mask (array_like, optional) – Mask of the data points to be used, as in fit. (def. None)

  • dataRange (sequence of two scalars or None, optional) – Range (min, max) of the data values to be used, as in fit. (def. None)

Returns:

Dictionary of the parameter names (‘c0’, ‘c1’, …, up to the degree) and fitParam objects with the start values, without limits.

Return type:

dict

Raises:
  • TypeError – If data, pos or mask are of a wrong type, or if degree is not an integer.

  • ValueError – If data is not given with a single array of positions, if degree is negative, or if the number of the data points to be used is not larger than the degree.

See also

modelPolynomial

create a model of a polynomial of a given degree.

fit

fit a model function to data.

Notes

The same mask and dataRange should be given here and to fit. A polynomial is linear in its coefficients, so the start values are calculated directly with the linear least squares method (numpy.polynomial.Polynomial.fit) and are already the best values for the data without uncertainties. The fit is still needed for the uncertainties of the coefficients, for the data with uncertainties (dataError), or when some coefficients are fixed or limited.

Examples

>>> params = fredtools.guessPolynomial(vec, pos, 2)
>>> result = fredtools.fit(fredtools.modelPolynomial(2), vec, pos, params=params)

Landau, Vavilov and Gauss distributions

Functions for calculating and fitting the Landau and Vavilov probability density functions, as well as their convolutions with a Gaussian, useful for instance for fitting energy deposition spectra.

fredtools.pdfLandau(x: int | float | number | Iterable[int | float | number], mpv: int | float | number, xi: int | float | number, amp: int | float | number = 1) → int | float | number | Iterable[int | float | number]

Landau probability density function (PDF).

The function generates a Landau probability density with a given most probable value (mpv), width (described with xi) and amplitude at mpv. It was adapted from [landaupy] which was implemented based on the ROOT implementation. See [landaupy] and [landaupyDocs] for more details.

Parameters:
  • x (scalar or array_like) – Point (or points) where to calculate the PDF.

  • mpv (scalar) – Position of the most probable value (MPV) of the Landau distribution.

  • xi (scalar) – Parameter ‘xi’ of the Landau distribution, it is a measure of its width.

  • amp (scalar, optional) – Amplitude of the PDF at MPV. (def. 1)

Returns:

Single value or array of values of the Landau PDF.

Return type:

scalar or numpy array

Raises:
  • TypeError – If mpv, xi or amp is not a scalar.

  • ValueError – If xi is not positive or amp is negative.

See also

fitLandau

fit Landau distribution to data.

References

fredtools.pdfLandauGauss(x: int | float | number | Iterable[int | float | number], mpv: int | float | number, xi: int | float | number, sigma: int | float | number = 0, amp: int | float | number = 1) → int | float | number | Iterable[int | float | number]

Probability density function (PDF) of Landau convoluted with a Gaussian.

The function generates a Landau convoluted with a Gaussian probability density with a given most probable value of the convoluted function (mpv), the width of Landau (described with xi), the standard deviation of Gaussian and amplitude at mpv. It was adapted from [landaupy] which was implemented based on the ROOT implementation. See [landaupyDocs] for more details.

Parameters:
  • x (scalar or array_like) – Point (or points) where to calculate the PDF.

  • mpv (scalar) – Position of the most probable value (MPV) of the convoluted distribution.

  • xi (scalar) – Parameter ‘xi’ of the Landau distribution, it is a measure of its width.

  • sigma (scalar, optional) – Standard deviation of the Gaussian distribution. (def. 0)

  • amp (scalar, optional) – Amplitude of the PDF at MPV. (def. 1)

Returns:

Array of values of the Landau convoluted with Gaussian PDF.

Return type:

numpy array

Raises:
  • TypeError – If mpv, xi, sigma or amp is not a scalar.

  • ValueError – If xi is not positive, or sigma or amp is negative.

See also

fitLandauGauss

fit Landau distribution convoluted with a Gaussian to data.

Notes

The ‘mpv’ parameter does not describe the MPV of the landau distribution but the MPV, i.e. the position of the maximum value, of the whole Landau-gauss convoluted PDF.

fredtools.pdfVavilov(x: int | float | number | Iterable[int | float | number], mpv: int | float | number, kappa: int | float | number, beta: int | float | number, scaling: int | float | number, amp: int | float | number = 1) → int | float | number | Iterable[int | float | number]

Probability density function (PDF) of Vavilov.

The function generates a Vavilov probability density with a given most probable value (mpv), amplitude (amp), as well as kappa, beta and scaling parameters. It uses the implementation of pyamtrack library [pyamtrack] that adopts the ROOT implementation [ROOTVavilov]. The implemented PDF is not a true Vavilov distribution and the scaling parameter is not included in the original ROOT implementation. Therefore, the parameters kappa and beta might not describe the real kappa and beta parameters of the ROOT Vavilov. Nevertheless, the PDF can be used for fitting the distribution to the measurement data and to retrieve the MPV but the user must be aware that, for instance, the energy calculated based on the beta parameter might be wrong.

Parameters:
  • x (scalar or array_like) – Point (or points) where to calculate the PDF.

  • mpv (scalar) – Position of the most probable value (MPV) of the distribution.

  • kappa (float) – Parameter ‘kappa’ of the Vavilov distribution. It must be in the range 0.01 <= kappa <= 12.

  • beta (float) – Parameter ‘beta’ of the Vavilov distribution. It must be in the range 0 <= beta <= 1.

  • scaling (float) – Scaling factor of the distribution.

  • amp (scalar, optional) – Amplitude of the PDF at MPV. (def. 1)

Returns:

Array of values of the Vavilov PDF.

Return type:

numpy array

Raises:
  • TypeError – If mpv, kappa, beta or amp is not a scalar.

  • ValueError – If kappa is not in the range 0.01 <= kappa <= 12, beta is not in the range 0 <= beta <= 1, or amp or scaling is negative.

See also

fitVavilov

fit Vavilov distribution to data.

fredtools.fitLandau(x: Iterable[int | float | number], y: Iterable[int | float | number], fixAmplitude: bool = False) → fitResult

Fit Landau distribution.

The function fits Landau distribution to the data given as x and y values, using the least square algorithm.

Parameters:
  • x (array_like) – X values.

  • y (array_like) – Y values.

  • fixAmplitude (bool, optional) – Determine if the amp parameter should be kept fixed (not fitted). (def. False)

Returns:

An object of the fitResult class with the results of the fit.

Return type:

fitResult

See also

fitLandauGauss

fit Landau distribution convoluted with a Gaussian to data.

fitVavilov

fit Vavilov distribution to data.

fit

fit a model function to data.

fitResult

result of a fit.

fredtools.fitLandauGauss(x: Iterable[int | float | number], y: Iterable[int | float | number], fixAmplitude: bool = False) → fitResult

Fit Landau convoluted with Gaussian distribution.

The function fits Landau convoluted with Gaussian distribution to the data given as x and y values, using the least square algorithm.

Parameters:
  • x (array_like) – X values.

  • y (array_like) – Y values.

  • fixAmplitude (bool, optional) – Determine if the amp parameter should be kept fixed (not fitted). (def. False)

Returns:

An object of the fitResult class with the results of the fit.

Return type:

fitResult

See also

fitLandau

fit Landau distribution to data.

fitVavilov

fit Vavilov distribution to data.

fit

fit a model function to data.

fitResult

result of a fit.

fredtools.fitVavilov(x: Iterable[int | float | number], y: Iterable[int | float | number], beta0: int | float | number = 0.5, kappa0: int | float | number = 0.3, scaling0: int | float | number = -1, fixAmplitude: bool = False) → fitResult

Fit Vavilov distribution.

The function fits the Vavilov distribution to the data given as x and y values, using the least square algorithm. The fitting routine is sensitive to the initial values of kappa, beta and scaling. Therefore, the results should be always validated and different initial values of the parameters can be used if needed.

Parameters:
  • x (array_like) – X values.

  • y (array_like) – Y values.

  • beta0 (scalar, optional) – Initial value of beta parameter. (def. 0.5)

  • kappa0 (scalar, optional) – Initial value of kappa parameter. (def. 0.3)

  • scaling0 (scalar, optional) – Initial value of scaling parameter. If it is less than 0 then it is calculated based on the standard deviation of the distribution. (def. -1)

  • fixAmplitude (bool, optional) – Determine if the amp parameter should be kept fixed (not fitted). (def. False)

Returns:

An object of the fitResult class with the results of the fit.

Return type:

fitResult

See also

fitLandau

fit Landau distribution to data.

fitLandauGauss

fit Landau distribution convoluted with a Gaussian to data.

fit

fit a model function to data.

fitResult

result of a fit.

Logging

FREDtools uses the standard Python logging framework. All the output produced by the functions, including the summaries requested with the displayInfo argument, is emitted through loggers. The logging verbosity and format can be controlled with the functions below.

fredtools.configureLogging(level: int = 30, console: bool = True, fileName: str | None = None, force: bool = True) → None

Configure logging for the FREDtools library.

The function configures logging for the FREDtools library. By default (force=True), any existing handlers attached to the root logger are removed and closed before the configuration is carried out, i.e. the logging is always reconfigured. If force is False, the configuration is applied only if the root logger has no handlers configured already.

Parameters:
  • level (int, optional) – Logger level. It is recommended to use levels defined in logging, such as logging.DEBUG, logging.WARNING, etc. (def. logging.WARNING)

  • console (bool, optional) – Determine if the standard console output handler should be added. (def. True)

  • fileName (str or None, optional) – File name for logging or None if no logging to file is requested. (def. None)

  • force (bool, optional) – Determine if any existing handlers attached to the root logger should be removed and closed before carrying out the configuration (def. True)

fredtools.getLogger(name: str | None = None) → Logger

Get a logger with a NullHandler attached.

The function returns a logger with a NullHandler attached. The NullHandler is attached to the logger to suppress any logging messages if no handler is attached to the logger. The NullHandler is attached only if the logger does not hold one yet, therefore repeated calls with the same name, for instance in a loop or in a long living worker process, are safe.

Parameters:

name (str or None, optional) – Name of the logger. If not provided, the name of the calling function is used. (def. None)

Returns:

logger – Logger object with a NullHandler attached.

Return type:

logging.Logger