Skip to content

Latest commit

 

History

History
198 lines (137 loc) · 12.5 KB

README.md

File metadata and controls

198 lines (137 loc) · 12.5 KB

SOFIMA Cluster Workflows

Wrapper scripts around SOFIMA and Julia (Zarr.jl / ImageTransformations.jl) to submit dependent LSF jobs on the Janelia cluster for 2D multi-tile stitching, full-stack 3D elastic Z-alignment, and pairwise slab-interface alignment.

Overview

The repository provides three main LSF entry points, splitting GPU-bound optical flow / spring-mesh relaxation (Python + JAX) from multi-threaded CPU masking, Lanczos-4 image warping, and coordinate reverse-mapping (Julia):

  1. 1-plane-stitch.sh — Stitches a 2D grid of microscope tiles within each Z-slice (1-plane-stitch.py), writing stitched.s0.zarr plus per-tile forward/inverse coordinate maps (stitched-{mesh,invmap,invmap-box}.s0.zarr).
  2. N-planes-align.sh — Aligns thousands of consecutive Z-planes into a 3D multiscale Zarr pyramid:
    • Resin/background masking in Julia (N-planes-mask.jl -> mask.<mask_params>.zarr)
    • Multi-scale, coarse-to-fine Padfield masked optical flow (N-planes-flow.py -> flow.<params>.zarr)
    • Distributed block-local mesh relaxation & inversion (N-planes-mesh.py -> mesh.<params>.zarr, N-planes-invmap.py -> invmap.<params>.zarr)
    • Cross-block coarse relaxation, fine reconciliation, & global inversion (N-planes-meshXcoarse.py, N-planes-meshXfine.py -> meshXfine.<params>.zarr, N-planes-invmap.py -> invmapX.<params>.zarr)
    • Multi-threaded OpenCV-faithful Lanczos-4 warping in Julia (N-planes-warp.jl -> warped.<params>.zarr)
    • Isotropic 2x2x2 downsampling (multiscale.py -> multiscale.<params>.zarr/s0..s4)
  3. 2-planes-align.sh (and 2-volumes-*) — Aligns two adjacent slices or slab faces (2-planes-flow-mesh.py -> 2-planes-invmap.py -> 2-planes-warp.jl -> multiscale.py).

Dataset-specific I/O and cluster resource flags live in data-* plugin files rather than the core pipeline scripts.


Installation

Nothing is cloned into this repository: sofima and connectomics are installed into the Conda environment.

1. This Repository

git clone https://github.com/JaneliaSciComp/SOFIMA-scripts.git
cd SOFIMA-scripts

Run every command below, and every launch script, from this directory.

2. Python / Conda Environment (multi-sem)

