# Core Modules Documentation¶

The following is the API documentation for the core modules of pylinac. These can be used directly, or as the base for mixin classes or methods.

## Image Module¶

This module holds classes for image loading and manipulation.

pylinac.core.image.prepare_for_classification(path)[source]

Load and resize the image and return as flattened numpy array. Used when converting an image into a classification feature dataset

pylinac.core.image.equate_images(image1, image2)[source]
Crop and resize two images to make them:
• The same pixel dimensions
• The same DPI

The usefulness of the function comes when trying to compare images from different sources. The best example is calculating gamma on a machine log fluence and EPID image. The physical and pixel dimensions must be normalized, the SID normalized

Parameters: image1 ({ArrayImage, DicomImage, FileImage}) – Must have DPI and SID. image2 ({ArrayImage, DicomImage, FileImage}) – Must have DPI and SID. image1 (ArrayImage) image2 (ArrayImage) – The returns are new instances of Images.
pylinac.core.image.is_image(path)[source]

Determine whether the path is a valid image file.

Returns: bool
pylinac.core.image.retrieve_image_files(path)[source]

Retrieve the file names of all the valid image files in the path.

Returns: Contains strings pointing to valid image paths. list
pylinac.core.image.load(path, **kwargs)[source]

Load a DICOM image, JPG/TIF/BMP image, or numpy 2D array.

Parameters: path (str, file-object) – The path to the image file or data stream or array. kwargs – See FileImage, DicomImage, or ArrayImage for keyword arguments. Return type depends on input image.

Examples

Load an image from a file and then apply a filter:

>>> from pylinac.core.image import load
>>> my_image = "C:\QA\image.tif"
>>> img = load(my_image)  # returns a FileImage
>>> img.filter(5)


>>> arr = np.arange(36).reshape(6, 6)
>>> img = load(arr)  # returns an ArrayImage

pylinac.core.image.load_url(url, progress_bar=True, **kwargs)[source]

Load an image from a URL.

Parameters: url (str) – A string pointing to a valid URL that points to a file. Note For some images (e.g. Github), the raw binary URL must be used, not simply the basic link. progress_bar (bool) – Whether to display a progress bar of download status.
pylinac.core.image.load_multiples(image_file_list, method='mean', stretch=True, **kwargs)[source]

Combine multiple image files into one superimposed image.

Parameters: image_file_list (list) – A list of the files to be superimposed. method ({'mean', 'max', 'sum'}) – A string specifying how the image values should be combined. stretch (bool) – Whether to normalize the images being combined by stretching their high/low values to the same values across images. kwargs – Further keyword arguments are passed to the load function.

Examples

>>> from pylinac.core.image import load_multiples
>>> paths = ['starshot1.tif', 'starshot2.tif']
>>> superimposed_img = load_multiples(paths)

class pylinac.core.image.BaseImage(path)[source]

Bases: object

Base class for the Image classes.

path

The path to the image file.

Type: str
array

The actual image pixel array.

Type: numpy.ndarray
Parameters: path (str) – The path to the image.
classmethod from_multiples(filelist, method='mean', stretch=True, **kwargs)[source]

Load an instance from multiple image items. See load_multiples().

center

Return the center position of the image array as a Point.

physical_shape

The physical size of the image in mm.

plot(ax=None, show=True, clear_fig=False, **kwargs)[source]

Plot the image.

Parameters: ax (matplotlib.Axes instance) – The axis to plot the image to. If None, creates a new figure. show (bool) – Whether to actually show the image. Set to false when plotting multiple items. clear_fig (bool) – Whether to clear the prior items on the figure before plotting.
filter(size=0.05, kind='median')[source]

Filter the profile.

Parameters: size (int, float) – Size of the median filter to apply. If a float, the size is the ratio of the length. Must be in the range 0-1. E.g. if size=0.1 for a 1000-element array, the filter will be 100 elements. If an int, the filter is the size passed. kind ({'median', 'gaussian'}) – The kind of filter to apply. If gaussian, size is the sigma value.
crop(pixels=15, edges=('top', 'bottom', 'left', 'right'))[source]

Removes pixels on all edges of the image in-place.

Parameters: pixels (int) – Number of pixels to cut off all sides of the image. edges (tuple) – Which edges to remove from. Can be any combination of the four edges.
remove_edges(pixels=15, edges=('top', 'bottom', 'left', 'right'))[source]

Removes pixels on all edges of the image in-place.

Parameters: pixels (int) – Number of pixels to cut off all sides of the image. edges (tuple) – Which edges to remove from. Can be any combination of the four edges.
flipud()[source]

Flip the image array upside down in-place. Wrapper for np.flipud()

invert()[source]

Invert (imcomplement) the image.

roll(direction='x', amount=1)[source]

