pysnt.core module#

Core initialization and setup for PySNT.

This module handles the initialization of the Java environment and Fiji integration required for SNT functionality.

exception FijiNotFoundError[source]#

Bases: RuntimeError

Exception raised when Fiji installation cannot be found or configured.

initialize(fiji_path: str | None = None, interactive: bool = True, ensure_java: bool = True, mode: str = 'headless', max_heap: str | None = None, min_heap: str | None = None, jvm_args: List[str] | None = None) None[source]#

Initialize the SNT environment with ImageJ/Fiji.

Parameters:
  • fiji_path (str, optional) – Path to Fiji installation. If None, will try to auto-detect. Can also be a mode string for convenience (e.g., “gui”, “interactive”).

  • interactive (bool, default True) – Whether to prompt user for Fiji path if not found automatically. Set to False for non-interactive environments (CI, scripts, etc.).

  • ensure_java (bool, default True) – Whether to check and ensure Java is available. If True, will attempt to install OpenJDK if Java is not found or version is too old.

  • mode (str, default "headless") – pyimagej initialization mode. Either “headless”, “gui”, “interactive”, or “interactive:force”

  • max_heap (str, optional) – Maximum JVM heap size (e.g., “8g”, “4096m”, “2G”). Convenient alternative to manually configuring JVM args.

  • min_heap (str, optional) – Initial JVM heap size (e.g., “2g”, “1024m”, “1G”). Convenient alternative to manually configuring JVM args.

  • jvm_args (List[str], optional) – Additional JVM arguments to pass (e.g., [“-XX:+UseG1GC”, “-Xss2m”]). For advanced users who need full control over JVM configuration.

Examples

>>> # Standard usage
>>> pysnt.initialize("/path/to/Fiji.app", mode="gui")
>>>
>>> # Convenience syntax - just specify mode
>>> pysnt.initialize("gui")
>>> pysnt.initialize("interactive")
>>>
>>> # Memory configuration
>>> pysnt.initialize(max_heap="8g")  # 8GB heap
>>> pysnt.initialize(max_heap="16g", min_heap="4g")  # 16GB max, 4GB initial
>>>
>>> # Advanced JVM configuration
>>> pysnt.initialize(jvm_args=["-Xmx8g", "-XX:+UseG1GC"])
>>>
>>> # Full control
>>> pysnt.initialize(None, True, True, "gui", max_heap="8g")
Raises:
  • FijiNotFoundError – If Fiji installation cannot be found or configured.

  • RuntimeError – If initialization fails for other reasons (Java issues, etc.).

Notes

JVM memory configuration (max_heap, min_heap, jvm_args) must be specified on the first call to initialize(). Subsequent calls will ignore these parameters since the JVM cannot be reconfigured once started.

ij()[source]#

Get the ImageJ instance.

This provides access to the ImageJ instance used by PySNT. Consistent with PyImageJ’s naming convention.

Returns:

The initialized ImageJ instance.

Return type:

ImageJ instance

Raises:

RuntimeError – If SNT has not been initialized.

is_initialized() bool[source]#

Check if SNT has been initialized.

Returns:

True if initialized, False otherwise.

Return type:

bool

get_mode() str | None[source]#

Get the initialization mode used.

Returns the mode that was specified when initialize() was called. This indicates how the ImageJ/Fiji environment was started.

Returns:

The mode used during initialization: - “headless”: No GUI, for batch processing and scripts - “gui”: Full GUI mode with ImageJ windows - “interactive”: Interactive mode with some GUI elements - “interactive:force”: Force interactive mode - None: If SNT has not been initialized yet

Return type:

str or None

Examples

>>> import pysnt
>>> pysnt.initialize("headless")
>>> pysnt.get_mode()
'headless'
>>>
>>> # Check mode before performing GUI operations
>>> if pysnt.get_mode() in ["gui", "interactive"]:
...     pysnt.show(image)
... else:
...     print("GUI not available in headless mode")
dispose() None[source]#

Dispose of PySNT resources and shut down the JVM.

This function properly cleans up all resources created by initialize(), including the ImageJ instance and the Java Virtual Machine. After calling dispose(), you will need to call initialize() again to use PySNT functionality.

The cleanup process includes: 1. Disposing of the ImageJ instance (if available) 2. Shutting down the JVM via scyjava 3. Resetting internal state variables

Notes

  • After calling dispose(), the JVM cannot be restarted in the same Python session

  • This is a limitation of the JVM architecture - once shut down, it cannot be restarted

  • If you need to reinitialize PySNT, you must restart your Python session

  • This function is safe to call multiple times or when PySNT is not initialized