CONDA_OVERRIDE_CUDA=12.6 conda env create -f environment.yaml
  • The environment must be named multi-sem: the launch scripts call conda run -n multi-sem.
  • environment.yaml pins the CUDA build of JAX (jax / jaxlib 0.4.35, built for CUDA 12.6). CONDA_OVERRIDE_CUDA=12.6 lets Conda install it from a host without a GPU, such as a login node; on a GPU node it is not needed. With neither, the command stops with nothing provides __cuda rather than installing a CPU-only JAX.
  • pip then installs the patched sofima fork (branch useme5 of https://github.com/bjarthur/sofima) and connectomics.

3. Working on sofima (Optional)

To change sofima itself, clone the fork anywhere outside this repository and install that checkout in place of the copy from step 2:

git clone -b useme5 https://github.com/bjarthur/sofima.git ../sofima
conda run -n multi-sem pip install --no-deps -e ../sofima

Python then imports that checkout whatever the current directory, and the provenance (below) records its commit and refuses to launch while it has uncommitted changes.

4. Julia 1.12 Environment

Install Julia 1.12 with juliaup and install the package versions pinned in Manifest.toml:

juliaup add 1.12
julia +1.12 --project=. -e 'using Pkg; Pkg.instantiate()'

The launch scripts call julia +1.12 --project=., so their jobs use this version and this project whatever your juliaup default and JULIA_PROJECT are; julia (the juliaup launcher) must be on your PATH.


Data-Loader Plugins

Each dataset defines a small set of plugin files passed by stem name (e.g. data-aphid-N-planes or data-velella-N-planes):

  • 1-plane stitching (data-<name>-1-plane.py): Defines url, tile_space, crop, get_tilepath(Z), load_data(planepath, scale), save_plane(...), and optional save_mesh(...) (to persist per-tile meshes and inverse maps).
  • N-planes alignment (data-<name>-N-planes.{py,jl,sh}):
    • .py — Python Zarr/HDF5 readers and writers for mask, flow, mesh / meshXfine, meshXcoarse, invmap / invmapX, and warped.
    • .jl — Julia Zarr/DiskArrays loaders and creators (load_data, load_invmap, create_mask, open_mask, create_warp, open_warp).
    • .sh — LSF bsub_flags_* arrays (bsub_flags_flow, bsub_flags_mesh, bsub_flags_warp, etc.) tuned for that dataset's XY dimensions.
  • 2-planes alignment (data-<name>-2-planes.{py,jl,sh}): Analogous 2-slice readers/writers and LSF resource flags.

Usage

Run all LSF launch scripts from an LSF submit host (e.g. login1).

1. Stitching Multi-Tile 2D Planes (1-plane-stitch.sh)

./1-plane-stitch.sh <scale> <patch_size> <stride> <k0> <k> <margins> <min_z> <max_z> <outpath> <chunk_size> [overlaps] [coarse_offsets]

Example (aphid 2x3 MultiSEM tiles, s1 flow/mesh + s0 rendering):

./1-plane-stitch.sh 1 64 4 0.01 0.1 150,50,150,50 1280 19380 /nrs/cellmap/arthurb/aphid/final 1024
  • margins: top,bottom,left,right pixels cropped from each raw tile edge during s0 rendering.
  • overlaps (optional, default 100,200,400,800): comma-separated candidate tile overlaps (in s0 pixels) tested during coarse rigid stitching.
  • coarse_offsets (optional, default none): pins the coarse offset of named tile pairs after it is estimated, e.g. 'H,1,1=-109:0' or 'H,0,0=-76:-10;V,1,0=-1:-125'. H,x,y is the pair (x, y) -> (x+1, y), V,x,y the pair (x, y) -> (x, y+1), and the value is <x offset>:<y offset> in pixels at <scale>. The same pins apply to every slice of the job array, so use it to re-stitch single slices. Each job's log prints the offsets it used as cx = ... and cy = ....
    • Why it exists: where a tile pair overlaps mostly in resin, the estimate can differ from run to run (XLA picks the GPU convolution algorithm used for peak finding at run time), and the alternatives are whole-pixel offsets tens of pixels apart. To reproduce a plane exactly, or to correct one where the wrong candidate won, pin the offset. Everything after the coarse offsets is deterministic.
  • Re-running individual outlier slices into an existing <outpath> automatically detects stitched.s0.zarr/.zarray and sets write_metadata=0.

2. Aligning a 3D Stack of Planes (N-planes-align.sh)

If Step 1 was run into a separate directory, symlink stitched*.zarr into <basepath>, then launch:

./N-planes-align.sh <data_loader> <basepath> <min_z> <max_z> \
    <scale> <high_pass> <uniform> <threshold> <close> \
    <patch_sizes> <strides> <scales> <k0> <k> <batch_size> \
    <chunkxy> <chunkz> <nslices>

Example:

./N-planes-align.sh "data-aphid-N-planes" /nrs/cellmap/arthurb/aphid/final4 1280 19380 \
    2 3 10 2 15 \
    256,128,64 64,32,16 1,2 0.01 0.1 256 \
    128 64 64
  • scale, high_pass, uniform, threshold, close: downsampled scale and filter/morphology parameters for resin masking in N-planes-mask.jl (for datasets without resin masking, load_mask in the .py plugin can return None).
  • patch_sizes, strides, scales: comma-separated coarse-to-fine patch sizes and strides (in pixels at each scale) and image mipmap scales (1,2 = 2x and 4x downsampled).
  • nslices: Z-block size per job; must be an integer multiple of chunkz.

3. Aligning Two Planes or Slab Faces (2-planes-align.sh)

./2-planes-align.sh <data_loader> <basepath> <top> <bot> <patch_sizes> <strides> <scales> <k0> <k> <batch_size> <chunk>

Example:

./2-planes-align.sh data-velella-2-planes /nrs/cellmap/arthurb/velella/alpha5 7995 7996 256,128,64 64,32,16 0,1,2 0.01 0.1 1024 1024

Provenance & Clean-Git Guard

  • Clean working tree check: All .sh launchers run ./provenance.py check-clean <data_loader> before submitting jobs, verifying that this repository has no uncommitted modifications, that the data-loader plugin files are tracked in git, and that the commit of the sofima Python will import is known: either the one pip recorded when installing it from a git URL, or, for a pip install -e checkout, its HEAD, in which case that checkout must have no uncommitted modifications either. The check runs inside the multi-sem environment, so it sees the same sofima as the jobs. Set ALLOW_DIRTY_GIT=1 only for throwaway tests.
  • Zarr .zattrs lineage: Every Zarr stage (stitched*.zarr, mask.*.zarr, flow.*.zarr, mesh.*.zarr, meshXfine.*.zarr, invmap*.zarr, warped.*.zarr, and multiscale.*.zarr) records an atomic .zattrs["provenance"] entry containing CLI arguments, parsed parameters, git remotes/branches/commits, Python/Julia package versions, and the upstream Zarr provenance chain.
  • Copying patched Z-planes (copy-z-plane.jl): When re-stitching or patching specific 0-based Z-slices from an override Zarr into a destination Zarr, use copy-z-plane.jl so 0-based-to-1-based indexing and .zattrs["provenance"] propagation are handled automatically:
julia +1.12 --project=. ./copy-z-plane.jl /path/to/override/stitched.s0.zarr /path/to/final/stitched.s0.zarr 15991 16005 16068

Comparing Two Zarr Arrays (verify-zarr.jl)

verify-zarr.jl checks whether a regenerated Zarr array is identical to a reference. It handles 3D uint8 arrays stored with /-separated chunk directories (stitched.s0.zarr, warped.*.zarr, multiscale.*.zarr/s<N>). It compares the .zarray metadata, then the compressed chunk files byte for byte, and decompresses and compares voxels only for chunks whose files differ. It prints VERIFICATION RESULT: PASS (metadata equal, same set of chunk files, no voxel differences) or FAIL, and exits with status 0 or 1.

# reference first, candidate second; both are array directories (e.g. .../multiscale.<params>.zarr/s0)
julia +1.12 --project=. -t auto ./verify-zarr.jl <ref.zarr> <candidate.zarr> \
    [--z-chunks 122,146,161] [--z-range 5598,19379] [--decompress-all]
  • --z-chunks: only compare these top-level chunk directories (for a [1, Y, X]-chunked stitched.s0.zarr these are slice numbers).
  • --z-range: 0-based inclusive slice range to which the voxel comparison of differing chunks is limited.
  • --decompress-all: also decompress and compare chunks whose compressed files are already identical.

Reverse-Mapping 3D Coordinates to Raw Tiles (reverse-map.jl)

reverse-map.jl maps 0-based (x, y, z) Neuroglancer coordinates from any multiscale pyramid level (--level 0..4) back through Step 2 (invmapX.<params>.zarr or invmap.<params>.zarr) and—for multi-tile datasets—Step 1 (stitched-invmap.s0.zarr + stitched-invmap-box.s0.zarr, respecting painter's order and tile margins) to 0-based (tile_id, x_raw, y_raw) coordinates in the raw unstitched HDF5 tile:

# Multi-tile stack (with Step 1 XY stitching):
julia +1.12 --project=. ./reverse-map.jl \
    --align-basepath /nrs/cellmap/arthurb/aphid/final3 \
    --stitch-basepath /nrs/cellmap/arthurb/aphid/final \
    --params patch256,128,64.stride64,32,16.scales12.k00.01.k0.1 \
    --level 0 \
    10000,4000,10330

# Single-tile stack (no Step 1 stitch, e.g. velella):
julia +1.12 --project=. ./reverse-map.jl \
    --align-basepath /nrs/cellmap/arthurb/velella/alpha4 \
    --params patch256,128,64.stride64,32,16.scales12.k00.01.k0.1 \
    5000,4000,5000

The script prints one JSON record per point, in the order given. A point outside the region covered by the Step 2 inverse map gets null for its plane coordinates (stitched_s0_xy, or pre_align_s0_xy for single-tile stacks) and for raw_tile; a point that lands in the stitched plane but on no tile gets "raw_tile": null. The other points are still mapped.

Minimal Files Required to Invert Transforms

Once alignment and multiscale.*.zarr generation are complete, only the *invmap* Zarr directories need to be retained to reverse-map coordinates back to raw tiles:

  1. Step 2 (<align-basepath>): invmapX.<params>.zarr (or invmap.<params>.zarr for non-distributed runs)
  2. Step 1 (<stitch-basepath>, multi-tile datasets only): stitched-invmap.s0.zarr and stitched-invmap-box.s0.zarr

Intermediate arrays (stitched.s0.zarr, stitched-mesh.s0.zarr, mask.*.zarr, flow.*.zarr, mesh*.zarr, meshXcoarse*.npy) are not needed for coordinate inversion.