Roll the image array around in-place. Wrapper for np.roll().

Parameters: direction ({'x', 'y'}) – The axis to roll over. amount (int) – The amount of elements to roll over.
rot90(n=1)[source]

Wrapper for numpy.rot90; rotate the array by 90 degrees CCW.

resize(size, interp='bilinear')[source]

Resize/scale the image.

Wrapper for scipy’s imresize:

threshold(threshold, kind='high')[source]

Apply a high- or low-pass threshold filter.

Parameters: threshold (int) – The cutoff value. kind (str) – If high (default), will apply a high-pass threshold. All values above the cutoff are left as-is. Remaining points are set to 0. If low, will apply a low-pass threshold.
as_binary(threshold)[source]

Return a binary (black & white) image based on the given threshold.

Parameters: threshold (int, float) – The threshold value. If the value is above or equal to the threshold it is set to 1, otherwise to 0. ArrayImage
dist2edge_min(point)[source]

Calculates minimum distance from given point to image edges.

Parameters: point (geometry.Point, tuple) – float
ground()[source]

Ground the profile such that the lowest value is 0.

Note

This will also “ground” profiles that are negative or partially-negative. For such profiles, be careful that this is the behavior you desire.

Returns: The amount subtracted from the image. float
normalize(norm_val='max')[source]

Normalize the image values to the given value.

Parameters: norm_val (str, number) – If a string, must be ‘max’, which normalizes the values to the maximum value. If a number, normalizes all values to that number.
check_inversion(box_size=20, position=(0.0, 0.0))[source]

Check the image for inversion by sampling the 4 image corners. If the average value of the four corners is above the average pixel value, then it is very likely inverted.

Parameters: box_size (int) – The size in pixels of the corner box to detect inversion. position (2-element sequence) – The location of the sampling boxes.
gamma(comparison_image, doseTA=1, distTA=1, threshold=0.1, ground=True, normalize=True)[source]

Calculate the gamma between the current image (reference) and a comparison image.

New in version 1.2.

The gamma calculation is based on Bakai et al eq.6, which is a quicker alternative to the standard Low gamma equation.

Parameters: comparison_image ({ArrayImage, DicomImage, or FileImage}) – The comparison image. The image must have the same DPI/DPMM to be comparable. The size of the images must also be the same. doseTA (int, float) – Dose-to-agreement in percent; e.g. 2 is 2%. distTA (int, float) – Distance-to-agreement in mm. threshold (float) – The dose threshold percentage of the maximum dose, below which is not analyzed. Must be between 0 and 1. ground (bool) – Whether to “ground” the image values. If true, this sets both datasets to have the minimum value at 0. This can fix offset errors in the data. normalize (bool) – Whether to normalize the images. This sets the max value of each image to the same value. gamma_map – The calculated gamma map. numpy.ndarray
class pylinac.core.image.DicomImage(path, *, dtype=None, dpi=None, sid=None)[source]

An image from a DICOM RTImage file.

metadata

The dataset of the file as returned by pydicom without pixel data.

Type: pydicom Dataset
Parameters: path (str, file-object) – The path to the file or the data stream. dtype (dtype, None, optional) – data type to cast the image data as. If None, will use whatever raw image format is. (The) – dpi : int, float dots-per-inch of the image, defined at isocenter. (The) – Note If a DPI tag is found in the image, that value will override the parameter, otherwise this one will be used. sid (int, float) – The Source-to-Image distance in mm.
save(filename)[source]

Save the image instance back out to a .dcm file.

Returns: A string pointing to the new filename.
sid

The Source-to-Image in mm.

dpi

The dots-per-inch of the image, defined at isocenter.

dpmm

The Dots-per-mm of the image, defined at isocenter. E.g. if an EPID image is taken at 150cm SID, the dpmm will scale back to 100cm.

cax

The position of the beam central axis. If no DICOM translation tags are found then the center is returned.

class pylinac.core.image.LinacDicomImage(path, use_filenames=False)[source]

DICOM image taken on a linac. Also allows passing of gantry/coll/couch values via the filename.

gantry_angle

Gantry angle of the irradiation.

collimator_angle

Collimator angle of the irradiation.

couch_angle

Couch angle of the irradiation.

class pylinac.core.image.FileImage(path, *, dpi=None, sid=None, dtype=None)[source]

An image from a “regular” file (.tif, .jpg, .bmp).

info

The info dictionary as generated by Pillow.

Type: dict
sid

The SID value as passed in upon construction.

Type: float
Parameters: path (str, file-object) – The path to the file or a data stream. dpi (int, float) – The dots-per-inch of the image, defined at isocenter. Note If a DPI tag is found in the image, that value will override the parameter, otherwise this one will be used. sid (int, float) – The Source-to-Image distance in mm. dtype (numpy.dtype) – The data type to cast the array as.
dpi