Examples

>>> import pysnt
>>> pysnt.initialize()
>>> # ... do work with PySNT ...
>>> pysnt.dispose()  # Clean shutdown
>>>
>>> # To use PySNT again, restart Python session and call initialize()

Warning

After calling dispose(), you cannot reinitialize PySNT in the same Python session. The JVM cannot be restarted once it has been shut down.

setup_dynamic_imports(module_globals: Dict[str, Any], package_name: str, known_classes: List[str] | None = None, include_abstract: bool = False, include_interfaces: bool = False) Dict[str, Any][source]#

Set up dynamic imports for a module using discovered Java classes.

This is a convenience function that discovers classes and sets up the module’s global namespace and __all__ list.

Parameters:
  • module_globals (Dict[str, Any]) – The module’s globals() dictionary

  • package_name (str) – Java package name to discover classes from

  • known_classes (List[str], optional) – Known class names to test

  • include_abstract (bool, default False) – Whether to include abstract classes

  • include_interfaces (bool, default False) – Whether to include interfaces

Returns:

Dictionary mapping class names to Java classes

Return type:

Dict[str, Any]

Examples

>>> # In a module's _java_setup function:
>>> java_classes = setup_dynamic_imports(
...     globals(),
...     'sc.fiji.snt.analysis',
...     ['TreeStatistics', 'ConvexHull']
... )
to_python(obj, **kwargs)[source]#

Convert supported Java data into Python equivalents.

This function extends scyjava’s to_python() to support SNT-specific objects like Tree, Path, and SNTChart.

Parameters:
  • obj (Any) – The Java object to convert to Python

  • **kwargs – Additional arguments passed to the converter

Returns:

The converted Python object

Return type:

Any

Examples

>>> import pysnt
>>> pysnt.initialize("headless")
>>> service = pysnt.SNTService()
>>> tree = service.demoTree('fractal')
>>> skeleton = tree.getSkeleton2D()
>>>
>>> # Convert Java objects to Python
>>> py_tree = pysnt.to_python(tree)
>>> py_skeleton = pysnt.to_python(skeleton)
from_java(obj, **kwargs)[source]#

Alias for to_python() for backward compatibility.

This provides backward compatibility for existing code that uses from_java(). New code should use to_python() for consistency with scyjava.

show(obj, **kwargs)[source]#

Enhanced show that handles SNT objects and converted data.

This function extends PyImageJ’s show() to support displaying SNT objects and data converted by our custom converters.

Parameters:
  • obj (Any) – The object to display (can be SNT objects, numpy arrays, etc.)

  • **kwargs – Additional display arguments (e.g., cmap=’gray’, title=’My Image’)

Examples

>>> import pysnt
>>> pysnt.initialize("interactive")  # or "gui"
>>> service = pysnt.SNTService()
>>> tree = service.demoTree('fractal')
>>> skeleton = tree.getSkeleton2D()
>>>
>>> # Convert and display
>>> py_skeleton = pysnt.to_python(skeleton)
>>> pysnt.show(py_skeleton, cmap='gray', title='Fractal Skeleton')
>>>
>>> # Or convert and display in one step
>>> pysnt.show(pysnt.to_python(tree))
extract_figure(display_result)[source]#

Extract matplotlib figure from display result.

This convenience function extracts the underlying data (typically a matplotlib figure) from an SNTObject dictionary returned by pysnt.display(). If the input is already a matplotlib figure or other object, it returns it unchanged.

Parameters:

display_result (Any) – Result from pysnt.display() - can be: - SNTObject dictionary (data will be extracted) - matplotlib.Figure (returned as-is) - Any other object (returned as-is)

Returns:

The extracted data (typically matplotlib.Figure) or the original object

Return type:

Any

Examples

>>> import pysnt
>>> pysnt.initialize()
>>>
>>> # Extract figure from display result
>>> result = pysnt.display(tree)
>>> fig = pysnt.extract_figure(result)  # matplotlib.Figure
>>>
>>> # Works with lists for multi-panel display
>>> fig1 = pysnt.extract_figure(pysnt.display(img))
>>> fig2 = pysnt.extract_figure(pysnt.display(tree))
>>> pysnt.display([fig1, fig2], panel_layout=(1,2))
>>>
>>> # Also works with objects that aren't SNTObject dicts
>>> fig = plt.figure()
>>> same_fig = pysnt.extract_figure(fig)  # Returns fig unchanged