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[tuple[Any, ...], dtype[_ScalarT]], ndarray[tuple[Any, ...], dtype[_ScalarT]]]

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 centres (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 centres (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.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.

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) ModelResult

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:

Model results of the LMFit package.

Return type:

lmfit.model.ModelResult

See also

fitLandauGauss

fit Landau distribution convoluted with a Gaussian to data.

fitVavilov

fit Vavilov distribution to data.

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

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:

Model results of the LMFit package.

Return type:

lmfit.model.ModelResult

See also

fitLandau

fit Landau distribution to data.

fitVavilov

fit Vavilov distribution to data.

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) ModelResult

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:

Model results of the LMFit package.

Return type:

lmfit.model.ModelResult

See also

fitLandau

fit Landau distribution to data.

fitLandauGauss

fit Landau distribution convoluted with a Gaussian to data.

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. Note that a new NullHandler instance is appended to the logger on every call, so repeated calls with the same name accumulate NullHandler instances.

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