The dots-per-inch of the image, defined at isocenter.

dpmm

The Dots-per-mm of the image, defined at isocenter. E.g. if an EPID image is taken at 150cm SID, the dpmm will scale back to 100cm.

class pylinac.core.image.ArrayImage(array, *, dpi=None, sid=None, dtype=None)[source]

An image constructed solely from a numpy array.

Parameters: array (numpy.ndarray) – The image array. dpi (int, float) – The dots-per-inch of the image, defined at isocenter. Note If a DPI tag is found in the image, that value will override the parameter, otherwise this one will be used. sid (int, float) – The Source-to-Image distance in mm. dtype (dtype, None, optional) – The data type to cast the image data as. If None, will use whatever raw image format is.
dpmm

The Dots-per-mm of the image, defined at isocenter. E.g. if an EPID image is taken at 150cm SID, the dpmm will scale back to 100cm.

dpi

The dots-per-inch of the image, defined at isocenter.

class pylinac.core.image.DicomImageStack(folder, dtype=None, min_number=39, check_uid=True)[source]

Bases: object

A class that loads and holds a stack of DICOM images (e.g. a CT dataset). The class can take a folder or zip file and will read CT images. The images must all be the same size. Supports indexing to individual images.

images

Holds instances of DicomImage. Can be accessed via index; i.e. self[0] == self.images[0].

Type: list

Examples

Load a folder of Dicom images >>> from pylinac import image >>> img_folder = r”folder/qa/cbct/june” >>> dcm_stack = image.DicomImageStack(img_folder) # loads and sorts the images >>> dcm_stack.plot(3) # plot the 3rd image

Load a zip archive >>> img_folder_zip = r”archive/qa/cbct/june.zip” # save space and zip your CBCTs >>> dcm_stack = image.DicomImageStack.from_zip(img_folder_zip)

Load as a certain data type >>> dcm_stack_uint32 = image.DicomImageStack(img_folder, dtype=np.uint32)

Load a folder with DICOM CT images.

Parameters: folder (str) – Path to the folder. dtype (dtype, None, optional) – The data type to cast the image data as. If None, will use whatever raw image format is.
classmethod from_zip(zip_path, dtype=None)[source]

Load a DICOM ZIP archive.

Parameters: zip_path (str) – Path to the ZIP archive. dtype (dtype, None, optional) – The data type to cast the image data as. If None, will use whatever raw image format is.
static is_CT_slice(file)[source]

Test if the file is a CT Image storage DICOM file.

plot(slice=0)[source]

Plot a slice of the DICOM dataset.

Parameters: slice (int) – The slice to plot.
metadata

The metadata of the first image; shortcut attribute. Only attributes that are common throughout the stack should be used, otherwise the individual image metadata should be used.

## Geometry Module¶

Module for classes that represent common geometric objects or patterns.

pylinac.core.geometry.tan(degrees)[source]

Calculate the tangent of the given degrees.

pylinac.core.geometry.cos(degrees)[source]

Calculate the cosine of the given degrees.

pylinac.core.geometry.sin(degrees)[source]

Calculate the sine of the given degrees.

class pylinac.core.geometry.Vector(x=0, y=0, z=0)[source]

Bases: object

A vector with x, y, and z coordinates.

as_scalar()[source]

Return the scalar equivalent of the vector.

distance_to(thing)[source]

Calculate the distance to the given point.

Parameters: thing (Circle, Point, 2 element iterable) – The other point to calculate distance to.
pylinac.core.geometry.vector_is_close(vector1, vector2, delta=0.1)[source]

Determine if two vectors are with delta of each other; this is a simple coordinate comparison check.

class pylinac.core.geometry.Point(x=0, y=0, z=0, idx=None, value=None, as_int=False)[source]

Bases: object

A geometric point with x, y, and z coordinates/attributes.

Parameters: x (number-like, Point, iterable) – x-coordinate or iterable type containing all coordinates. If iterable, values are assumed to be in order: (x,y,z). y (number-like, optional) – y-coordinate idx (int, optional) – Index of point. Useful for sequential coordinates; e.g. a point on a circle profile is sometimes easier to describe in terms of its index rather than x,y coords. value (number-like, optional) – value at point location (e.g. pixel value of an image) as_int (boolean) – If True, coordinates are converted to integers.
distance_to(thing)[source]

Calculate the distance to the given point.

Parameters: thing (Circle, Point, 2 element iterable) – The other thing to calculate distance to.
as_array(only_coords=True)[source]

Return the point as a numpy array.

class pylinac.core.geometry.Circle(center_point=None, radius=None)[source]

Bases: object

A geometric circle with center Point, radius, and diameter.

Parameters: center_point (Point, optional) – Center point of the wobble circle. radius (float, optional) – Radius of the wobble circle.
diameter

