Pylinac: Python Toolkit for Linear Accelerator QA

repository·master·Indexed 41 days ago

https://github.com/jrkerns/pylinac

A Python library providing TG-142 quality assurance (QA) tools for medical physics. It includes high-level modules for analyzing DICOM images from linear accelerators and CT simulators, such as ACR CT 464 and ACR MRI phantoms, as well as low-level tools for custom image analysis.

Tokens
123.7K
Snippets
380
Records
552
Agent score
52%

What's inside Pylinac

  1. Overview of Pylinac Core Modules

    master

    Pylinac's core functionality is organized into several specialized modules that can be used directly or as a foundation for building custom mixin classes and methods. The core modules include:

    • Image Module (pylinac.core.image): Handles image processing and representation.
    • Geometry Module (pylinac.core.geometry): Provides geometric primitives and calculations.
    • Profile Module (pylinac.core.profile): Manages intensity profiles.
    • I/O Module (pylinac.core.io): Handles input and output operations.
    • ROI Module (pylinac.core.roi): Manages Regions of Interest.
    • Mask Module (pylinac.core.mask): Handles image masking operations.
    • Utilities Module (pylinac.core.utilities): Contains general helper functions.
  2. Overview of Calibration (TG-51 and TRS-398)

    master

    Pylinac's calibration module is split into two submodules: tg51 and trs398, which implement their respective dosimetry protocols. Both modules provide classes and functions for calculating protocol dose.

    Key features include:

    • Helper functions: Includes PDD to TPR converters and pressure unit converters (e.g., converting various units to kPa, which is the internal standard for Pylinac).
    • Vocabulary: Note that some terms may differ from the official protocols for clarity. For example:
      • voltage_reference: The voltage used for reference readings (commonly -300V).
      • voltage_reduced: The lower voltage used to determine $k_{s}/P_{ion}$ (commonly -150V).
      • m_reference: Ion chamber reading at the reference voltage.
      • m_reduced: Ion chamber reading at the reduced voltage.
      • m_opposite: Ion chamber reading at the opposite polarity (commonly +300V).
  3. What is Pylinac?

    master

    Pylinac (pronounced "pie-linac") is a Python library designed to analyze images and datasets used by medical physicists for routine Quality Assurance (QA). It focuses on tests outlined by AAPM TG-142 and similar guidelines (e.g., MLC "picket fence" tests).

    Capabilities:

    • Consumes raw data/images to compute numeric results related to physics tests.
    • Generates plots showing the analysis.
    • Produces PDF reports containing both numerical and plot data.

    Important Limitations:

    • Not a database: Pylinac is an analysis engine, not a data repository. Users should export outputs to specialized applications like QAtrack+ or RadMachine.
    • Validation required: Pylinac is not liable for incorrect outputs. Users must always validate results against a known methodology (manual or automatic) before clinical use.
  4. What is an MLCShaper?

    master

    The MLCShaper is a tool used by the PlanGenerator to create basic shapes defined by MLCs. It generates the required control points and leaf positions for those shapes, which can then be exported as DICOM control points and meterset values. It operates on two main concepts:

    1. Static dose: The relative dose delivered after MLCs reach a target shape (e.g., an open field or a picket fence). This involves at least two control points: a start and an end position where the MLC positions are identical but the meterset value changes.
    2. Dose in transition: The relative dose delivered while moving from one shape to another (e.g., a sweeping pattern). The meterset value is incremented during this transitional move.
  5. Choose an edge detection method

    master

    Edge detection determines how field width and beam center are calculated. Use the Edge enum in the .analyze() method:

    • Edge.FWHM: Full-Width Half-Max. Traditional for flat beams; may perform poorly on FFF beams.
    • Edge.INFLECTION_HILL: Fits a Hill/sigmoid function to the edge. Best for low-resolution data (like 2D device arrays). You can tune the fit using hill_window_ratio (e.g., 0.05 for a 5% window).
    • Edge.INFLECTION_DERIVATIVE: (Default for FieldAnalysis) Uses the max/min of the derivative. Recommended for high-resolution images like EPID. You can apply smoothing to the derivative using edge_smoothing_ratio in the FieldAnalysis constructor.
    from pylinac import FieldAnalysis, Edge, Interpolation
    
    # Recommended for low-resolution device arrays
    fa = DeviceFieldAnalysis(path="data.prm")
    fa.analyze(interpolation=Interpolation.LINEAR, edge_detection_method=Edge.INFLECTION_HILL)
    
    # Using derivative method with smoothing for EPID
    fa = FieldAnalysis(path="img.dcm", edge_smoothing_ratio=0.005)
    fa.analyze(edge_detection_method=Edge.INFLECTION_DERIVATIVE)
  6. Calculate metrics using Profile plugins

    master

    Pylinac profile classes allow you to calculate various metrics (like penumbra, flatness, or symmetry) by passing a list of metric plugin instances to the compute method.

    Metrics can be accessed in two ways:

    1. Directly from the compute method: The method returns the result of the metric calculation(s).
    2. Via the metric_values attribute: The profile maintains a dictionary where keys are the plugin's name and values are the calculated results.

    Note: When passing multiple metrics, compute returns a list of results.

    # Method 1: Direct return
    penum = profile.compute(metrics=PenumbraRightMetric())
    print(penum)
    
    # Method 2: Accessing via metric_values dictionary
    profile.compute(metrics=[PenumbraRightMetric()])
    print(profile.metric_values["Right Penumbra"]
  7. Understand the TomoCheese algorithm constraints and behavior

    master

    The TomoCheese algorithm is used for analyzing Cheese phantoms. It includes automatic roll compensation by searching for high-density peaks in a circular profile at the radius of the 'outer' ROIs.

    Allowances

    • Images can be any size.
    • The phantom can have significant translation in all 3 directions.
    • The phantom can have significant roll and moderate yaw and pitch.

    Restrictions (Violations may cause failure or unreliable results)

    • The phantom cannot touch any edge of the Field of View (FOV).
    • There must be at least one ROI in the 'outer' ROI ring with a value higher than the water/background phantom to enable automatic roll compensation. If no peak is found, no correction is applied.
    • Roll compensation is only applied if the calculated distance to the nearest nominal ROI is < 5 degrees.
  8. Legacy vs Modern Profile classes

    master

    Legacy Class

    • SingleProfile: A legacy "swiss army knife" class. It is frozen and will not receive updates. While it can perform many tasks, it is more complex and less robust than the modern alternatives.

    Modern Specialized Classes

    Modern classes are more focused, robust, and allow for easier implementation of Metric Plugins. They are split into two types:

    1. Array-only classes: These deal with raw arrays without physical context.

      • FWXMProfile
      • InflectionDerivativeProfile
      • HillProfile
    2. Physical classes: Use these for data with physical dimensions (e.g., EPID or water tank scans). Most plugins require these variants.

      • FWXMProfilePhysical
      • InflectionDerivativeProfilePhysical
      • HillProfilePhysical
  9. Understand differences between Field Profile Analysis v1 and v2

    master

    The current version (v2) of the field profile analysis module differs from the original (v1) in several ways:

    • Interpolation: v2 always uses linear interpolation under the hood. In v1, if interpolation was set to None, the penumbra might be slightly larger due to edge index 'snapping' to the nearest pixel.
    • Plugin Architecture: v2 is modular and loosely coupled, making it easier to write new plugins and use metrics in other modules.
    • Device Specificity: v2 is a generic device-to-profile framework and does not perform device-specific analysis (like IC Profiler). Users are responsible for converting device-specific formats into a 1D array of values.
    • Coordinate Language: v1 used top, left, bottom, right. In v2, everything is treated as left and right. For vertical (y) profiles, rotating the profile 90 degrees counterclockwise aligns the terminology (e.g., 'top' corresponds to the y-left value).
  10. How Simulators and Layers work together

    master

    The image generation process relies on two main abstractions:

    • Simulators: Define the base image properties like pixel_size and shape. They provide the .add_layer(layer) method to build the image and a .generate_dicom() method to export the result.
    • Layers: Simple structures that modify the image. Every layer must implement an .apply(image, pixel_size) -> image method, where image is a numpy array and the method returns the modified numpy array.

    This architecture allows for a non-deterministic pipeline where users can stack multiple effects to simulate complex radiation scenarios.

  11. Understand the purpose of the contrib module

    master

    The pylinac.contrib module contains one-off analyses and specialized protocols that are useful to specific subsets of users but are not part of the core pylinac library.

    Warning: Code in the contrib module may not be tested, is not guaranteed to work, may break in future versions, and does not have comprehensive documentation. It is provided as-is.

  12. Understand Starshot analysis restrictions and requirements

    master

    To ensure reliable results, observe the following requirements:

    Requirements:

    • The image must have at least 6 spokes (3 angles).
    • The center of the "star" must be in the central 1/3 of the image.
    • Radiation spokes must extend to both sides of the center (they must not end at the center).
    • Avoid markings like pin pricks or marker dots; if present, crop them out.

    Allowances:

    • Supports both inversion (darker or brighter radiation).
    • Supports any image size.
    • Supports DICOM (EPID) or most scanned film formats.
    • If using multiple images, they must all be the same size.