Package sc.fiji.snt

Class PathAndFillManager

All Implemented Interfaces:
ij3d.UniverseListener, ContentHandler, DTDHandler, EntityResolver, ErrorHandler

public class PathAndFillManager extends DefaultHandler implements ij3d.UniverseListener
The PathAndFillManager is responsible for importing, handling and managing of Paths and Fills. Typically, a PathAndFillManager is accessed from a SNT instance, but accessing a PathAndFillManager directly is useful for batch/headless operations.
Author:
Mark Longair, Tiago Ferreira, Cameron Arshadi
  • Field Details

    • TRACES_FILE_TYPE_COMPRESSED_XML

      protected static final int TRACES_FILE_TYPE_COMPRESSED_XML
      See Also:
    • TRACES_FILE_TYPE_UNCOMPRESSED_XML

      protected static final int TRACES_FILE_TYPE_UNCOMPRESSED_XML
      See Also:
    • TRACES_FILE_TYPE_SWC

      protected static final int TRACES_FILE_TYPE_SWC
      See Also:
    • TRACES_FILE_TYPE_ML_JSON

      protected static final int TRACES_FILE_TYPE_ML_JSON
      See Also:
    • TRACES_FILE_TYPE_NDF

      protected static final int TRACES_FILE_TYPE_NDF
      See Also:
    • TRACES_FILE_TYPE_NEUROLUCIDA

      protected static final int TRACES_FILE_TYPE_NEUROLUCIDA
      See Also:
    • plugin

      protected SNT plugin
    • enableUIupdates

      protected boolean enableUIupdates
    • unsavedPaths

      protected volatile boolean unsavedPaths
  • Constructor Details

    • PathAndFillManager

      public PathAndFillManager()
      Instantiates a new PathAndFillManager using default values. Voxel dimensions are inferred from the first imported set of nodes.
    • PathAndFillManager

      protected PathAndFillManager(SNT plugin)
    • PathAndFillManager

      public PathAndFillManager(double x_spacing, double y_spacing, double z_spacing, String spacing_units)
      Instantiates a new PathAndFillManager imposing specified pixel dimensions, which may be required for pixel operations. New Paths created under this instance, will adopt the specified spacing details.
      Parameters:
      x_spacing - the 'voxel width'
      y_spacing - the 'voxel height'
      z_spacing - the 'voxel depth'
      spacing_units - the spacing units (e.g., 'um', 'mm)
  • Method Details

    • syncSpatialSettingsWithPlugin

      protected void syncSpatialSettingsWithPlugin()
    • assignSpatialSettings

      public void assignSpatialSettings(ij.ImagePlus imp)
    • assignSpatialSettings

      protected ij.measure.Calibration assignSpatialSettings(net.imagej.Dataset dataset)
    • assignSpatialSettings

      protected ij.measure.Calibration assignSpatialSettings(net.imagej.ImgPlus<?> imgPlus)
    • resetSpatialSettings

      protected void resetSpatialSettings(boolean alsoResetPaths)
    • rebuildRelationships

      protected void rebuildRelationships()
      Rebuild relationships. Will wipe existing fitted flavors.
    • size

      public int size()
      Returns the number of Paths in the PathAndFillManager list.
      Returns:
      the number of Paths
    • addPathAndFillListener

      public void addPathAndFillListener(sc.fiji.snt.PathAndFillListener listener)
      Adds a PathAndFillListener. This is used by the interface to have changes in the path manager reported so that they can be reflected in the UI.
      Parameters:
      listener - the listener
    • getPath

      public Path getPath(int i)
      Returns the Path at the specified position in the PathAndFillManager list.
      Parameters:
      i - the index of the Path
      Returns:
      the Path at the specified index
    • getPathFromName

      public Path getPathFromName(String name, boolean caseSensitive)
      Returns the Path with the specified name.
      Parameters:
      name - the name of the Path to be retrieved
      caseSensitive - If true, case considerations are ignored
      Returns:
      the Path with the specified name, or null if name was not found.
    • getPathFrom3DViewerName

      protected Path getPathFrom3DViewerName(String name)
    • getPathFromID

      public Path getPathFromID(int id)
      Returns the Path with the specified id.
      Parameters:
      id - the id of the Path to be retrieved
      Returns:
      the Path with the specified id, or null if id was not found.
    • setSelected

      protected void setSelected(Collection<Path> selectedPaths, Object sourceOfMessage)
    • isSelected

      public boolean isSelected(Path path)
      Checks if a Path is currently selected in the GUI.
      Parameters:
      path - the path to be checked
      Returns:
      true, if is selected
    • getSelectedPaths

      public Set<Path> getSelectedPaths()
      Gets all paths selected in the GUI
      Returns:
      the collection of selected paths
    • getPathsInROI

      public Collection<Path> getPathsInROI(ij.gui.Roi roi)
    • anySelected

      public boolean anySelected()
      Checks whether at least one Path is currently selected in the UI.
      Returns:
      true, if successful
    • getSWCFileForIndex

      protected File getSWCFileForIndex(String prefix, int index)
    • exportAllPathsAsSWC

      public boolean exportAllPathsAsSWC(String baseFilename)
      Exports all as Paths as SWC file(s). Multiple files are created if multiple Trees exist.
      Parameters:
      baseFilename - the file path (including common basename) for exported files. The .swc extension can be omitted. Each traced structure will be saved into a dedicated file using a 3-digits identifier. E.g., if only a single structure exists, specifying /path/to/results, generates a /path/to/results-000.swc file.
      Returns:
      true, if successful
    • exportTree

      public boolean exportTree(int treeIndex, File file)
    • savetoFileOrFileSeries

      protected boolean savetoFileOrFileSeries(File file)
    • exportAllPathsAsSWC

      protected boolean exportAllPathsAsSWC(Path[] primaryPaths, String baseFilename, String commonFileHeader)
    • exportConnectedStructureAsSWC

      protected boolean exportConnectedStructureAsSWC(Path primaryPath, File swcFile, String commonFileHeader)
    • setHeadless

      public void setHeadless(boolean headless)
      Sets whether this PathAndFillManager instance should run headless.
      Parameters:
      headless - true to activate headless calls, otherwise false
    • flushSWCPoints

      protected void flushSWCPoints(List<SWCPoint> swcPoints, PrintWriter pw, String commonFileHeader)
    • usingNonPhysicalUnits

      protected boolean usingNonPhysicalUnits()
    • updateBoundingBox

      protected void updateBoundingBox()
    • getBoundingBox

      public BoundingBox getBoundingBox(boolean compute)
      Returns the BoundingBox enclosing all nodes of all existing Paths.
      Parameters:
      compute - If true, BoundingBox dimensions will be computed for all the existing Paths. If false, the last computed BoundingBox will be returned. Also, if BoundingBox is not scaled, its spacing will be computed from the smallest inter-node distance of an arbitrary ' large' Path. Computations of Path boundaries typically occur during import operations.
      Returns:
      the BoundingBox enclosing existing nodes, or an 'empty' BoundingBox if no computation of boundaries has not yet occurred. Output is never null.
    • allPathsShareSameSpatialCalibration

      protected boolean allPathsShareSameSpatialCalibration()
    • getPathsStructured

      public Path[] getPathsStructured()
    • getTrees

      public Collection<Tree> getTrees()
      Returns all the paths associated with this PathAndFillManager instance, grouped by Tree.
      Returns:
      the Trees associated with this PathAndFillManager instance
    • getTree

      public Tree getTree(String treeLabel)
      Returns the specified Tree.
      Parameters:
      treeLabel - the Tree's label
      Returns:
      the tree or null if this PathAndFillManager instance holds no such treeLabel
      See Also:
    • getTree

      public Tree getTree(int treeId)
      Returns the specified Tree.
      Parameters:
      treeId - the Tree's id
      Returns:
      the tree or null if this PathAndFillManager instance holds no such treeId
      See Also:
    • multipleTreesExist

      protected boolean multipleTreesExist()
    • getPathsStructured

      public Path[] getPathsStructured(Collection<Path> paths)
    • getSWCFor

      public List<SWCPoint> getSWCFor(Collection<Path> paths) throws SWCExportException
      Converts a collection of connected Path objects into SWC points for export.

      SWC is the standardized format used for neuromorphological data exchange. The conversion process:

      • Validates that paths form a proper tree structure with exactly one primary path (tree's root)
      • Uses breadth-first traversal to ensure correct parent-child relationships
      • Assigns sequential SWC IDs starting from 1
      • Establishes proper parent references based on path connectivity
      • Preserves path properties including SWC type, color, annotations, and custom tags

      Path Requirements:

      • Must contain exactly one primary path (root of the tree)
      • All non-primary paths must have valid parent relationships
      • Paths must form a connected tree structure (no disconnected components)
      • Empty paths (size == 0) are automatically skipped
      Parameters:
      paths - the collection of Path objects to convert. Must contain exactly one primary path and form a connected tree structure. Empty paths are automatically skipped. Cannot be null or empty.
      Returns:
      a list of SWCPoint objects representing the neuronal structure in SWC format. Points are ordered by their sequential SWC IDs, with proper parent-child relationships established. The list is never null but may be empty if all input paths are empty.
      Throws:
      SWCExportException - if the input paths do not form a valid tree structure:
      See Also:
    • resetListeners

      public void resetListeners(Path justAdded)
    • resetListeners

      protected void resetListeners(Path justAdded, boolean expandAll)
    • addTree

      public void addTree(Tree tree)
      Adds a Tree. If an image is currently being traced, it is assumed it is large enough to contain the tree.
      Parameters:
      tree - the collection of paths to be added
    • addTree

      public void addTree(Tree tree, String commonTag)
      Adds a Tree. If an image is currently being traced, it is assumed it is large enough to contain the tree.
      Parameters:
      tree - the collection of paths to be added
      commonTag - a custom name tag to be applied to all Paths
    • addTrees

      public void addTrees(Collection<Tree> trees, String commonTag)
      Adds a collection of Trees.
      Parameters:
      trees - the collection of trees to be added
      commonTag - a custom name tag to be applied to all Paths
    • addTrees

      public void addTrees(Collection<Tree> trees)
      Adds a collection of Trees.
      Parameters:
      trees - the collection of trees to be added
    • addPath

      public void addPath(Path p)
      Adds a new path.
      Parameters:
      p - the Path to be added
    • addPath

      public void addPath(Path p, boolean forceNewName, boolean forceNewId)
    • addPath

      protected void addPath(Path p, boolean forceNewName, boolean forceNewId, boolean assumeMaxUsedTreeID)
    • addPath

      public void addPath(Path p, int id, int treeID)
    • getDefaultName

      protected String getDefaultName(Path p)
    • deletePath

      public boolean deletePath(int index)
      Deletes a Path by index
      Parameters:
      index - the index (zero-based) of the Path to be deleted
      Returns:
      true, if index is valid and Path was successfully deleted
    • deletePath

      public boolean deletePath(Path p)
      Deletes a path.
      Parameters:
      p - the path to be deleted
      Returns:
      true, if path was found and successfully deleted
    • deletePaths

      public boolean deletePaths(Collection<Path> paths)
      Deletes a collection of paths. If present, the UI is only updated once operation completes.
      Parameters:
      paths - the collection to be deleted
      Returns:
      true, if all Paths in the collection were found and successfully deleted
    • deletePaths

      public void deletePaths(int[] indices)
      Delete paths by position.
      Parameters:
      indices - the indices to be deleted
    • addFill

      protected void addFill(Fill fill)
    • deleteFills

      protected void deleteFills(int[] indices)
    • getLoadedFills

      public Map<Fill,FillerThread> getLoadedFills()
    • reloadFills

      protected void reloadFills(int[] selectedIndices)
    • writeXML

      protected void writeXML(String fileName, boolean compress) throws IOException
      Throws:
      IOException
    • startElement

      public void startElement(String uri, String localName, String qName, Attributes attributes) throws TracesFileFormatException
      Specified by:
      startElement in interface ContentHandler
      Overrides:
      startElement in class DefaultHandler
      Throws:
      TracesFileFormatException
    • endElement

      public void endElement(String uri, String localName, String qName) throws TracesFileFormatException
      Specified by:
      endElement in interface ContentHandler
      Overrides:
      endElement in class DefaultHandler
      Throws:
      TracesFileFormatException
    • createFromFile

      public static PathAndFillManager createFromFile(String filePath, int... swcTypes)
      Creates a PathAndFillManager instance from imported data
      Parameters:
      filePath - the absolute path of the file to be imported as per load(String, int...)
      Returns:
      the PathAndFillManager instance, or null if file could not be imported
    • createFromNodes

      public static PathAndFillManager createFromNodes(Collection<SWCPoint> nodes)
      Creates a PathAndFillManager instance from a collection of reconstruction nodes.
      Parameters:
      nodes - the collection of reconstruction nodes. Nodes will be sorted by id and any duplicate entries pruned.
      Returns:
      the PathAndFillManager instance, or null if file could not be imported
    • createFromGraph

      public static PathAndFillManager createFromGraph(DirectedWeightedGraph graph, boolean keepTreePathStructure)
      Create a new PathAndFillManager instance from the graph.
      Parameters:
      graph - The input graph
      keepTreePathStructure - Whether to maintain the path hierarchy of the Tree backing the input graph. If this is set to true, the graph must have been created from operations on at least one Tree. Note that even if the graph is backed by a Tree, this may not always be possible. For instance, consider the case where two graphs oriented in opposing directions are merged at an edge. One graph will need to be re-oriented, which will change the Path hierarchy of the result.
    • importGraph

      protected void importGraph(DirectedWeightedGraph graph)
    • importGraphWithPathStructure

      protected void importGraphWithPathStructure(DirectedWeightedGraph graph)
    • clear

      public void clear()
      Deletes all paths and fills.
    • dispose

      public void dispose()
    • resetIDs

      protected void resetIDs()
    • importSWC

      public boolean importSWC(String descriptor, String urlOrFilePath)
      Imports an SWC file using default settings.
      Parameters:
      descriptor - the identifier for the imported data
      urlOrFilePath - the URL pointing to the SWC file or the absolute file path of a local file. Note that with URLs, https may not be supported.
      Returns:
      true, if import was successful
      See Also:
    • importSWCs

      public List<Tree> importSWCs(Map<String,String> swcs, org.scijava.util.ColorRGB color)
      Imports a group of SWC files (Remote URLs supported).
      Parameters:
      swcs - the HashMap containing the absolute file paths (or URLs) of files to be imported as values and a file descriptor as keys.
      color - the color to be applied to imported Paths. If null, paths from each file will be assigned unique colors
      Returns:
      the List of imported Trees labeled after the file descriptor. The returned list will not contain null elements: If a file was not successfully imported an empty Tree will be generated
      See Also:
    • importSWC

      protected boolean importSWC(BufferedReader br, String descriptor, boolean assumeCoordinatesInVoxels, double xOffset, double yOffset, double zOffset, double xScale, double yScale, double zScale, double rScale, boolean replaceAllPaths, int... swcTypes)
      Imports SWC data with advanced settings. The SWC format is described in PMID 9821633 and e.g., neuromorpho.org It is named after the initials of Stockley, Wheal, and Cole, who earlier developed a pioneer system for morphometric reconstructions (PMID 8321013).

      Annoyingly, While the SWC specification details the usage of of world coordinates in microns, some published SWC files have adopted image (pixel) coordinates, which is inappropriate and less useful (an example of the latter seems to part of the DIADEM Challenge data set). In addition, it's not clear what the "radius" column is meant to mean in such files.

      Parameters:
      br - the character stream containing the data
      descriptor - the label describing the Tree associated with the data
      assumeCoordinatesInVoxels - If true, the SWC coordinates are assumed to be in image coordinates ("pixels"). Note that in this case, radii will be scaled by the minimum voxel separation. This workaround seems to be required to properly import unscaled files
      xOffset - the offset to be applied to all X coordinates. May be useful to import data obtained from multiple "un-stitched" fields of view. Default is 0.
      yOffset - the offset to be applied to all Y coordinates. May be useful to import data obtained from multiple "un-stitched" fields of view. Default is 0.
      zOffset - the offset to be applied to all Z coordinates. May be useful to import data obtained from multiple "un-stitched" fields of view. Default is 0.
      xScale - the scaling factor for all X coordinates. Useful to import data onto downsampled images. Default is 1.
      yScale - the scaling factor for all Y coordinates. Useful to import data onto downsampled images. Default is 1.
      zScale - the scaling factor for all Z coordinates. Useful to import data onto downsampled images. Default is 1.
      rScale - the scaling factor for all radii. Default is 1.
      replaceAllPaths - If true, all existing Paths will be deleted before the import. Default is false.
      Returns:
      true, if import was successful
    • importNeurons

      public Map<String,Tree> importNeurons(Map<String,TreeSet<SWCPoint>> map, org.scijava.util.ColorRGB color, String spatialUnit)
      Import neuron(s) as a collection of reconstruction nodes (SWC points)
      Parameters:
      map - the input map of reconstruction nodes
      color - the color to be applied to imported Paths. If null, paths from each ID will be assigned unique colors
      spatialUnit - the spatial unit (um, mm, etc) associated with imported nodes. If null, "um" are assumed
      Returns:
      the map mapping imported ids to imported Trees. A null Tree will be assigned if a morphology could not be imported
      See Also:
    • importSWC

      protected boolean importSWC(String filePath, boolean ignoreCalibration)
      Imports an SWC file.
      Parameters:
      filePath - the absolute path of the file to be imported
      ignoreCalibration - the ignore calibration
      Returns:
      true, if import was successful
    • importSWC

      public boolean importSWC(String filePath, boolean assumeCoordinatesInVoxels, double xOffset, double yOffset, double zOffset, double xScale, double yScale, double zScale, double rScale, boolean replaceAllPaths, int... swcTypes)
      Imports an SWC file using advanced options.
      Parameters:
      filePath - the absolute file path to the imported file
      assumeCoordinatesInVoxels - If true, the SWC coordinates are assumed to be in image coordinates ("pixels"). Note that in this case, radii will be scaled by the minimum voxel separation. This workaround seems to be required to properly import unscaled files
      xOffset - the offset to be applied to all X coordinates. May be useful to import data obtained from multiple "un-stitched" fields of view. Default is 0.
      yOffset - the offset to be applied to all Y coordinates. May be useful to import data obtained from multiple "un-stitched" fields of view. Default is 0.
      zOffset - the offset to be applied to all Z coordinates. May be useful to import data obtained from multiple "un-stitched" fields of view. Default is 0.
      xScale - the scaling factor for all X coordinates. Useful to import data onto downsampled images. Default is 1.
      yScale - the scaling factor for all Y coordinates. Useful to import data onto downsampled images. Default is 1.
      zScale - the scaling factor for all Z coordinates. Useful to import data onto downsampled images. Default is 1.
      rScale - the scaling factor for all radii. Default is 1.
      replaceAllPaths - If true, all existing Paths will be deleted before the import.
      Returns:
      true, if import was successful
    • guessTracesFileType

      protected int guessTracesFileType(String filename)
    • loadCompressedXML

      protected boolean loadCompressedXML(String filename)
    • loadUncompressedXML

      protected boolean loadUncompressedXML(String filename)
    • load

      public boolean load(String filePath, int... swcTypes)
      Imports a reconstruction file (any supported extension).
      Parameters:
      filePath - the absolute path to the file (.Traces, SWC or JSON) to be imported
      swcTypes - (Optional) The SWC type(s) (e.g., Path.SWC_AXON, Path.SWC_DENDRITE, etc.) to be considered in the import. Ignored if filePath encodes a .TRACES file.
      Returns:
      true, if successful
    • loadGuessingType

      public boolean loadGuessingType(String filePathOrURL) throws IOException, URISyntaxException
      Throws:
      IOException
      URISyntaxException
    • loadGuessingType

      public boolean loadGuessingType(String optionalDescription, InputStream is) throws IOException
      Throws:
      IOException
    • getPaths

      public List<Path> getPaths()
      Returns the "main" paths managed by this PathAndFillManager. This is a convenience method that excludes:
      • Null entries (defensive filtering)
      • Fitted paths (i.e., paths that are refined versions of other paths, created by path-fitting algorithms). These are typically displayed alongside their parent path rather than as standalone entries.
      The returned list is a snapshot safe for iteration even if paths are concurrently added or removed.
      Returns:
      a filtered list of paths, excluding nulls and fitted versions
      See Also:
    • getPathsFiltered

      public List<Path> getPathsFiltered()
      Returns the 'de facto' Paths (excluding null or fitted versions). The returned list is a snapshot safe for iteration even if paths are concurrently added or removed.
      Returns:
      the paths associated with this PathAndFillManager instance excluding those that are null or fitted version of other paths.
    • transformationStarted

      public void transformationStarted(org.jogamp.java3d.View view)
      Specified by:
      transformationStarted in interface ij3d.UniverseListener
    • transformationUpdated

      public void transformationUpdated(org.jogamp.java3d.View view)
      Specified by:
      transformationUpdated in interface ij3d.UniverseListener
    • transformationFinished

      public void transformationFinished(org.jogamp.java3d.View view)
      Specified by:
      transformationFinished in interface ij3d.UniverseListener
    • contentAdded

      @Deprecated public void contentAdded(ij3d.Content c)
      Deprecated.
      Specified by:
      contentAdded in interface ij3d.UniverseListener
    • contentRemoved

      @Deprecated public void contentRemoved(ij3d.Content c)
      Deprecated.
      Specified by:
      contentRemoved in interface ij3d.UniverseListener
    • contentChanged

      @Deprecated public void contentChanged(ij3d.Content c)
      Deprecated.
      Specified by:
      contentChanged in interface ij3d.UniverseListener
    • contentSelected

      @Deprecated public void contentSelected(ij3d.Content c)
      Deprecated.
      Specified by:
      contentSelected in interface ij3d.UniverseListener
    • canvasResized

      @Deprecated public void canvasResized()
      Deprecated.
      Specified by:
      canvasResized in interface ij3d.UniverseListener
    • universeClosed

      @Deprecated public void universeClosed()
      Deprecated.
      Specified by:
      universeClosed in interface ij3d.UniverseListener
    • nearestPointOnAnyPath

      public NearPoint nearestPointOnAnyPath(double x, double y, double z, double distanceLimit)
    • getUnSelectedPathsRenderedInViewPort

      protected List<Path> getUnSelectedPathsRenderedInViewPort(TracerCanvas canvas)
    • nearestPointOnAnyPath

      public NearPoint nearestPointOnAnyPath(Collection<Path> paths, PointInCanvas pic, double distanceLimit)
    • nearestPointOnAnyPath

      protected NearPoint nearestPointOnAnyPath(Collection<Path> paths, PointInImage pim, double distanceLimitSquared, boolean unScaledPositions)
    • allPointsIterator

      public Iterator<PointInImage> allPointsIterator()
    • getCorrespondences

      public List<NearPoint> getCorrespondences(PathAndFillManager other, double maxDistance)
      For each point in this PathAndFillManager, find the corresponding point on the other one. If there's no corresponding one, include a null instead. *
      Parameters:
      other - the other PathAndFillManager holding the corresponding Paths
      maxDistance - the distance limit below which the NearPoint is considered
      Returns:
      the cloud of NearPoint correspondences
    • getAllFills

      protected List<Fill> getAllFills()
    • exportFillsAsCSV

      public void exportFillsAsCSV(File outputFile) throws IOException
      Export fills as CSV.
      Parameters:
      outputFile - the output file
      Throws:
      IOException - Signals that an I/O exception has occurred.
    • exportToCSV

      public void exportToCSV(File outputFile) throws IOException
      Output some potentially useful information about all the Paths managed by this instance as a CSV (comma separated values) file.
      Parameters:
      outputFile - the output file
      Throws:
      IOException - if data could not be stored
    • update3DViewerContents

      protected void update3DViewerContents()
    • transformPaths

      public PathAndFillManager transformPaths(PathTransformer transformation, ij.ImagePlus templateImage, ij.ImagePlus modelImage)
    • downsampleAll

      public void downsampleAll(double maximumPermittedDistance)
      Downsamples alls path using Ramer–Douglas–Peucker simplification. Downsampling occurs only between branch points and terminal points.
      Parameters:
      maximumPermittedDistance - the maximum permitted distance between nodes.
    • getPlugin

      public SNT getPlugin()
      Gets the SNT instance.
      Returns:
      the SNT instance associated with this PathManager (if any)
    • pathChanged

      public void pathChanged(sc.fiji.snt.PathChangeEvent event)