Get the diameter of the circle.

plot2axes(axes, edgecolor='black', fill=False)[source]

Plot the Circle on the axes.

Parameters: axes (matplotlib.axes.Axes) – An MPL axes to plot to. edgecolor (str) – The color of the circle. fill (bool) – Whether to fill the circle with color or leave hollow.
class pylinac.core.geometry.Line(point1, point2)[source]

Bases: object

A line that is represented by two points or by m*x+b.

Notes

Calculations of slope, etc are from here: http://en.wikipedia.org/wiki/Linear_equation and here: http://www.mathsisfun.com/algebra/line-equation-2points.html

Parameters: point1 (Point, optional) – One point of the line point2 (Point, optional) – Second point along the line.
m

Return the slope of the line.

m = (y1 - y2)/(x1 - x2)

b

Return the y-intercept of the line.

b = y - m*x

y(x)[source]

Return y-value along line at position x.

x(y)[source]

Return x-value along line at position y.

center

Return the center of the line as a Point.

length

Return length of the line, if finite.

distance_to(point)[source]

Calculate the minimum distance from the line to a point.

Equations are from here: http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html #14

Parameters: point (Point, iterable) – The point to calculate distance to.
plot2axes(axes, width=1, color='w')[source]

Plot the line to an axes.

Parameters: axes (matplotlib.axes.Axes) – An MPL axes to plot to. color (str) – The color of the line.
class pylinac.core.geometry.Rectangle(width, height, center, as_int=False)[source]

Bases: object

A rectangle with width, height, center Point, top-left corner Point, and bottom-left corner Point.

Parameters: width (number) – Width of the rectangle. height (number) – Height of the rectangle. center (Point, iterable, optional) – Center point of rectangle. as_int (bool) – If False (default), inputs are left as-is. If True, all inputs are converted to integers.
br_corner

The location of the bottom right corner.

bl_corner

The location of the bottom left corner.

tl_corner

The location of the top left corner.

tr_corner

The location of the top right corner.

plot2axes(axes, edgecolor='black', angle=0.0, fill=False, alpha=1, facecolor='g')[source]

Plot the Rectangle to the axes.

Parameters: axes (matplotlib.axes.Axes) – An MPL axes to plot to. edgecolor (str) – The color of the circle. angle (float) – Angle of the rectangle. fill (bool) – Whether to fill the rectangle with color or leave hollow.

## Profile Module¶

Module of objects that resemble or contain a profile, i.e. a 1 or 2-D f(x) representation.

pylinac.core.profile.stretch(array, min=0, max=1, fill_dtype=None)[source]

‘Stretch’ the profile to the fit a new min and max value and interpolate in between. From: http://www.labri.fr/perso/nrougier/teaching/numpy.100/ exercise #17

Parameters: min (number) – The new minimum of the values max (number) – The new maximum value. fill_dtype (numpy data type) – If None (default), the array will be stretched to the passed min and max. If a numpy data type (e.g. np.int16), the array will be stretched to fit the full range of values of that data type. If a value is given for this parameter, it overrides min and max.
class pylinac.core.profile.ProfileMixin[source]

Bases: object

A mixin to provide various manipulations of 1D profile data.

invert()[source]

Invert (imcomplement) the profile.

normalize(norm_val='max')[source]

Normalize the profile to the given value.

Parameters: norm_val (str, number) – If a string, must be ‘max’, which normalizes the values to the maximum value. If a number, normalizes all values to that number.
stretch(min=0, max=1)[source]

‘Stretch’ the profile to the min and max parameter values.

Parameters: min (number) – The new minimum of the values max (number) – The new maximum value.
ground()[source]

Ground the profile such that the lowest value is 0.

Returns: The minimum value that was used as the grounding value. float
filter(size=0.05, kind='median')[source]

Filter the profile.

Parameters: size (float, int) – Size of the median filter to apply. If a float, the size is the ratio of the length. Must be in the range 0-1. E.g. if size=0.1 for a 1000-element array, the filter will be 100 elements. If an int, the filter is the size passed. kind ({'median', 'gaussian'}) – The kind of filter to apply. If gaussian, size is the sigma value.
class pylinac.core.profile.SingleProfile(values, normalize_sides=True, initial_peak=None)[source]

A profile that has one large signal, e.g. a radiation beam profile. Signal analysis methods are given, mostly based on FWXM calculations. Profiles with multiple peaks are better suited by the MultiProfile class.

Parameters: values (ndarray) – The profile numpy array. Must be 1D. normalize_sides (bool, optional) – If True (default), each side of the profile will be grounded independently. If False, the profile will be grounded by the profile global minimum. initial_peak (int, optional) – If the approximate peak of the profile is known it can be passed in. Not needed unless there is more than one major peak in the profile, e.g. a very high edge.
values

