| name | snt | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| description | Script SNT (the Fiji framework for neuroanatomy - tracing, reconstruction, and morphometry of neurons and vasculature). Use when a user wants to write Groovy/Python/BeanShell scripts against SNT, run SNT headlessly via SNTService, analyze SWC/TRACES files, batch-process reconstructions, or extend SNT. Prefer this skill over generic ImageJ/Fiji advice whenever neurons, neurites, traces, SWC, MouseLight, NeuroMorpho, or `sc.fiji.snt.*` are involved. | ||||||||||
| compatibility | Designed for any agentic AI assistant with file system, bash, and internet browsing skill. Requires a local Fiji installation with SNT (Neuroanatomy update site enabled). | ||||||||||
| metadata |
|
You are helping a researcher write or debug scripts against SNT (https://imagej.net/plugins/snt), the Fiji framework for neuronal/vascular reconstruction and morphometry. SNT is actively developed; your training data is almost certainly out of date. Follow the conventions in this file even when they contradict your priors, and prefer reading the installed jar / official docs over guessing.
- SNT requires Java 21 and a modern Fiji installation. Download Fiji-Latest (bundled with Java 21) from the Fiji downloads page
- If the user asks for something the official docs cover, link them. Don't paraphrase from memory:
- User guide: https://imagej.net/plugins/snt/
- pySNT notebooks: https://pysnt.readthedocs.io/en/latest/notebooks/index.html
- Latest version API: https://morphonets.github.io/SNT/
- Use the modern API. The package is
sc.fiji.snt.*. The legacytracing.*/SimpleNeuriteTracerclasses are deprecated: do not use them, do not invent method names from memory - Use
SNTServicefor headless / scripted entry. Do not instantiateSNTdirectly unless you have a specific reason.SNTServiceis a SciJava@Service: inject it, don't instantiate it - Prefer ImgLib2 over legacy IJ.
Img<T>,RandomAccessibleInterval,Dataset, are preferable overImagePlus,ImageStack,ImageProcessor. SNT Providessc.fiji.snt.util.ImpUtilsandsc.fiji.snt.util.ImgUtilsfor handling and converting image data structures - Look inside the jar before writing from scratch. SNT ships dozens of template scripts under
script_templates/Neuroanatomy/insideSNT-*.jar. Find a template that matches the task and adapt it. These are also part of the source code - No hard-coded paths. Resolve the Fiji install at runtime (see Phase 0)
- Prefer SciJava parameters. Scripts should declare
#@parameters at the top
For a one-shot script that loads a reconstruction and prints a statistic, you don't need Phase 0 - 2. Just write:
#@ SNTService snt
#@ File swcFile
import sc.fiji.snt.Tree
import sc.fiji.snt.analysis.TreeStatistics
Tree t = new Tree(swcFile.getAbsolutePath())
// getSummaryStats() returns an Apache Commons Math SummaryStatistics; its toString()
// already lists n / min / max / mean / sd, so println is enough.
println new TreeStatistics(t).getSummaryStats("branch length")Run with "$FIJI_HOME/fiji" --headless --run script.groovy 'swcFile="/path/to/cell.swc"'.
For anything else (batch processing, autotracing, custom analyzers, figure rendering), continue to Phase 0.
The path of a Fiji install subscribed to the Neuroanatomy update site is the only per-machine variable. Resolve it before doing anything else.
find_fiji_home() {
# Honor $FIJI_HOME or $FIJI_PATH if already set and valid
[ -n "$FIJI_HOME" ] && [ -d "$FIJI_HOME" ] && { echo "$FIJI_HOME"; return 0; }
[ -n "$FIJI_PATH" ] && [ -d "$FIJI_PATH" ] && { echo "$FIJI_PATH"; return 0; }
# On Windows-with-Cygwin/MSYS, convert USERPROFILE paths to POSIX
local WIN_DOWNLOADS="" WIN_DESKTOP=""
if [ -n "$USERPROFILE" ] && command -v cygpath >/dev/null 2>&1; then
WIN_DOWNLOADS=$(cygpath -u "$USERPROFILE/Downloads")
WIN_DESKTOP=$(cygpath -u "$USERPROFILE/Desktop")
fi
for p in \
"/Applications/Fiji.app" \
"$HOME/Fiji.app" \
"$HOME/Applications/Fiji.app" \
"/opt/Fiji.app" \
"$HOME/Downloads/Fiji.app" \
"$HOME/Desktop/Fiji.app" \
"${WIN_DOWNLOADS}/Fiji.app" \
"${WIN_DESKTOP}/Fiji.app" \
"/c/Program Files/Fiji.app" \
"/c/Fiji.app"; do
if [ -d "$p" ]; then
echo "$p"
return 0
fi
done
# Last resort: a `fiji` on PATH (snap, brew, custom)
if command -v fiji >/dev/null 2>&1; then
readlink -f "$(command -v fiji)"
return 0
fi
return 1
}
export FIJI_HOME="$(find_fiji_home)"If still ambiguous, ask the user once and cache it. Export it as FIJI_HOME for the rest of the session.
Verify SNT is installed:
ls "$FIJI_HOME"/jars/SNT-*.jar # SNT jar present
ls "$FIJI_HOME"/jars/scijava-common-*.jar # SciJava presentIf SNT-*.jar is missing: Instruct the user to enable the Neuroanatomy update site (Help > Update... > Manage update sites) and rerun Fiji's updater.
SNT scripts run on the Fiji Script Editor or headlessly via fiji --headless --run path/to/script. Supported languages:
| Lang | Extension | When to prefer |
|---|---|---|
| Groovy | .groovy |
Default. Best Java interop, concise. |
| Python (Jython 2.7) | .py |
If user explicitly wants Python inside Fiji. Note: Jython, not CPython — no numpy, no f-strings. |
| Python (3) | .py |
If user explicitly wants Python. The recommended approach is using PySNT, but It is also possible to run Fiji in Python mode. See Phase 3 |
| BeanShell | .bsh |
Legacy; only if extending an existing .bsh script. |
Always check the bundled templates first:
unzip -l "$FIJI_HOME"/jars/SNT-*.jar | grep script_templates/Neuroanatomy
# Extract one to read / adapt:
unzip -p "$FIJI_HOME"/jars/SNT-*.jar script_templates/Neuroanatomy/Analysis/Get_Branch_Points.groovyTemplates are grouped: Analysis/, Batch/, Big_Data/, Misc/, Render/, Skeletons_and_ROIs/, Time-lapses/, Tracing/.
Their headers also serve as canonical examples of #@ parameters and SNTService use.
Every SNT script should look roughly like this (Groovy shown; adapt syntax for Jython/BSH). Note the SciJava parameter prefix is #@: this is true for all scripting languages despite the host language's own comment syntax:
#@ Context context
#@ SNTService snt
#@ UIService ui
#@ File swcFile
import sc.fiji.snt.Tree
import sc.fiji.snt.analysis.TreeStatistics
import sc.fiji.snt.io.MouseLightLoader
// 1. Load reconstruction(s): from a `#@File` parameter (above), or a remote DB
tree = new Tree(swcFile.getAbsolutePath()) // local SWC/TRACES file
// For Remote DB files see sc.fiji.snt.io
// tree = new MouseLightLoader("AA0001").getTree("axon") // MouseLight DB
// 2. Analyze with TreeStatistics
stats = new TreeStatistics(tree)
println stats.getSummaryStats("branch length") // mean, sd, min, max, n
// 3. Render via Viewer2D (SVG, PDF) / Viewer3D (3D Scene)
tree.show()
// 4. Plots: Use SNTChart (not IJ1 plotters)
stats.getHistogram("branch length").show()Key rules embodied above:
- Injection over construction:
SNTService,UIService,Contextcome from SciJava@parameters Treeis the central type for a reconstruction. ATreeis a collection ofPaths. Don't pass raw SWC lists around- Analyzers are stateful wrappers around a
Tree:TreeStatistics,ShollAnalyzer,StrahlerAnalyzer,PersistenceAnalyzer,MultiTreeStatistics,GroupedTreeStatistics. Pick the most specific one SNTChartis the unified plotting surface: use it instead ofPlot/ charts. For tables useSNTTablenotResultsTable
- Local SWC / TRACES:
new Tree(path)orTree.listFromDir(dir) - MouseLight:
new MouseLightLoader(id).getTree(MouseLightLoader.AXON)(id in ctor; compartment string in getter, or use theAXON/DENDRITE/SOMAconstants) - NeuroMorpho.Org:
new NeuroMorphoLoader().getTree(cellId)(no-arg ctor; id is passed togetTree) - FlyCircuit:
new FlyCircuitLoader().getTree(cellId)(same pattern as NeuroMorpho) - Insect Brain DB:
new InsectBrainLoader(id).getTree()(int id in ctor; no-arg getter)
Loader APIs are NOT uniform — check the constructor vs. getTree(...) arity per loader. The four above are the verified shapes as of this skill's last_updated.
"$FIJI_HOME/fiji" --headless --run script.groovy 'inputDir="/data/swcs",outputCsv="/tmp/out.csv"'Declare matching #@File / #@String parameters at the top of the script.
Use MultiTreeStatistics over a list of Trees rather than looping TreeStatistics: It handles grouping, normalization, and produces a tidy SNTTable.
For cell groups use GroupedTreeStatistics
Use sc.fiji.snt.tracing.auto.BinaryTracer
Use the sc.fiji.snt.tracing.auto package. AutoTracer is the interface contract; the concrete implementations are:
GWDTTracer— default in-memory backendDiskBackedGWDTTracer— for stacks larger than RAMSparseGWDTTracer— for very sparse signalBinaryTracer— for already-binarised inputs (implements AutoTracer)
All GWDT*Tracer classes extend AbstractGWDTTracer<T extends RealType<T>>, so the configuration API (setSeed, setTips, setWaypoints, trace) is uniform.
SNT's SeedManager stores ROI- or label-derived starting points and lets users batch-trace from them. Programmatically, the matching SciJava commands (in sc.fiji.snt.plugin) are the easiest entry points:
AutotraceFromSeedsCmd: seeds from the active SeedManager / ROI selectionAutotraceFromBinarySeedsCmd: seeds harvested from a binary maskAutotraceFromTipsCmd/AutotraceFromWaypointsCmd: seed + endpoint hintsAutotraceFromBinaryTipsCmd: both seeds and tips derived from binary masks
For finer control instantiate an AbstractGWDTTracer subclass (GWDTTracer, DiskBackedGWDTTracer, SparseGWDTTracer) directly and call setSeed(...) / setSeedPhysical(...) / setTips(...) / setWaypoints(...) before trace().
For data-science workflows in standard Python 3 (CPython, with numpy / pandas / matplotlib), use the PySNT package: It proxies the full Java API through scyjava:
pip install pysntThen in Python (consult https://pysnt.readthedocs.io/ for the current import path — PySNT is evolving and earlier versions used a different module layout):
import pysnt # spins up a SciJava/Fiji gateway lazily
Tree = pysnt.snt.Tree # full Java FQN under pysnt.<package>
TreeStatistics = pysnt.snt.analysis.TreeStatistics
tree = Tree("/path/to/cell.swc")
stats = TreeStatistics(tree)
print(stats.getSummaryStats("branch length")) # SummaryStatistics.toString()Any method documented in the Javadoc is callable through PySNT. Use PySNT instead of Jython whenever the user needs numpy/pandas/matplotlib alongside SNT.
- Publication plots:
SNTChart - 2D:
Viewer2DorMultiViewer2Dfor Viewer2D montages - 3D:
Viewer3D: Supports brain meshes (Allen, InsectBrainDB, MouseLight, VirtualFlyBrain, mapZebrain), color-by-feature, animation.MultiViewer3Dcan be used forViewer3Dmontages.Image3DUniverseis considered deprecated. FigCreatorCmd.render(Collection<Tree>, String)is a one-call utility that returns the rendered viewer (Viewer2D/Viewer3D/MultiViewer2D/MultiViewer3D/ImagePlus). Example (Groovy):def viewer = FigCreatorCmd.render(trees, "montage,2d-raster,xy,zero-origin,upright-geodesic,show") // viewer.saveAsPNG(...) / viewer.saveSnapshot(...) etc. depending on the // concrete return type. See FigCreatorCmd Javadoc for the full flag list.
MultiTreeStatistics.getGroupStats(...), GroupedTreeStatistics.getGroupStats(...)
tree.getGraph() returns a DirectedWeightedGraph (JGraphT): Use this for any custom topology work instead of manually walking Path parents
SNT has dedicated, format-aware save methods on its result types. Don't hand-roll CSV writers or use ChartUtilities:
- Reconstructions:
tree.saveAsSWC(path)(SWC) /tree.save(path)(TRACES — XML, compressed) - Tables:
SNTTable.save(path)(writes CSV by extension; round-trips throughnew SNTTable(path)) - Plots:
SNTChart.saveAsPNG(path)/saveAsSVG(path)/saveAsPDF(path)(alsochart.save(path)for format-by-extension) - 3D scenes:
Viewer3D.saveSnapshot(path)for PNG snapshots of the current view - Generic figures via
FigCreatorCmd.render(trees, options)returns anImagePlus/Viewer2D/Viewer3D/MultiViewer2D/MultiViewer3D— capture it and call the appropriate save method on the returned object. There is nosave=flag in the option string.
| Don't | Do instead |
|---|---|
import tracing.SimpleNeuriteTracer |
import sc.fiji.snt.SNTService (inject it) |
new SNT(...) from a script |
@SNTService snt; snt.initialize(true) |
Iterate pixels via ImageProcessor |
Iterate via Cursor<T> on a RandomAccessibleInterval |
| Parse SWC manually | new Tree(path) |
Call IJ.run("3D Viewer", ...) |
new Viewer3D() |
ResultsTable for SNT outputs |
SNTTable (subclass with persistence helpers) |
| Mix length units silently | Always work in calibrated units; check tree.getProperties() |
ChartUtilities.saveChartAsPNG(...) |
chart.saveAsPNG(path) on SNTChart |
double[] xyz (or three loose doubles) |
PointInImage (world coords) / PointInCanvas (display coords) |
Walk Path.getStartJoins() parents manually |
tree.getGraph() then use JGraphT's iterators / BFS / DFS |
Share one SNT instance across threads |
Treat SNT as single-threaded; spawn one per worker, or use SNTService |
ImageProcessor → ad-hoc pixel arrays |
ImpUtils.toRAI(imp) / ImageJFunctions.wrap(imp) to get a RAI/Img |
Before handing a script back to the user:
- Sanity-run headlessly with synthetic input if the script doesn't need a GUI. Fiji's CLI has no real
--dry-run, so the next-best thing is to drive the script with one of SNT's built-in demos (SNTService.demoTree(),SNTService.demoTrees(),SNTService.demoImage(name)) instead of the user's real data, then inspect the log:"$FIJI_HOME/fiji" --headless --run script.groovy 'useDemo=true'
- Inspect the SNT log:
SNTUtils.log(...)output goes to Fiji's console but only after callingSNTUtils.setDebugMode(true) - Cite the API version in your reply:
println SNTUtils.VERSIONand include it so the user knows which API surface you targeted
- Read the jar.
unzip -l "$FIJI_HOME"/jars/SNT-*.jaris the ground truth for what classes/templates exist on this machine - Open the javadoc for the specific class:
https://morphonets.github.io/SNT/sc/fiji/snt/<ClassName>.html - Check the notebooks repo for curated working examples: https://github.com/morphonets/SNT/tree/main/notebooks
- Forum, not StackOverflow. Point users to https://forum.image.sc/tag/snt for help that needs a human
- GitHub Issues for bugs, not the forum: https://github.com/morphonets/SNT/issues
- Demos for quick sanity checks:
SNTService.demoTree(),SNTService.demoTrees(),SNTService.demoImage(name)return ready-to-use objects with zero external dependencies
| File / URL | When to Consult |
|---|---|
$FIJI_HOME/jars/SNT-*.jar :: script_templates/Neuroanatomy/ |
Always first: copy a template, adapt it |
| https://morphonets.github.io/SNT/ | Javadoc: authoritative method signatures |
| https://imagej.net/plugins/snt/scripting | Scripting overview & getting-started snippets |
| https://github.com/morphonets/SNT/tree/main/notebooks | Curate Jupyter/Python examples |
| https://forum.image.sc/tag/snt | Community Q&A |