The profile array.

fwxm(x=50, interpolate=False)[source]

Return the width at X-Max, where X is the percentage height.

Parameters: x (int) – The percent height of the profile. E.g. x = 50 is 50% height, i.e. FWHM. interpolate (bool) – If True, interpolates the values to give a more accurate FWXM. The width in number of elements of the FWXM. int, float
fwxm_center(x=50, interpolate=False, kind='index')[source]

Return the center index of the FWXM.

penumbra_width(side='left', lower=20, upper=80, interpolate=False)[source]

Return the penumbra width of the profile.

This is the standard “penumbra width” calculation that medical physics talks about in radiation profiles. Standard is the 80/20 width, although 90/10 is sometimes used.

Parameters: side ({'left', 'right', 'both'}) – Which side of the profile to determined penumbra. If ‘both’, the left and right sides are averaged. lower (int) – The “lower” penumbra value used to calculate penumbra. Must be lower than upper. upper (int) – The “upper” penumbra value used to calculate penumbra. interpolate (bool) – Whether to interpolate the profile to get more accurate values. ValueError – If lower penumbra is larger than upper penumbra
field_values(field_width=0.8)[source]

Return a subarray of the values of the profile for the given field width. This is helpful for doing, e.g., flatness or symmetry calculations, where you want to calculate something over the field, not the whole profile.

Parameters: field_width (float) – The field width of the profile, based on the fwhm. Must be between 0 and 1. ndarray
field_edges(field_width=0.8, interpolate=False)[source]

Return the indices of the field width edges, based on the FWHM.

Returns: left_index, right_index
field_calculation(field_width=0.8, calculation='mean')[source]

Perform an operation on the field values of the profile. This function is useful for determining field symmetry and flatness.

Parameters: calculation ({'mean', 'median', 'max', 'min', 'area'}) – Calculation to perform on the field values. float
plot()[source]

Plot the profile.

class pylinac.core.profile.MultiProfile(values)[source]

A class for analyzing 1-D profiles that contain multiple signals. Methods are mostly for finding & filtering the signals, peaks, valleys, etc. Profiles with a single peak (e.g. radiation beam profiles) are better suited by the SingleProfile class.

values

The array of values passed in on instantiation.

Type: ndarray
peaks

List of Points, containing value and index information.

Type: list
valleys

Same as peaks, but for valleys.

Type: list
Parameters: values (iterable) – Array of profile values.
plot(show_peaks=True)[source]

Plot the profile.

Parameters: show_peaks (bool) – Whether to plot the peak locations as well. Will not show if a peak search has not yet been done.
find_peaks(threshold=0.3, min_distance=0.05, max_number=None, search_region=(0.0, 1.0), kind='index')[source]

Find the peaks of the profile using a simple maximum value search. This also sets the peaks attribute.

Parameters: threshold (int, float) – The value the peak must be above to be considered a peak. This removes “peaks” that are in a low-value region. If passed an int, the actual value is the threshold. E.g. when passed 15, any peak less with a value <15 is removed. If passed a float, it will threshold as a percent. Must be between 0 and 1. E.g. when passed 0.4, any peak <40% of the maximum value will be removed. min_distance (int, float) – If passed an int, parameter is the number of elements apart a peak must be from neighboring peaks. If passed a float, must be between 0 and 1 and represents the ratio of the profile to exclude. E.g. if passed 0.05 with a 1000-element profile, the minimum peak width will be 0.05*1000 = 50 elements. max_number (int, None) – Specify up to how many peaks will be returned. E.g. if 3 is passed in and 5 peaks are found, only the 3 largest peaks will be returned. If None, no limit will be applied. search_region (tuple of ints, floats, or both) – The region within the profile to search. The tuple specifies the (left, right) edges to search. This allows exclusion of edges from the search. If a value is an int, it is taken as is. If a float, must be between 0 and 1 and is the ratio of the profile length. The left value must be less than the right. kind ({'value', 'index'}) – What kind of return is given. If ‘index’ (default), returns the index of the point desired. If ‘value’, returns the value of the profile at the given index. Either the values or indices of the peaks. ndarray
find_valleys(threshold=0.3, min_distance=0.05, max_number=None, search_region=(0.0, 1.0), kind='index')[source]

Find the valleys (minimums) of the profile using a simple minimum value search.

Returns: Either the values or indices of the peaks. ndarray

find_peaks() : Further parameter info.

find_fwxm_peaks(x=50, threshold=0.3, min_distance=0.05, max_number=None, search_region=(0.0, 1.0), kind='index', interpolate=False, interpolation_factor=100, interpolation_type='linear')[source]

Find peaks using the center of the FWXM (rather than by max value).

Parameters: x (int, float) – The Full-Width-X-Maximum desired. E.g. 0.7 will return the FW70%M. Values must be between 0 and 100. interpolate (bool) – Whether to interpolate the profile to determine a more accurate peak location. interpolation_factor (int) – The interpolation multiplication factor. E.g. if 10, the profile is interpolated to have 10x the number of values. Only used if interpolate is True. interpolation_type ({'linear', 'cubic'}) – The type of interpolation to perform. Only used if interpolate is True.

find_peaks()
Further parameter info
subdivide(interpolation_factor=100, interpolation_type='linear')[source]

Subdivide the profile data into SingleProfiles.

Returns: List of SingleProfile list
class pylinac.core.profile.CircleProfile(center, radius, image_array, start_angle=0, ccw=True, sampling_ratio=1.0)[source]

A profile in the shape of a circle.

image_array

The 2D image array.

Type: ndarray
start_angle

Starting position of the profile in radians; 0 is right (0 on unit circle).

Type: int, float
ccw

How the profile is/was taken; clockwise or counter-clockwise.

Type: bool
Parameters: image_array (ndarray) – The 2D image array. start_angle (int, float) – Starting position of the profile in radians; 0 is right (0 on unit circle). ccw (bool) – If True (default), the profile will proceed counter-clockwise (the direction on the unit circle). If False, will proceed clockwise. sampling_ratio (float) – The ratio of pixel sampling to real pixels. E.g. if 1.0, the profile will have approximately the same number of elements as was encountered in the profile. A value of 2.0 will sample the profile at 2x the number of elements.

Circle : Further parameter info.

size

The elemental size of the profile.

x_locations

The x-locations of the profile values.

y_locations

The x-locations of the profile values.

find_peaks(threshold=0.3, min_distance=0.05, max_number=None, search_region=(0.0, 1.0), kind='index')[source]

Overloads Profile to also map peak locations to the image.

find_valleys(threshold=0.3, min_distance=0.05, max_number=None, search_region=(0.0, 1.0), kind='index')[source]

Overload Profile to also map valley locations to the image.

find_fwxm_peaks(x=50, threshold=0.3, min_distance=0.05, max_number=None, search_region=(0.0, 1.0), kind='index', interpolate=False, interpolation_factor=100, interpolation_type='linear')[source]

Overloads Profile to also map the peak locations to the image.

roll(amount)[source]

Roll the profile and x and y coordinates.

plot2axes(axes=None, edgecolor='black', fill=False, plot_peaks=True)[source]

Plot the circle to an axes.

Parameters: axes (matplotlib.Axes, None) – The axes to plot on. If None, will create a new figure of the image array. edgecolor (str) – Color of the Circle; must be a valid matplotlib color. fill (bool) – Whether to fill the circle. matplotlib keyword. plot_peaks (bool) – If True, plots the found peaks as well.
class pylinac.core.profile.CollapsedCircleProfile(center, radius, image_array, start_angle=0, ccw=True, sampling_ratio=1.0, width_ratio=0.1, num_profiles=20)[source]

A circular profile that samples a thick band around the nominal circle, rather than just a 1-pixel-wide profile to give a mean value.

Parameters: width_ratio (float) – The “thickness” of the band to sample. The ratio is relative to the radius. E.g. if the radius is 20 and the width_ratio is 0.2, the “thickness” will be 4 pixels. num_profiles (int) – The number of profiles to sample in the band. Profiles are distributed evenly within the band.

CircleProfile : Further parameter info.

size

The elemental size of the profile.

plot2axes(axes=None, edgecolor='black', fill=False, plot_peaks=True)[source]

Add 2 circles to the axes: one at the maximum and minimum radius of the ROI.

plot2axes() : Further parameter info.

pylinac.core.profile.peak_detect(values, threshold=None, min_distance=10, max_number=None, search_region=(0.0, 1.0), find_min_instead=False)[source]

Find the peaks or valleys of a 1D signal.

Uses the difference (np.diff) in signal to find peaks. Current limitations include:
1. Only for use in 1-D data; 2D may be possible with the gradient function.
2. Will not detect peaks at the very edge of array (i.e. 0 or -1 index)
Parameters: values (array-like) – Signal values to search for peaks within. threshold (int, float) – The value the peak must be above to be considered a peak. This removes “peaks” that are in a low-value region. If passed an int, the actual value is the threshold. E.g. when passed 15, any peak less with a value <15 is removed. If passed a float, it will threshold as a percent. Must be between 0 and 1. E.g. when passed 0.4, any peak <40% of the maximum value will be removed. min_distance (int, float) – If passed an int, parameter is the number of elements apart a peak must be from neighboring peaks. If passed a float, must be between 0 and 1 and represents the ratio of the profile to exclude. E.g. if passed 0.05 with a 1000-element profile, the minimum peak width will be 0.05*1000 = 50 elements. max_number (int) – Specify up to how many peaks will be returned. E.g. if 3 is passed in and 5 peaks are found, only the 3 largest peaks will be returned. find_min_instead (bool) – If False (default), peaks will be returned. If True, valleys will be returned. max_vals (numpy.array) – The values of the peaks found. max_idxs (numpy.array) – The x-indices (locations) of the peaks. ValueError – If float not between 0 and 1 passed to threshold.

## I/O Module¶

I/O helper functions for pylinac.

pylinac.core.io.is_dicom(file)[source]

Boolean specifying if file is a proper DICOM file.

This function is a pared down version of read_preamble meant for a fast return. The file is read for a proper preamble (‘DICM’), returning True if so, and False otherwise. This is a conservative approach.

Parameters: file (str) – The path to the file.

pydicom.filereader.read_preamble(), pydicom.filereader.read_partial()

pylinac.core.io.is_dicom_image(file)[source]

Boolean specifying if file is a proper DICOM file with a image

Parameters: file (str) – The path to the file.

pydicom.filereader.read_preamble(), pydicom.filereader.read_partial()

pylinac.core.io.retrieve_dicom_file(file)[source]

Read and return the DICOM dataset.

Parameters: file (str) – The path to the file.
pylinac.core.io.is_zipfile(file)[source]

Wrapper function for detecting if file is a true ZIP archive

class pylinac.core.io.TemporaryZipDirectory(zfile)[source]

Bases: tempfile.TemporaryDirectory

Creates a temporary directory that unpacks a ZIP archive.

Parameters: zfile (str) – String that points to a ZIP archive.
pylinac.core.io.retrieve_filenames(directory, func=None, recursive=True, **kwargs)[source]

Retrieve file names in a directory.

Parameters: directory (str) – The directory to walk over recursively. func (function) – The function that validates if the file name should be kept. If None, no validation will be performed and all file names will be returned. recursive (bool) – Whether to search only the root directory. kwargs – Additional arguments passed to the function.
pylinac.core.io.retrieve_demo_file(url)[source]

Retrieve the demo file either by getting it from file or from a URL.

If the file is already on disk it returns the file name. If the file isn’t on disk, get the file from the URL and put it at the expected demo file location on disk for lazy loading next time.

Parameters: url (str) – The suffix to the url (location within the S3 bucket) pointing to the demo file.
pylinac.core.io.is_url(url)[source]

Determine whether a given string is a valid URL.

Parameters: url (str) – bool
pylinac.core.io.get_url(url, destination=None, progress_bar=True)[source]

Download a URL to a local file.

Parameters: url (str) – The URL to download. destination (str, None) – The destination of the file. If None is given the file is saved to a temporary directory. progress_bar (bool) – Whether to show a command-line progress bar while downloading. filename – The location of the downloaded file. str

Notes

Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm

## ROI Module¶

pylinac.core.roi.bbox_center(region)[source]

Return the center of the bounding box of an scikit-image region.

Parameters: region – A scikit-image region as calculated by skimage.measure.regionprops(). point Point
class pylinac.core.roi.DiskROI(array, angle, roi_radius, dist_from_center, phantom_center)[source]

An class representing a disk-shaped Region of Interest.

Parameters: array (ndarray) – The 2D array representing the image the disk is on. angle (int, float) – The angle of the ROI in degrees from the phantom center. roi_radius (int, float) – The radius of the ROI from the center of the phantom. dist_from_center (int, float) – The distance of the ROI from the phantom center. phantom_center (tuple) – The location of the phantom center.
pixel_value

The median pixel value of the ROI.

std

The standard deviation of the pixel values.

circle_mask[source]

Return a mask of the image, only showing the circular ROI.

class pylinac.core.roi.LowContrastDiskROI(array, angle, roi_radius, dist_from_center, phantom_center, contrast_threshold=None, background=None, cnr_threshold=None)[source]

A class for analyzing the low-contrast disks.

Parameters: contrast_threshold (float, int) – The threshold for considering a bubble to be “seen”.
contrast_to_noise

(Signal - Background)/Stdev.

Type: The contrast to noise ratio of the bubble
contrast

(ROI - backg) / (ROI + backg).

Type: The contrast of the bubble compared to background
cnr_constant

The contrast-to-noise value times the bubble diameter.

contrast_constant

The contrast value times the bubble diameter.

passed

Whether the disk ROI contrast passed.

passed_contrast_constant

Boolean specifying if ROI pixel value was within tolerance of the nominal value.

passed_cnr_constant

Boolean specifying if ROI pixel value was within tolerance of the nominal value.

plot_color

Return one of two colors depending on if ROI passed.

plot_color_constant

Return one of two colors depending on if ROI passed.

plot_color_cnr

Return one of two colors depending on if ROI passed.

class pylinac.core.roi.HighContrastDiskROI(array, angle, roi_radius, dist_from_center, phantom_center, contrast_threshold, mtf_norm=None)[source]

A class for analyzing the high-contrast disks.

Parameters: contrast_threshold (float, int) – The threshold for considering a bubble to be “seen”.
mtf

(ROI - backg) / (ROI + backg).

Type: The contrast of the bubble compared to background
passed

Boolean specifying if ROI pixel value was within tolerance of the nominal value.

plot_color

Return one of two colors depending on if ROI passed.

max

The max pixel value of the ROI.

min

The min pixel value of the ROI.

class pylinac.core.roi.RectangleROI(array, width, height, angle, dist_from_center, phantom_center)[source]

Class that represents a rectangular ROI.

pixel_array

The pixel array within the ROI.

Module for processing “masked” arrays, i.e. binary images.

pylinac.core.mask.bounding_box(array)[source]

Get the bounding box values of an ROI in a 2D array.

pylinac.core.mask.filled_area_ratio(array)[source]

Return the ratio of filled pixels to empty pixels in the ROI bounding box.

For example a solid square would be 1.0, while a sold circle would be ~0.785.

pylinac.core.mask.square_ratio(array)[source]

Determine the width/height ratio of the ROI

pylinac.core.mask.sector_mask(shape, center, radius, angle_range=(0, 360))[source]

Return a circular arc-shaped boolean mask.

Parameters: shape (tuple) – Shape of the image matrix. Usually easiest to pass something like array.shape center (Point, iterable) – The center point of the desired mask. radius (int, float) – Radius of the mask. angle_range (iterable) – The angle range of the mask. E.g. the default (0, 360) creates an entire circle. The start/stop angles should be given in clockwise order. 0 is right (0 on unit circle).

References

## Utilities Module¶

Utility functions for pylinac.

pylinac.core.utilities.clear_data_files()[source]

Delete all demo files, image classifiers, etc from the demo folder

pylinac.core.utilities.assign2machine(source_file, machine_file)[source]

Assign a DICOM RT Plan file to a specific machine. The source file is overwritten to contain the machine of the machine file.

Parameters: source_file (str) – Path to the DICOM RTPlan file that contains the fields/plan desired (e.g. a Winston Lutz set of fields or Varian’s default PF files). machine_file (str) – Path to a DICOM RTPlan file that has the desired machine. This is easily obtained from pushing a plan from the TPS for that specific machine. The file must contain at least one valid field.
pylinac.core.utilities.is_close(val, target, delta=1)[source]

Return whether the value is near the target value(s).

Parameters: val (number) – The value being compared against. target (number, iterable) – If a number, the values are simply evaluated. If a sequence, each target is compared to val. If any values of target are close, the comparison is considered True. bool
pylinac.core.utilities.typed_property(name, expected_type_or_tuple_of_types)[source]

Type-enforced property. Python Cookbook 9.21 (3rd ed).

pylinac.core.utilities.simple_round(number, decimals=0)[source]

Round a number to the given number of decimals. Fixes small floating number errors.

pylinac.core.utilities.isnumeric(object)[source]

Check whether the passed object is numeric in any sense.

pylinac.core.utilities.is_iterable(object)[source]

Determine if an object is iterable.

pylinac.core.utilities.minmax_scale(array, feature_range=(0, 1), axis=0, copy=True)[source]

Copy of scikit-learn’s minmax_scale function. Reproduced here for backwards compatibility.

class pylinac.core.utilities.Structure(**kwargs)[source]

Bases: object

A simple structure that assigns the arguments to the object.

pylinac.core.utilities.decode_binary(file, dtype, num_values=1, cursor_shift=0)[source]

Read in a raw binary file and convert it to given data types.

Parameters: file (file object) – The open file object. dtype (int, float, str) – The expected data type to return. If int or float, will return numpy array. num_values (int) – The expected number of dtype to return Note This is not the same as the number of bytes. cursor_shift (int) – The number of bytes to move the cursor forward after decoding. This is used if there is a reserved section after the read-in segment.
pylinac.core.utilities.open_path(path)[source]

Open the specified path in the system default viewer.

## Decorators Module¶

pylinac.core.decorators.timethis(func)[source]

Report execution time of function.

pylinac.core.decorators.type_accept(*type_args, **type_kwargs)[source]

Decorator to check function/method input types. Based on Python Cookbook 3rd ed. #9.7.

pylinac.core.decorators.value_accept(*value_args, **value_kwargs)[source]

Decorator to check function/method input types. Based on Python Cookbook 3rd ed. #9.7.

pylinac.core.decorators.convert_dictvals2tuple(args)[source]

Convert from dictionary to tuple of dictionary values.