diff --git a/applications/pipeline/Dockerfile b/applications/pipeline/Dockerfile new file mode 100644 index 00000000..e9f104d0 --- /dev/null +++ b/applications/pipeline/Dockerfile @@ -0,0 +1,23 @@ +# VFB precomputed pipeline: precomputed.zip per image folder (see README.md, vfb_pipeline.py). +# Built for the VFB cluster, whose VMs expose a qemu64 CPU without SSE4.2/POPCNT: no x86-64-v2 wheels +# (numpy < 2.4, scipy < 1.15) and nothing compiled with -march. +FROM python:3.12-slim-bookworm + +RUN apt-get update && apt-get install -y --no-install-recommends build-essential ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +# Pin the two packages whose newer wheels assume x86-64-v2 first, so the rest resolve against them. +RUN pip install --no-cache-dir "numpy<2.4" "scipy<1.15" + +WORKDIR /app +COPY requirements.txt /app/requirements.txt +# igneous/zmesh/DracoPy (multires_draco) and navis are optional for the production path (legacy meshes; +# volume_man.obj or tube meshes from SWC) and are left out of the cluster image. +RUN grep -vE '^(igneous|zmesh|DracoPy|navis)' requirements.txt > /tmp/req.txt \ + && pip install --no-cache-dir -r /tmp/req.txt +COPY . /app +RUN python -c "import numpy, scipy, skimage, trimesh, nrrd, cloudvolume, vfb_pipeline; print('numpy', numpy.__version__)" +# cloud-volume writes ~/.cloudfiles and ~/.cloudvolume; uid 1000 has no home in the image. +ENV PYTHONUNBUFFERED=1 HOME=/tmp +USER 1000:1000 +ENTRYPOINT ["python", "/app/vfb_pipeline.py"] diff --git a/applications/pipeline/README.md b/applications/pipeline/README.md index 9c1234c9..13ed4269 100644 --- a/applications/pipeline/README.md +++ b/applications/pipeline/README.md @@ -2,24 +2,69 @@ ## Overview -This repository contains scripts and documentation for converting Virtual Fly Brain (VFB) image files into [Neuroglancer precomputed format](https://github.com/google/neuroglancer/tree/master/src/datasource/precomputed) for use in Neuroglancer/Neuroglass viewers. +This folder converts Virtual Fly Brain (VFB) image files into [Neuroglancer precomputed format](https://github.com/google/neuroglancer/tree/master/src/datasource/precomputed) for the Neuroglancer/Neuroglass viewer. VFB image data lives at `https://www.virtualflybrain.org/data/VFB/i/{first4}/{last4}/{template_id}/` and contains several file types per image: | File | Format | Description | |------|--------|-------------| -| `volume.nrrd` | NRRD | 3D volumetric voxel data | -| `volume_man.obj` | OBJ mesh | Manually curated or generated mesh (vertices + faces) | +| `volume.nrrd` | NRRD | 3D volumetric voxel data (uint8, X Y Z, microns) | +| `volume_man.obj` | OBJ mesh | Manually curated or generated mesh (vertices + faces, X Y Z, microns) | | `volume.obj` | OBJ point cloud | Auto-generated point cloud (vertices only, no faces) | -| `volume.swc` | SWC | Neuron skeleton/morphology tracing | +| `volume.swc` | SWC | Neuron skeleton/morphology tracing (microns) | | `volume.wlz` | Woolz | Format for the IIP3D slice viewer | +## The production pipeline: `vfb_pipeline.py` + +`vfb_pipeline.py` is what runs against the image store. For each image folder it writes **one file**, `precomputed.zip`, next to the source files: a precomputed dataset (`info`, `0/` chunks, `mesh/`) zipped as a single archive that Neuroglancer reads through its zip kvstore with HTTP Range requests: + +``` +https://www.virtualflybrain.org/data/VFB/i/0010/1567/VFB_00101567/precomputed.zip|zip:|neuroglancer-precomputed: +``` + +What is written depends on what the image **is** (its VFB category, from the KB), because every VFB NRRD is uint8 and the dtype cannot tell a template from a neuron: + +| category | KB rule | layer | chunks (`0/`) | mesh | +|---|---|---|---|---| +| template | `:Template` individual | `image` | intensities | none | +| expression | typed by a `VFBexp_*` (GAL4 / split pattern) or `VFBext_*` (fragment) class | `image` | intensities | none | +| object | everything else: `FBbt_*`-typed neurons, clones, painted domains | `segmentation` | `{0,1}`, segment 1 | `volume_man.obj` if it has faces, else generated from `volume.swc`, else marching cubes on the NRRD | + +Without a KB category (filesystem scan, `--ids`) the same decision is made from the data: a `volume_man.obj` with faces or a `volume.swc` means an object; a single-valued mask is an object; intensities are an image. + +Axes and units: everything stays X, Y, Z as pynrrd returns it — no transposes, no swaps (OBJ and SWC vertices were checked against the NRRD voxel extents of templates, domains, FlyWire/hemibrain neurons and LM neurons). Source files are in microns; `resolution`, `voxel_offset` (voxel units) and mesh vertices are written in **nanometres**, the unit the precomputed spec defines, so VFB datasets compose with other precomputed sources. + +The zip also carries `provenance.json` (pipeline version, category, mesh source, size+mtime of the source files). A re-run skips a folder whose zip was made by the current `PIPELINE_VERSION` from unchanged sources, so the job is idempotent and resumable; bump `PIPELINE_VERSION` to regenerate everything. + +Each dataset is built in `--work-dir` (local scratch; a template-sized volume is ~120 MB of raw chunks) and only the finished zip is copied into the image folder, as `precomputed.zip.tmp-` then renamed — a reader never sees a partial file. + +```bash +# What would be done for everything on JRC2018U, live images only (KB) +python vfb_pipeline.py --image-root /data --use-kb --template VFB_00101567 --dry-run + +# A few folders, building on local scratch +python vfb_pipeline.py --image-root /data --ids VFB_00101567 VFB_00102107 VFB_jrchk0ew --template VFB_00101567 --work-dir /scratch + +# A batch file (one id per line), e.g. one Argo task +python vfb_pipeline.py --image-root /data --ids-file batch.txt --template VFB_00101567 --work-dir /scratch +``` + +For a planned run (one plan pod, many workers): `--use-kb --list-targets targets.tsv` writes the discovered targets with their category (40 s for the 680k JRC2018U images); split that into batches and give each worker `--targets-file batch.tsv --results results.jsonl` — no KB access in the workers, one JSON line per image for the report. + +`--template` is required (except with `--targets-file`): space is limited, so only the alignments you name get a `precomputed.zip`. Hemibrain (`VFB_00101384`) alignments are never converted. + +`--layer-type image|segmentation` overrides the per-image decision; `--mask/--mesh-percentile/--decimate-fraction/--mesh-format` only affect the marching-cubes path (objects with no mesh); `--no-compress` leaves an uncompressed `precomputed/` folder for debugging. Discovery needs only HTTP access to `kb.virtualflybrain.org` (read-only, published credentials). + +Measured on JRC2018U samples (one core): template 29 MB in 5 s; neurons and painted domains 0.3–0.9 MB in ~2 s; a dense GAL4 line 16 MB in 5 s; an MCFO fragment 6 MB in 3.5 s. + ## VFB Image Categories & Conversion Strategies There are four distinct categories of VFB images, each requiring a different conversion approach: --- +(The standalone scripts below predate `vfb_pipeline.py` and are kept for experiments; the production pipeline does not call `convert_templates.py` or `convert_all.py`.) + ### Category A: Templates with Painted Domains (Index Regions) **What they are:** Reference brain templates (e.g., JRC2018Unisex `VFB_00101567`) that contain a segmentation label field — an integer-indexed NRRD volume where each voxel value maps to a specific anatomical region (neuropil). @@ -171,21 +216,19 @@ For each VFB image: ## Output: Neuroglancer Precomputed Format -All conversion paths produce the same output structure: +`vfb_pipeline.py` writes `precomputed.zip` (see above) whose entries are: ``` -output/{vfb_id}/ - ├── info # JSON metadata (type, data_type, scales, resolution) - ├── mesh/ - │ ├── info # Mesh metadata (@type: neuroglancer_legacy_mesh) - │ ├── {seg_id} # Binary mesh data per segment - │ └── {seg_id}:0 # Fragment manifest - ├── segment_properties/ - │ └── info # Segment labels and descriptions - └── 0/ # Scale level 0 volume chunks (for segmentation types) - └── 0-64_0-64_0-64 # Chunk files +info # JSON metadata (type image|segmentation, uint8, one scale, resolution in nm) +provenance.json # pipeline version, category, mesh source, source-file stamps +0/ # scale-0 chunks, 64^3, raw (absent for a mesh-only object with no NRRD) +mesh/info # {"@type": "neuroglancer_legacy_mesh"} (segmentation only) +mesh/1:0 # fragment manifest for segment 1 +mesh/1:0:1 # the mesh ``` +No `segment_properties/`: a VFB image is one object, so there is nothing to label. + ## Requirements ```bash diff --git a/applications/pipeline/convert_all.py b/applications/pipeline/convert_all.py index 1b21cba0..0165ff0c 100644 --- a/applications/pipeline/convert_all.py +++ b/applications/pipeline/convert_all.py @@ -152,7 +152,7 @@ def process_image(vfb_id: str, template_id: str, category: str, download_file(url, tmp_path) convert_nrrd( tmp_path, output_dir, vfb_id, - merge_segments=True, verbose=verbose, + layer_type="auto", verbose=verbose, ) finally: os.unlink(tmp_path) diff --git a/applications/pipeline/convert_nrrd.py b/applications/pipeline/convert_nrrd.py index c774bd87..86545ec3 100644 --- a/applications/pipeline/convert_nrrd.py +++ b/applications/pipeline/convert_nrrd.py @@ -5,17 +5,20 @@ This script: 1. Reads the NRRD file - 2. Converts to precomputed format (segmentation or image layer) - 3. For segmentation data, generates a single mesh from the outer boundary - of all non-zero voxels via marching cubes - -Volume conversion approach matches MetaCell/virtual-fly-brain converter.py: - - Detects voxel spacing and origin from NRRD header - - Writes data as-is (no thresholding/relabeling for integer data) - - Writes chunks/mesh fragments uncompressed -- the whole neuroglancer/ output folder is - zipped as a single artifact afterward (see mesh_compression/zip_output.py) instead of per-chunk gzip/ - brotli, so Neuroglancer's client-side zip-kvstore adapter can decompress it without any - server-side Content-Encoding hacks. + 2. Converts to precomputed format as an image layer (intensities kept: templates, + expression patterns) or a segmentation layer (every non-zero voxel -> segment 1: + neurons, clones, painted domains) -- the caller says which via layer_type, since + every VFB NRRD is uint8 and the dtype cannot tell them apart + 3. For a segmentation, writes one mesh for segment 1: an existing volume_man.obj + when supplied, else marching cubes on the outer boundary of the non-zero voxels + + - Axes: data and header are used in pynrrd's X, Y, Z order; nothing is transposed + - voxel_offset is written in voxel units, resolution and mesh vertices in nanometres, + as the precomputed spec requires (sources are in microns) + - Writes chunks/mesh fragments uncompressed -- the whole output folder is zipped as + one artifact afterward (see mesh_compression/zip_output.py) instead of per-chunk + gzip/brotli, so Neuroglancer's client-side zip-kvstore adapter can decompress it + without any server-side Content-Encoding hacks. Mesh-size reduction (mask cleanup, decimation, Draco) is implemented in mesh_compression/ and wired in here -- see mesh_compression/README.md @@ -70,31 +73,51 @@ def download_file(url: str, dest: str) -> str: def detect_spacing(header: dict) -> list[float]: + """Voxel size [x, y, z] in the header's own units (microns for VFB data). + + pynrrd's default index_order="F" returns the data array AND the header's + "space directions"/"spacings"/"space origin" in the file's own axis order, + which for VFB NRRDs is X, Y, Z (sizes: 1210 566 174 for JRC2018U). Nothing + is reversed here -- the earlier [::-1] produced Z,Y,X output (size + [174, 566, 1210], resolution [1.0, 0.519, 0.519]) that only lined up with + the OBJ meshes because write_precomputed() swapped those to match. + """ if "space directions" in header and header["space directions"] is not None: try: dirs = header["space directions"] - return [float(np.linalg.norm(d)) if d is not None else 1.0 for d in dirs][::-1] + return [float(np.linalg.norm(d)) if d is not None else 1.0 for d in dirs] except Exception: pass if "spacings" in header: try: - return list(map(float, header["spacings"]))[::-1] + return list(map(float, header["spacings"])) except Exception: pass return [1.0, 1.0, 1.0] def detect_origin(header: dict) -> list[float]: - """Extract space origin from NRRD header and convert to XYZ order.""" + """Space origin [x, y, z] in the header's own units (microns), same axis + order as detect_spacing().""" if "space origin" in header and header["space origin"] is not None: try: - origin = header["space origin"] - return [float(x) for x in origin[::-1]] + return [float(x) for x in header["space origin"]] except Exception: pass return [0.0, 0.0, 0.0] +# Precomputed `resolution` and legacy-mesh vertex positions are in NANOMETRES (the +# spec's unit); VFB NRRD headers, OBJ and SWC files are in microns. +NM_PER_UM = 1000.0 + + +def origin_to_voxel_offset(origin_um: list[float], voxel_size: list[float]) -> list[int]: + """The precomputed `voxel_offset` is in integer VOXEL units at that scale + (physical origin = voxel_offset * resolution), not microns.""" + return [int(round(o / v)) if v else 0 for o, v in zip(origin_um, voxel_size)] + + def read_nrrd_voxel_size(nrrd_path: str) -> list[float]: """Read just the voxel spacing from an NRRD file's header (no data array read) -- native header units, no conversion, same convention as convert_nrrd()'s own @@ -169,12 +192,9 @@ def convert_nrrd( nrrd_path: str, output_dir: str, dataset_name: str, - threshold: float | None = None, + layer_type: str = "auto", dust_threshold: int = 100, - merge_segments: bool = False, - min_intensity: int | None = None, - max_intensity: int | None = None, - generate_mesh: bool = False, + generate_mesh: bool = True, mask: str = "none", mesh_min_intensity: int | None = None, mesh_max_intensity: int | None = None, @@ -183,98 +203,80 @@ def convert_nrrd( decimate_fraction: float = 0.0, max_simplification_error: int = 10, mesh_obj_path: str | None = None, - mesh_obj_swap_xz: bool = False, verbose: bool = True -): - """Convert an NRRD volume to precomputed format with external-boundary mesh. - - The volume is written as-is (matching converter.py behaviour) -- min_intensity/ - max_intensity zero voxels in the STORED volume (destructive, unrelated to meshing). - A single mesh is generated from the outer boundary of non-zero voxels, rather than - one mesh per segmented region. - - mesh_obj_path: if given (and generate_mesh is True), the mesh is loaded from this - OBJ file instead of running marching cubes on the NRRD volume -- mask/mesh_format/ - decimate_fraction/max_simplification_error are ignored in that case (see - _generate_mesh_from_obj). Volume chunks (0/) are still written from the NRRD either - way; only the mesh source changes. See vfb_pipeline.py's --mesh-from-obj. - - mesh_obj_swap_xz: pass True when mesh_obj_path is a pre-existing external obj built - upstream directly off the raw NRRD array (Z,Y,X order) rather than one generated - from a .swc file this run -- see vfb_pipeline.write_precomputed()'s swap_xz for the - full explanation and how it's determined per-image. - - Everything below mesh-size reduction is OPTIONAL and each choice is independent -- - see mesh_compression/README.md for the full validation. Three separate decisions, - each on its own axis (pick at most one thing per axis; axes combine freely): - - 1. generate_mesh: False (default) | True. Whether to generate a mesh from the - volume's external boundary at all -- off by default since most instances - already ship a usable volume_man.obj (see vfb_pipeline.py) and don't need one - regenerated from the NRRD. When True, mesh_obj_path picks the source: an - existing volume_man.obj (used as-is) or marching cubes on the NRRD (default). - 2. mask: "none" (default -- no mask cleanup at all) | "otsu" (automatic threshold, - no extra params) | "minmax" (explicit band -- supply mesh_percentile for a - per-sample floor, OR mesh_min_intensity/mesh_max_intensity for a fixed band; - not both). Pick ONE of otsu/minmax, or leave at "none". Applied exactly as - requested -- masking is known to backfire on dense data (e.g. whole-brain - templates, confirmed: +23% bigger), so choosing otsu/minmax there is a real - risk you're opting into, not something this function protects you from. - 3. mesh_format: "legacy" (default) | "multires_draco". Pick ONE. Under "legacy", - decimate_fraction (default 0.0 = off) optionally simplifies the mesh afterward - (pyfqmr, safe on both sparse and dense data). Under "multires_draco", - max_simplification_error (default 10) controls Draco's own simplification - instead -- decimate_fraction is ignored in that case. Can't combine decimation - with Draco (they're different mesh formats), but masking (axis 2) combines - freely with either. +) -> str: + """Convert an NRRD volume to precomputed format at {output_dir}/{dataset_name}/. + + layer_type decides what the volume IS, which the voxel dtype cannot (every VFB + NRRD is uint8): + "image" -- intensity data (a template brain, a GAL4 expression pattern, + a split-GAL4 line, an MCFO fragment). Values are stored as-is + as a Neuroglancer image layer. No mesh. + "segmentation" -- one object (a neuron, a clone, a painted neuropil domain). + Every non-zero voxel becomes segment 1 and, with + generate_mesh, one mesh for segment 1 is written: from + mesh_obj_path (an existing volume_man.obj, used as-is) when + given, otherwise marching cubes on the mesh mask. + "auto" -- "segmentation" when the volume holds a single non-zero value + (a mask) or a volume_man.obj mesh was supplied, else "image". + Callers that know the VFB category (vfb_pipeline.py, from the + KB) should pass it explicitly rather than rely on this. + + Axes: pynrrd (index_order="F") already returns the array as X, Y, Z, which is what + CloudVolume expects, so the data is written without any transpose and the header's + spacing/origin are used in their own order (see detect_spacing). voxel_offset is + written in voxel units (see origin_to_voxel_offset); resolution and mesh vertices + in nanometres (NM_PER_UM), as the precomputed spec requires. + + Mesh-size options (mask / mesh_format / decimate_fraction / max_simplification_error) + apply only to the marching-cubes path -- see mesh_compression/README.md. They are + ignored when mesh_obj_path supplies the mesh. """ validate_mesh_params(mask, mesh_min_intensity, mesh_max_intensity, mesh_percentile, mesh_format, decimate_fraction, generate_mesh, verbose) + if layer_type not in ("auto", "image", "segmentation"): + raise ValueError(f"layer_type must be 'auto', 'image' or 'segmentation', got {layer_type!r}") if verbose: print(f"Reading NRRD: {nrrd_path}") - data, header = nrrd.read(nrrd_path) + data, header = nrrd.read(nrrd_path) # X, Y, Z (pynrrd index_order="F") if data.ndim != 3: raise RuntimeError(f"Expected 3D volume, got ndim={data.ndim}") + arr = np.ascontiguousarray(data) + voxel_size_um = detect_spacing(header) + voxel_offset = origin_to_voxel_offset(detect_origin(header), voxel_size_um) + voxel_size = [v * NM_PER_UM for v in voxel_size_um] # nm, as the spec requires + + nonzero = np.unique(arr[arr > 0]) + if layer_type == "auto": + layer_type = "segmentation" if (len(nonzero) <= 1 or mesh_obj_path) else "image" + if verbose: + print(f" layer_type=auto -> {layer_type} ({len(nonzero)} distinct non-zero values" + f"{', mesh supplied' if mesh_obj_path else ''})") - # Transpose from ZYX (NRRD) to XYZ (Neuroglancer) - arr = np.transpose(data, (2, 1, 0)).copy() - voxel_size = detect_spacing(header) - voxel_offset = detect_origin(header) + if layer_type == "segmentation": + # One object per VFB image: collapse whatever values are present to segment 1. + # Chunks are stored as uint8 {0, 1}; the mesh is written for segid 1. + seg = (arr > 0).astype(np.uint8) + if verbose: + print(f" Segmentation: {int(seg.sum())} voxels -> segment 1") + intensity_for_mask = arr # the mesh mask may still use the original intensities + arr = seg if verbose: print(f" Shape (XYZ): {arr.shape}") - print(f" Voxel size: {voxel_size}") - print(f" Voxel offset: {voxel_offset}") + print(f" Voxel size: {voxel_size} nm") + print(f" Voxel offset: {voxel_offset} (voxels)") print(f" Dtype: {arr.dtype}") - print(f" Value range: [{arr.min()}, {arr.max()}]") - - # Apply intensity filtering if specified (for segmentation data) - if np.issubdtype(arr.dtype, np.integer): - if min_intensity is not None or max_intensity is not None: - original_segments = len(np.unique(arr[arr > 0])) - if min_intensity is not None: - arr[arr < min_intensity] = 0 - if max_intensity is not None: - arr[arr > max_intensity] = 0 - filtered_segments = len(np.unique(arr[arr > 0])) - if verbose: - print(f" Intensity filter: {original_segments} segments -> {filtered_segments} segments") - print(f" Range: [{min_intensity or 'any'}, {max_intensity or 'any'}]") - - # Determine layer type - is_segmentation = np.issubdtype(arr.dtype, np.integer) - layer_type = "segmentation" if is_segmentation else "image" - dtype_str = str(np.dtype(arr.dtype).name) + print(f" Layer type: {layer_type}") dest_local = os.path.join(output_dir, dataset_name) os.makedirs(dest_local, exist_ok=True) dest = f"file://{dest_local}" - # Write precomputed volume info = { - "data_type": dtype_str, + "data_type": str(np.dtype(arr.dtype).name), "num_channels": 1, "scales": [{ "chunk_sizes": [[64, 64, 64]], @@ -286,15 +288,9 @@ def convert_nrrd( }], "type": layer_type, } - - if is_segmentation and generate_mesh: + if layer_type == "segmentation" and generate_mesh: # Only declare a mesh directory when we're actually going to write one -- - # otherwise Neuroglancer requests neuroglancer/mesh/info and gets a 404 - # (see _generate_external_mesh/_generate_draco_mesh for what populates it). - # segment_properties is NOT declared: our mesh is always a single merged - # blob with a placeholder label ("Segment N"), never real per-segment - # labels, so a segment_properties list would be misleading rather than - # informative (see NEUROGLANCER_STANDARDIZATION.md item 3). + # otherwise Neuroglancer requests mesh/info and gets a 404. info["mesh"] = "mesh" vol = CloudVolume(dest, mip=0, info=info, compress=False) @@ -303,38 +299,18 @@ def convert_nrrd( if verbose: print(f" Wrote precomputed volume to {dest_local}") - print(f" Layer type: {layer_type}") - # Generate mesh from the external boundary of all non-zero voxels, or from an - # existing volume_man.obj if mesh_obj_path was given - if is_segmentation: - if generate_mesh and mesh_obj_path: - if verbose: - touched = [] - if mask != "none": - touched.append(f"--mask {mask}") - if mesh_format != "legacy": - touched.append(f"--mesh-format {mesh_format}") - if decimate_fraction > 0: - touched.append("--decimate-fraction") - if mesh_min_intensity is not None or mesh_max_intensity is not None or mesh_percentile is not None: - touched.append("--mesh-min-intensity/--mesh-max-intensity/--mesh-percentile") - if touched: - print(f" WARNING: mesh_obj_path set -- {', '.join(touched)} will have no " - f"effect (mesh sourced from {mesh_obj_path}, no marching cubes step runs).") - _generate_mesh_from_obj(mesh_obj_path, arr, dest_local, vol, verbose, - swap_xz=mesh_obj_swap_xz) - elif generate_mesh: + if layer_type == "segmentation" and generate_mesh: + if mesh_obj_path: + _generate_mesh_from_obj(mesh_obj_path, dest_local, vol, verbose) + else: _generate_external_mesh( - arr, dest_local, vol, voxel_size, voxel_offset, dust_threshold, verbose, + intensity_for_mask, dest_local, vol, voxel_size, voxel_offset, dust_threshold, verbose, mask=mask, mesh_min_intensity=mesh_min_intensity, mesh_max_intensity=mesh_max_intensity, mesh_percentile=mesh_percentile, mesh_format=mesh_format, decimate_fraction=decimate_fraction, max_simplification_error=max_simplification_error, ) - else: - if verbose: - print(" generate_mesh=False, skipping mesh generation") return dest_local @@ -406,9 +382,10 @@ def _generate_external_mesh(arr, dest_local, vol, voxel_size, voxel_offset, dust mask="none", mesh_min_intensity=None, mesh_max_intensity=None, mesh_percentile=None, mesh_format="legacy", decimate_fraction=0.0, max_simplification_error=10): - """Generate a single mesh from the outer boundary of the mesh mask (see - _select_mesh_mask). A single mesh with segment ID = the lowest non-zero segment ID - present, vertices transformed to physical coordinates including voxel_offset. + """Generate a single mesh (segment ID 1) from the outer boundary of the mesh mask + (see _select_mesh_mask), vertices in physical units including voxel_offset. + `arr` is the ORIGINAL intensity volume so percentile/otsu masks still mean + something; the stored segmentation is always {0, 1}. """ if mesh_format == "legacy": @@ -428,9 +405,7 @@ def _generate_external_mesh(arr, dest_local, vol, voxel_size, voxel_offset, dust print(f" Skipping mesh: only {voxel_count} non-zero voxels (< {dust_threshold})") return - all_segments = np.unique(arr) - all_segments = all_segments[all_segments > 0] - mesh_seg_id = int(all_segments[0]) + mesh_seg_id = 1 # the stored segmentation is {0, 1} -- see convert_nrrd() if mesh_format == "multires_draco": _generate_draco_mesh( @@ -456,11 +431,10 @@ def _generate_external_mesh(arr, dest_local, vol, voxel_size, voxel_offset, dust print(" Merged mesh has no geometry") return - # Transform vertices to physical coordinates (resolution + offset) + # Transform vertices to physical coordinates: (voxel index + voxel_offset) * resolution vertices = vertices.astype(np.float32) - vertices[:, 0] = vertices[:, 0] * voxel_size[0] + voxel_offset[0] - vertices[:, 1] = vertices[:, 1] * voxel_size[1] + voxel_offset[1] - vertices[:, 2] = vertices[:, 2] * voxel_size[2] + voxel_offset[2] + for ax in range(3): + vertices[:, ax] = (vertices[:, ax] + voxel_offset[ax]) * voxel_size[ax] faces = faces.astype(np.uint32) if verbose: @@ -481,52 +455,25 @@ def _generate_external_mesh(arr, dest_local, vol, voxel_size, voxel_offset, dust print(f" Wrote merged external boundary mesh (segment ID {mesh_seg_id})") -def _generate_mesh_from_obj(obj_path, arr, dest_local, vol, verbose, swap_xz=False): +def _generate_mesh_from_obj(obj_path, dest_local, vol, verbose): """Use an existing volume_man.obj as the mesh source instead of marching cubes - on the NRRD volume (see vfb_pipeline.py's --mesh-from-obj). The OBJ is used - as-is -- mask/mesh_format/decimate_fraction/max_simplification_error don't apply - here, only to the marching-cubes path in _generate_external_mesh. - - swap_xz: True for a pre-existing external obj stored in NRRD's native (Z, Y, X) - order instead of (X, Y, Z) -- see vfb_pipeline.write_precomputed()'s swap_xz. + on the NRRD volume. The OBJ is used as-is: VFB OBJ vertices are X, Y, Z in + microns (checked against the NRRD voxel extents of templates, painted domains, + FlyWire/hemibrain neurons and LM neurons -- all agree): same axis order as the + volume, so no swap; scaled um -> nm to match the volume's resolution. + mask/mesh_format/decimate_fraction/max_simplification_error don't apply here. """ _setup_mesh_metadata(dest_local, vol, verbose) - mesh = trimesh.load(obj_path, force="mesh") if not isinstance(mesh, trimesh.Trimesh): raise ValueError(f"Could not load as triangle mesh: {obj_path}") - - if swap_xz: - mesh.vertices = mesh.vertices[:, [2, 1, 0]] - - all_segments = np.unique(arr) - all_segments = all_segments[all_segments > 0] - if len(all_segments) == 0: - if verbose: - print(" No non-zero voxels found, skipping mesh generation") - return - mesh_seg_id = int(all_segments[0]) - - # OBJ vertices are physical microns, same as this dataset's voxel_size (detected - # straight from the NRRD header's "space directions"/"spacings", themselves in - # microns -- see detect_spacing() and README.md's template voxel-size table, e.g. - # JRC2018Unisex 0.519 um). No unit conversion here: unlike vfb_pipeline's standalone - # write_precomputed() (OBJ-only path, no NRRD to read a voxel_size from -- it uses - # a hardcoded nm-scale resolution and therefore multiplies vertices by 1000 to - # bridge um->nm), this vol's resolution field is already in the same microns as the - # OBJ. Applying that *1000.0 here would make the mesh ~1000x too big relative to - # this volume's own grid. - vertices = mesh.vertices.astype(np.float32) + vertices = (mesh.vertices * NM_PER_UM).astype(np.float32) # um -> nm faces = mesh.faces.astype(np.uint32) - if verbose: print(f" Using mesh from {obj_path}: {len(vertices)} vertices, {len(faces)} faces") - - mesh_obj = Mesh(vertices, faces, segid=mesh_seg_id) - vol.mesh.put(mesh_obj, compress=False) - + vol.mesh.put(Mesh(vertices, faces, segid=1), compress=False) if verbose: - print(f" Wrote mesh from volume_man.obj (segment ID {mesh_seg_id})") + print(" Wrote mesh from volume_man.obj (segment ID 1)") def _generate_draco_mesh( @@ -618,22 +565,19 @@ def main(): help="Output directory for precomputed datasets") parser.add_argument("--dataset-name", default=None, help="Name for the output dataset (default: derived from input)") - parser.add_argument("--threshold", type=float, default=None, - help="(unused, kept for CLI compatibility)") + parser.add_argument("--layer-type", choices=["auto", "image", "segmentation"], default="auto", + help="What the volume is (see convert_nrrd()): 'image' keeps the intensities " + "(templates, expression patterns); 'segmentation' makes every non-zero " + "voxel segment 1 and writes one mesh (neurons, clones, domains); " + "'auto' (default) picks segmentation for a single-valued mask or when " + "--mesh-obj is given, else image.") + parser.add_argument("--mesh-obj", default=None, + help="Existing volume_man.obj to use as the segment-1 mesh instead of " + "marching cubes (segmentation only).") parser.add_argument("--dust-threshold", type=int, default=100, help="Minimum voxel count for mesh generation (default: 100)") - parser.add_argument("--merge-segments", action="store_true", - help="(unused, kept for CLI compatibility)") - parser.add_argument("--min-intensity", type=int, default=None, - help="Minimum segment ID/intensity to keep in the STORED volume " - "(destructive, values below will be set to 0)") - parser.add_argument("--max-intensity", type=int, default=None, - help="Maximum segment ID/intensity to keep in the STORED volume " - "(destructive, values above will be set to 0)") - parser.add_argument("--generate-mesh", action="store_true", - help="Generate a marching-cubes mesh from the NRRD volume's external " - "boundary (default: off). Independent of --mesh-format/--mask/" - "--decimate-fraction/etc, which only take effect when this is set.") + parser.add_argument("--no-mesh", action="store_true", + help="Segmentation only: write the chunks but no mesh.") parser.add_argument("--mask", choices=["none", "otsu", "minmax"], default="none", help="OPTIONAL. 'none' (default): no mask cleanup. 'otsu': automatic " "threshold, no extra params needed. 'minmax': explicit intensity " @@ -665,10 +609,9 @@ def main(): help="Regenerate even if --output-dir/--dataset-name already has an " "info file (default: skip existing results without touching them)") parser.add_argument("--compress", action="store_true", - help="Zip the output neuroglancer/ folder into a single artifact " - "(default: off, leaves the raw uncompressed tree as-is). " - "No gzip/brotli choice anymore -- if set, this simply zips the " - "whole folder; see mesh_compression/zip_output.py.") + help="Zip the output folder into a single .zip artifact " + "(default: off, leaves the raw uncompressed tree as-is); see " + "mesh_compression/zip_output.py.") parser.add_argument("--verbose", action="store_true") args = parser.parse_args() @@ -678,7 +621,7 @@ def main(): try: validate_mesh_params(args.mask, args.mesh_min_intensity, args.mesh_max_intensity, args.mesh_percentile, args.mesh_format, args.decimate_fraction, - args.generate_mesh, args.verbose) + not args.no_mesh, args.verbose) except ValueError as e: parser.error(str(e)) @@ -718,12 +661,10 @@ def main(): try: dest_local = convert_nrrd( nrrd_path, output_dir, dataset_name, - threshold=args.threshold, + layer_type=args.layer_type, dust_threshold=args.dust_threshold, - merge_segments=args.merge_segments, - min_intensity=args.min_intensity, - max_intensity=args.max_intensity, - generate_mesh=args.generate_mesh, + generate_mesh=not args.no_mesh, + mesh_obj_path=args.mesh_obj, mask=args.mask, mesh_min_intensity=args.mesh_min_intensity, mesh_max_intensity=args.mesh_max_intensity, diff --git a/applications/pipeline/requirements.txt b/applications/pipeline/requirements.txt index be61e4bc..bce3e7ff 100644 --- a/applications/pipeline/requirements.txt +++ b/applications/pipeline/requirements.txt @@ -19,8 +19,7 @@ igneous-pipeline==4.36.0 zmesh>=1.13.1 DracoPy>=1.7.0 -# VFB Knowledge Base connectivity (optional, for --use-kb mode) -vfb-connect>=2.0.0 +# (--use-kb talks to kb.virtualflybrain.org over HTTP with `requests`; vfb-connect is not needed) # SWC to mesh conversion navis>=1.0.0 diff --git a/applications/pipeline/vfb_pipeline.py b/applications/pipeline/vfb_pipeline.py index c0c1ec94..eeb0a056 100755 --- a/applications/pipeline/vfb_pipeline.py +++ b/applications/pipeline/vfb_pipeline.py @@ -1,287 +1,205 @@ #!/usr/bin/env python3 """ -VFB Jenkins Pipeline: Generate missing volume_man.obj files from SWC skeletons -and create Neuroglancer precomputed mesh data. - -Designed to run on the VFB Jenkins server where -https://www.virtualflybrain.org/data/ is mounted at /IMAGE_WRITE/ - -Workflow: - 1. Discover image directories (filesystem scan or KB query) - 2. For each image with volume.swc but no volume_man.obj → generate OBJ - 3. For each image with volume_man.obj but no neuroglancer/ → generate precomputed - -Discovery modes: - - Default: scan /IMAGE_WRITE/VFB/i/ filesystem - - --use-kb: query kb.virtualflybrain.org for live images from production - datasets only (requires vfb-connect package) - -Folder structure per image: - /IMAGE_WRITE/VFB/i/{first4}/{last4}/{template_id}/ - ├── volume.swc (existing) - ├── volume.obj (existing, auto-generated point cloud) - ├── volume_man.obj ← generated from SWC if missing +VFB pipeline: precomputed (Neuroglancer-format) data for every VFB image folder. + +For each image folder + /data/VFB/i/{first4}/{last4}/{template_id}/ (the image store, read-write) ├── volume.nrrd (existing) - ├── volume.wlz (existing) - ├── neuroglancer/ ← NEW precomputed mesh (chunks/mesh written uncompressed, - │ ├── info no segment_properties/ -- our mesh is always a single - │ └── mesh/ synthetic merged segment, never real per-segment labels) - │ ├── info - │ ├── 1:0 - │ └── 1:0:1 - └── neuroglancer.zip ← whole neuroglancer/ folder zipped as one artifact, - only when --compress is passed (see mesh_compression/zip_output.py); - this is what Neuroglancer's client-side zip-kvstore - adapter reads via HTTP - Range requests, instead of per-chunk gzip/brotli - + a server-side Content-Encoding hack. - -Neuroglancer URL (directory form, still works locally): - precomputed://https://www.virtualflybrain.org/data/VFB/i/{first4}/{last4}/{template_id}/neuroglancer + ├── volume.swc (existing, skeletons only) + ├── volume_man.obj (existing mesh; generated from volume.swc when missing) + ├── volume.obj, volume.wlz, thumbnail*.png (existing, untouched) + └── precomputed.zip ← this pipeline's one output: a precomputed dataset + (info, 0/ chunks, mesh/) zipped as a single archive + that Neuroglancer reads through its zip kvstore: + https://.../VFB_xxx/precomputed.zip|zip:|neuroglancer-precomputed: + plus provenance.json (pipeline version + source file + stamps) so a re-run knows when it is up to date. + +What gets written depends on what the image IS (its VFB category, from the KB), +not on the voxel dtype -- every VFB NRRD is uint8: + + category layer chunks (0/) mesh + template image intensities none + expression image intensities none (GAL4/split patterns, MCFO fragments) + object segmentation {0,1} segment 1: volume_man.obj when it has faces, + else generated from volume.swc, else + marching cubes on the NRRD + (neurons, clones, painted domains) + +Axes and units: everything is X, Y, Z -- the NRRD as pynrrd returns it, the OBJ/SWC +vertices, and the precomputed output. No transposes, no swaps. Source files are in +microns; the precomputed resolution and mesh vertices are written in nanometres, the +unit the precomputed spec defines (so VFB data composes with other precomputed +sources such as FlyWire's). + +The build happens in --work-dir (local scratch), and only the finished zip is +moved into the image folder: written as precomputed.zip.tmp- and renamed, so +a reader never sees a partial file and a killed run leaves nothing to mistake for +output. + +Discovery: --use-kb (production datasets only, with the category) or a filesystem +scan (category: template when vfb_id == template_id, else decided from the data). Usage: - # Dry run — show what would be done - python vfb_pipeline.py --dry-run - - # Process everything - python vfb_pipeline.py - - # Process specific IDs - python vfb_pipeline.py --ids VFB_00000001 VFB_00000002 - - # Use KB to discover only live images from production datasets - python vfb_pipeline.py --use-kb - - # Process from a file - python vfb_pipeline.py --ids-file missing_objs.txt - - # Force regeneration even if outputs exist - python vfb_pipeline.py --force + python vfb_pipeline.py --image-root /data --use-kb --template VFB_00101567 --dry-run + python vfb_pipeline.py --image-root /data --ids VFB_00101567 VFB_00102107 --work-dir /scratch + python vfb_pipeline.py --image-root /data --ids-file batch.txt --work-dir /scratch """ from __future__ import annotations import argparse -import importlib.util +import datetime as _dt import json import logging import os import shutil import sys import time -import types import zipfile from pathlib import Path import numpy as np +import requests import trimesh from cloudvolume import CloudVolume from cloudvolume.mesh import Mesh -# Import NRRD converter (same package) -try: - from convert_nrrd import ( - convert_nrrd as _convert_nrrd, - validate_mesh_params as _validate_mesh_params, - read_nrrd_voxel_size as _read_nrrd_voxel_size, - ) -except ImportError: - _convert_nrrd = None - _validate_mesh_params = None - _read_nrrd_voxel_size = None - +from convert_nrrd import ( + NM_PER_UM, + convert_nrrd as _convert_nrrd, + validate_mesh_params as _validate_mesh_params, +) import mesh_compression # --------------------------------------------------------------------------- # Configuration # --------------------------------------------------------------------------- -IMAGE_ROOT = "/IMAGE_WRITE" +# Bump when the output format or conversion changes in a way that should make +# existing precomputed.zip files stale (they are regenerated on the next run). +PIPELINE_VERSION = "2" + +OUTPUT_NAME = "precomputed" # work folder name and the zip's basename +OUTPUT_ZIP = OUTPUT_NAME + ".zip" +PROVENANCE_NAME = "provenance.json" # entry inside the zip (Neuroglancer ignores it) +SOURCE_FILES = ("volume.nrrd", "volume_man.obj", "volume.swc") # stamped in provenance + +IMAGE_ROOT = "/data" VFB_DATA_DIR = os.path.join(IMAGE_ROOT, "VFB", "i") -# Fallback resolution (um, JRC2018Unisex), used by write_precomputed() ONLY when an -# image directory has no volume.nrrd of its own to read the real voxel size from -- -# see process_image()'s Step 2a and read_nrrd_voxel_size() in convert_nrrd.py. +# Fallback resolution (um, JRC2018Unisex) for a mesh-only build of an image folder +# with no volume.nrrd to read the real voxel size from. DEFAULT_RESOLUTION = [0.5189161, 0.5189161, 1.0] -# Default processing order when --template is not given. -# Templates listed here are processed first, in order; any others come after. -# Short_forms of the anatomical template individual (VFB_…), matching both the -# filesystem directory name and `t.short_form` returned by the KB query. -DEFAULT_TEMPLATE_ORDER = [ - "VFB_00101567", # JRC2018U / JRC2018Unisex - "VFB_00200000", # JRCVNC2018U / JRC2018UnisexVNC -] - -# KB (Knowledge Base) endpoint for VFBconnect -KB_ENDPOINT = "http://kb.virtualflybrain.org" -KB_USER = "neo4j" -KB_PASSWORD = "vfb" +# Never converted, whatever else is asked for: the FlyEM hemibrain-aligned versions of images are not wanted. +EXCLUDED_TEMPLATES = {"VFB_00101384"} # JRC FlyEM Hemibrain -# Folder URL prefix in KB → local path mapping +KB_ENDPOINT = os.environ.get("VFB_KB", "http://kb.virtualflybrain.org") +KB_USER = "neo4j" # the published read-only pair +KB_PASSWORD = "vfb" KB_FOLDER_URL_PREFIX = "http://www.virtualflybrain.org/data/" +CATEGORY_TEMPLATE = "template" +CATEGORY_EXPRESSION = "expression" +CATEGORY_OBJECT = "object" + log = logging.getLogger("vfb_pipeline") # --------------------------------------------------------------------------- -# KB Discovery: query kb.virtualflybrain.org for live image directories +# KB discovery (read-only Cypher over the HTTP transaction endpoint) # --------------------------------------------------------------------------- -def _get_neo4j_connect(): - """Import Neo4jConnect without triggering vfb_connect's slow __init__. +def kb_query(cypher: str, endpoint: str = KB_ENDPOINT) -> list[dict]: + """Run one read-only Cypher statement and return rows as dicts.""" + r = requests.post(f"{endpoint}/db/data/transaction/commit", + auth=(KB_USER, KB_PASSWORD), timeout=600, + json={"statements": [{"statement": cypher}]}) + r.raise_for_status() + body = r.json() + if body.get("errors"): + raise RuntimeError(f"KB query failed: {body['errors']}") + res = body["results"][0] + return [dict(zip(res["columns"], row["row"])) for row in res["data"]] - The vfb_connect package's __init__.py instantiates a global VfbConnect - object that connects to PDB and caches all terms, which blocks for a very - long time. We bypass this by stubbing the top-level package and importing - the Neo4j module directly. - """ - # If already imported (e.g. caller already set up the bypass), just use it - if "vfb_connect.neo.neo4j_tools" in sys.modules: - mod = sys.modules["vfb_connect.neo.neo4j_tools"] - return mod.Neo4jConnect, mod.dict_cursor - - # Remove any existing stub so find_spec works on the real package - saved = sys.modules.pop("vfb_connect", None) - try: - spec = importlib.util.find_spec("vfb_connect") - finally: - # Restore or re-stub immediately - if saved is not None: - sys.modules["vfb_connect"] = saved - if spec is None or spec.submodule_search_locations is None: - raise ImportError("vfb_connect is not installed — pip install vfb-connect") +def _safe_ids(ids: list[str] | None) -> list[str]: + """Only simple VFB-style short_forms go into Cypher literals.""" + return [t for t in (ids or []) if t and all(ch.isalnum() or ch == "_" for ch in t)] - pkg = types.ModuleType("vfb_connect") - pkg.__path__ = list(spec.submodule_search_locations) - sys.modules["vfb_connect"] = pkg - from vfb_connect.neo.neo4j_tools import Neo4jConnect, dict_cursor # noqa: E402 - return Neo4jConnect, dict_cursor +def _folder_to_dir(folder_url: str, image_root: str) -> str | None: + if not folder_url or not folder_url.startswith(KB_FOLDER_URL_PREFIX): + return None + return os.path.join(image_root, folder_url[len(KB_FOLDER_URL_PREFIX):].rstrip("/")) -def iter_kb_image_dirs(image_root: str = IMAGE_ROOT, - templates: list[str] | None = None): - """Query KB for live image folders from production datasets. - Yields (image_dir, vfb_id, template_id) tuples, matching the - interface of iter_image_dirs(). +def iter_kb_image_dirs(image_root: str = IMAGE_ROOT, templates: list[str] | None = None): + """Yield (image_dir, vfb_id, template_id, category) for every live image in a + production dataset, registered to one of `templates` (all templates when None). - The ``in_register_with`` edge points at a *channel* individual (``VFBc_…``). - The anatomical template individual (``VFB_…``) is reached via - ``(channel)-[:depicts]->(template)``, so filtering by template short_form - must be applied to the template node, not the channel. + `in_register_with` points at the template *channel* (VFBc_…); the anatomical + template individual (VFB_…) is reached via (channel)-[:depicts]->(template), so + the template filter is applied there. JFRC2 (VFBc_00017894) is excluded as before. - ``templates``: optional list of template short_forms (e.g. ``VFB_00101567``) - to restrict the query to. + category: 'expression' when the individual is typed by a VFBexp_ (expression + pattern / split) or VFBext_ (fragment) class, else 'object' (FBbt-typed neurons, + clones, painted domains). Template images come from iter_kb_template_dirs(). """ - Neo4jConnect, dict_cursor = _get_neo4j_connect() - nc = Neo4jConnect(endpoint=KB_ENDPOINT, usr=KB_USER, pwd=KB_PASSWORD) - - template_clause = "" - if templates: - # Guard against Cypher injection: only allow simple VFB-style ids. - safe = [t for t in templates if all(ch.isalnum() or ch == "_" for ch in t)] - if not safe: - log.warning("No valid template short_forms in filter %s", templates) - return - quoted = ", ".join("'" + t + "'" for t in safe) - template_clause = f" AND t.short_form IN [{quoted}]\n" - - query = f""" + safe = _safe_ids(templates) + clause = f" AND t.short_form IN [{', '.join(repr(t) for t in safe)}]\n" if safe else "" + cypher = f""" MATCH (c:Individual)-[:depicts]->(i:Individual)-[:has_source]->(ds:DataSet) MATCH (c)-[r:in_register_with]->(tc:Template)-[:depicts]->(t:Template) WHERE ds.production[0] = true AND r.folder IS NOT NULL AND (r.block IS NULL OR NOT r.block[0] = 'Missing Image') AND NOT tc.short_form = 'VFBc_00017894' -{template_clause} RETURN DISTINCT i.short_form AS id, r.folder[0] AS folder, t.short_form AS template + {clause} + OPTIONAL MATCH (i)-[:INSTANCEOF]->(cl:Class) + WITH DISTINCT i, r.folder[0] AS folder, t.short_form AS template, + collect(DISTINCT cl.short_form) AS classes + RETURN i.short_form AS id, folder, template, + CASE WHEN any(x IN classes WHERE x STARTS WITH 'VFBexp_' OR x STARTS WITH 'VFBext_') + THEN '{CATEGORY_EXPRESSION}' ELSE '{CATEGORY_OBJECT}' END AS category """ - log.info("Querying KB at %s for live image directories...", KB_ENDPOINT) - results = nc.commit_list([query]) - rows = dict_cursor(results) - - count = 0 - for row in rows: - folder_url = row["folder"] - vfb_id = row["id"] - - # Map URL to local path: replace URL prefix with IMAGE_ROOT - if not folder_url.startswith(KB_FOLDER_URL_PREFIX): - log.debug(" Skipping unexpected folder URL: %s", folder_url) + n = 0 + for row in kb_query(cypher): + image_dir = _folder_to_dir(row["folder"], image_root) + if image_dir is None: + log.debug(" Skipping unexpected folder URL: %s", row["folder"]) continue - - rel_path = folder_url[len(KB_FOLDER_URL_PREFIX):] - # Strip trailing slash - rel_path = rel_path.rstrip("/") - image_dir = os.path.join(image_root, rel_path) - - # Prefer the template individual's short_form from the KB; fall back - # to the last path component if the query didn't return one. - template_id = row.get("template") or os.path.basename(image_dir) - - count += 1 - yield image_dir, vfb_id, template_id - - log.info("KB returned %d live image directories", count) - - -def get_kb_template_image_dirs(templates: list[str], - image_root: str = IMAGE_ROOT) -> list[tuple]: - """Fetch each template's own image folder from the KB. - - Returns a list of (image_dir, vfb_id, template_id) tuples where - vfb_id == template_id. Unlike iter_kb_image_dirs(), this does NOT filter - on production datasets — templates frequently lack a has_source edge to a - DataSet, so the main query would otherwise omit them. - - Folder URLs live on the template channel's self in_register_with edge - (tc)-[rt:in_register_with]->(tc), not on the c→tc edge that - iter_kb_image_dirs follows. URL→path mapping uses the same - KB_FOLDER_URL_PREFIX so the rest of the pipeline is unchanged. - """ - if not templates: - return [] - - # Guard against Cypher injection: only allow simple VFB-style ids. - safe = [t for t in templates if all(ch.isalnum() or ch == "_" for ch in t)] - if not safe: - return [] - - Neo4jConnect, dict_cursor = _get_neo4j_connect() - nc = Neo4jConnect(endpoint=KB_ENDPOINT, usr=KB_USER, pwd=KB_PASSWORD) - - quoted = ", ".join("'" + t + "'" for t in safe) - query = f""" + n += 1 + yield image_dir, row["id"], row["template"] or os.path.basename(image_dir), row["category"] + log.info("KB returned %d live image directories", n) + + +def iter_kb_template_dirs(image_root: str = IMAGE_ROOT, templates: list[str] | None = None): + """Yield (image_dir, template_id, template_id, 'template') for each template's own + image folder. Templates usually have no has_source DataSet, so the main query + omits them; their folder lives on the channel's self in_register_with edge.""" + safe = _safe_ids(templates) + clause = f" AND t.short_form IN [{', '.join(repr(t) for t in safe)}]\n" if safe else "" + cypher = f""" MATCH (tc:Template)-[:depicts]->(t:Template) MATCH (tc)-[rt:in_register_with]->(tc) - WHERE t.short_form IN [{quoted}] - AND rt.folder IS NOT NULL + WHERE rt.folder IS NOT NULL + AND NOT tc.short_form = 'VFBc_00017894' + {clause} RETURN DISTINCT t.short_form AS template, rt.folder[0] AS folder """ - - log.info("Querying KB for template image folders: %s", safe) - rows = dict_cursor(nc.commit_list([query])) - - out = [] - for row in rows: - folder_url = row["folder"] - tid = row["template"] - if not folder_url.startswith(KB_FOLDER_URL_PREFIX): - log.debug(" Skipping unexpected folder URL: %s", folder_url) - continue - rel_path = folder_url[len(KB_FOLDER_URL_PREFIX):].rstrip("/") - image_dir = os.path.join(image_root, rel_path) - out.append((image_dir, tid, tid)) - return out + for row in kb_query(cypher): + image_dir = _folder_to_dir(row["folder"], image_root) + if image_dir is not None: + yield image_dir, row["template"], row["template"], CATEGORY_TEMPLATE # --------------------------------------------------------------------------- # Discovery: find image directories and classify them # --------------------------------------------------------------------------- -# Volume files that indicate an image directory -_VOLUME_FILES = {"volume.nrrd", "volume.swc", "volume.wlz", "volume.obj"} +_VOLUME_FILES = {"volume.nrrd", "volume.swc", "volume.wlz", "volume.obj", "volume_man.obj"} def _has_volume_files(directory: Path) -> bool: @@ -337,49 +255,59 @@ def has_faces(obj_path: str) -> bool: return False -def _zip_has_volume_chunks(zip_path: Path) -> bool: - """Whether a compressed neuroglancer.zip contains 0/ volume chunks, without - extracting anything -- mirrors the uncompressed (d / "neuroglancer" / "0").is_dir() - check for the case where the source folder was removed after zipping (see - process_image()'s compress step).""" +def _stamp(path: Path) -> dict | None: + try: + st = path.stat() + except FileNotFoundError: + return None + return {"size": st.st_size, "mtime": int(st.st_mtime)} + + +def source_stamps(image_dir: str) -> dict: + """size/mtime of the files the output is derived from (None when absent).""" + d = Path(image_dir) + return {name: _stamp(d / name) for name in SOURCE_FILES} + + +def read_provenance(zip_path: Path) -> dict | None: + """provenance.json from inside precomputed.zip, or None if absent/unreadable. + Reads only the central directory plus one small entry.""" try: with zipfile.ZipFile(zip_path) as zf: - return any(n.startswith("0/") for n in zf.namelist()) - except zipfile.BadZipFile: - return False + if PROVENANCE_NAME not in zf.namelist(): + return None + return json.loads(zf.read(PROVENANCE_NAME)) + except (zipfile.BadZipFile, OSError, ValueError): + return None def classify_dir(image_dir: str) -> dict: - """Classify what files exist and what needs to be done for an image directory.""" + """What is in an image directory and whether its precomputed.zip is current.""" d = Path(image_dir) - ng_dir = d / "neuroglancer" - ng_zip = d / "neuroglancer.zip" - has_ng_dir = (ng_dir / "info").is_file() - has_ng_zip = ng_zip.is_file() + obj = d / "volume_man.obj" + zip_path = d / OUTPUT_ZIP + has_zip = zip_path.is_file() + prov = read_provenance(zip_path) if has_zip else None + stamps = source_stamps(image_dir) + up_to_date = bool( + prov + and prov.get("pipeline_version") == PIPELINE_VERSION + and prov.get("sources") == stamps + ) return { "has_swc": (d / "volume.swc").is_file(), "has_nrrd": (d / "volume.nrrd").is_file(), - "has_obj_man": (d / "volume_man.obj").is_file(), - "has_obj_man_faces": ( - has_faces(str(d / "volume_man.obj")) - if (d / "volume_man.obj").is_file() - else False - ), - # --compress removes neuroglancer/ after zipping it (see process_image()), so - # a completed compressed instance only has neuroglancer.zip, no folder. - "has_neuroglancer": has_ng_dir or has_ng_zip, - # 0/ directory holds the volume chunks. Mesh-only outputs from - # write_precomputed() have neuroglancer/info but no neuroglancer/0/. Checked - # inside the zip too, since compress removes the loose folder. - "has_volume_chunks": ( - (ng_dir / "0").is_dir() - or (has_ng_zip and _zip_has_volume_chunks(ng_zip)) - ), + "has_obj_man": obj.is_file(), + "has_obj_man_faces": has_faces(str(obj)) if obj.is_file() else False, + "has_zip": has_zip, + "provenance": prov, + "sources": stamps, + "up_to_date": up_to_date, } # --------------------------------------------------------------------------- -# SWC → OBJ conversion (imported from convert_swc_to_mesh) +# SWC → OBJ conversion # --------------------------------------------------------------------------- def parse_swc(filepath: str) -> dict: @@ -498,7 +426,9 @@ def generate_obj_from_swc(image_dir: str) -> str: log.info(" Generating OBJ from SWC: %s", swc_path) mesh = swc_to_mesh(swc_path) - mesh.export(obj_path, file_type="obj") + tmp_path = f"{obj_path}.tmp-{os.getpid()}" + mesh.export(tmp_path, file_type="obj") + os.replace(tmp_path, obj_path) # readers never see a partial file log.info(" Saved: %s (%d vertices, %d faces)", obj_path, len(mesh.vertices), len(mesh.faces)) return obj_path @@ -508,60 +438,35 @@ def generate_obj_from_swc(image_dir: str) -> str: # OBJ → Neuroglancer precomputed # --------------------------------------------------------------------------- -def write_precomputed(obj_path: str, output_dir: str, - resolution: list[float] = DEFAULT_RESOLUTION, - segment_id: int = 1, swap_xz: bool = False): - """Convert OBJ mesh to Neuroglancer precomputed format (uncompressed). - - `resolution` must be in the OBJ's own physical units (microns), matching - whatever this image's (or its template's) volume.nrrd header reports via - detect_spacing() -- see process_image()'s Step 2a, which resolves this per - image before calling here. No unit conversion is applied to the mesh: OBJ - vertices are already physical microns, same as `resolution`, so the two stay - in the same coordinate space as the NRRD path (convert_nrrd.py) -- these used - to disagree by a hardcoded 1000x nm conversion here, which misaligned/oversized - OBJ-path meshes relative to anything produced via the NRRD path (e.g. templates, - always NRRD-path -- see is_template_image in process_image()). - - swap_xz: some pre-existing volume_man.obj files (built upstream directly off the - raw NRRD array) store vertices in NRRD's native (Z, Y, X) order instead of - Neuroglancer's (X, Y, Z) -- the same axis reshuffle convert_nrrd.py applies via - np.transpose(data, (2, 1, 0)) for the volume itself. Confirmed empirically - (VFB_jrchk0ew): obj column 0 matched the correct physical Z range, column 2 - matched X, column 1 (Y) was already correct. Only pass True for such - pre-existing objs -- ones generate_obj_from_swc() builds from a .swc file this - run are already in true X,Y,Z (no NRRD array involved) and must NOT be swapped. - """ +# --------------------------------------------------------------------------- +# OBJ → precomputed (mesh only, for an object with no volume.nrrd) +# --------------------------------------------------------------------------- + +def write_mesh_only_precomputed(obj_path: str, output_dir: str, + resolution: list[float] = DEFAULT_RESOLUTION, + segment_id: int = 1) -> None: + """A segmentation dataset holding just one legacy mesh (no 0/ chunks). + + OBJ vertices are X, Y, Z in microns, as is `resolution`; both are written in + nanometres (the spec's unit), nothing is swapped. The declared grid is anchored + on the mesh's bounding box (voxel_offset in VOXEL units) so Neuroglancer's + default view lands on it. + """ mesh = trimesh.load(obj_path, force="mesh") if not isinstance(mesh, trimesh.Trimesh): raise ValueError("Could not load as triangle mesh: " + obj_path) - - if swap_xz: - mesh.vertices = mesh.vertices[:, [2, 1, 0]] - - log.info(" Writing precomputed: %s (%d verts, %d faces)", + mesh.vertices = mesh.vertices * NM_PER_UM + resolution = [r * NM_PER_UM for r in resolution] + log.info(" Writing mesh-only precomputed: %s (%d verts, %d faces)", output_dir, len(mesh.vertices), len(mesh.faces)) - os.makedirs(output_dir, exist_ok=True) - dest = "file://" + output_dir - mesh_max = mesh.vertices.max(axis=0) mesh_min = mesh.vertices.min(axis=0) - size = [ - int(np.ceil((mesh_max[i] - mesh_min[i]) / resolution[i])) + 2 - for i in range(3) - ] - # voxel_offset is in VOXEL units (physical origin = voxel_offset * resolution) -- - # anchor the declared grid at the mesh's own bounding box, not [0, 0, 0]. A mesh - # that isn't near world-origin (e.g. an individual neuron registered onto a - # whole-brain template, sitting at physical position ~300+ instead of ~0) would - # otherwise declare a grid nowhere near its actual vertices, and Neuroglancer's - # default camera (centered on the declared grid) would never show it. + size = [int(np.ceil((mesh_max[i] - mesh_min[i]) / resolution[i])) + 2 for i in range(3)] voxel_offset = [int(np.floor(mesh_min[i] / resolution[i])) for i in range(3)] - info = { - "data_type": "uint32", + "data_type": "uint8", "num_channels": 1, "type": "segmentation", "mesh": "mesh", @@ -574,514 +479,313 @@ def write_precomputed(obj_path: str, output_dir: str, "voxel_offset": voxel_offset, }], } - - vol = CloudVolume(dest, mip=0, info=info, compress=False) + vol = CloudVolume("file://" + output_dir, mip=0, info=info, compress=False) vol.commit_info() - - # Mesh directory mesh_dir = os.path.join(output_dir, "mesh") os.makedirs(mesh_dir, exist_ok=True) with open(os.path.join(mesh_dir, "info"), "w") as f: json.dump({"@type": "neuroglancer_legacy_mesh"}, f) - - vertices = mesh.vertices.astype(np.float32) - faces = mesh.faces.astype(np.uint32) - mesh_obj = Mesh(vertices, faces, segid=segment_id) - vol.mesh.put(mesh_obj, compress=False) - # No segment_properties -- this is always a single synthetic segment with a - # placeholder label ("mesh"), never real per-segment labels, so a - # segment_properties list would be misleading rather than informative - # (see NEUROGLANCER_STANDARDIZATION.md item 3). - - log.info(" Precomputed written: %s", output_dir) + vol.mesh.put(Mesh(mesh.vertices.astype(np.float32), mesh.faces.astype(np.uint32), + segid=segment_id), compress=False) # --------------------------------------------------------------------------- -# Pipeline logic +# Per-image processing # --------------------------------------------------------------------------- -def process_image(image_dir: str, vfb_id: str, template_id: str, - force: bool = False, overwrite: bool = False, - dry_run: bool = False, - merge_segments: bool = False, - min_intensity: int | None = None, - max_intensity: int | None = None, - resolution: list[float] = DEFAULT_RESOLUTION, - generate_mesh: bool = False, - mesh_from_obj: bool = False, - mask: str = "none", - mesh_min_intensity: int | None = None, - mesh_max_intensity: int | None = None, - mesh_percentile: float | None = None, - mesh_format: str = "legacy", - decimate_fraction: float = 0.0, - max_simplification_error: int = 10, - compress: bool = False) -> dict: - """Process a single image directory. Returns a status dict. - - generate_mesh/mask/mesh_*/decimate_fraction/max_simplification_error are passed - straight through to convert_nrrd.convert_nrrd() for the NRRD path -- see that - function's docstring for what each one does. The OBJ mesh path (write_precomputed, - above) doesn't generate a mesh from a volume mask, so none of this applies there. - - mesh_from_obj: only relevant when generate_mesh is also set. generate_mesh forces - the NRRD path (even for a non-template image that would otherwise take the - lightweight OBJ-only path) -- mesh_from_obj then picks the mesh source within it: - if this image directory has a usable volume_man.obj, that OBJ is used as the mesh - source instead of running marching cubes on the NRRD volume (mask/mesh_*/ - decimate_fraction/max_simplification_error are then ignored for this image). - Falls back to marching-cubes NRRD generation, same as mesh_from_obj=False, when no - usable volume_man.obj exists. - """ +def decide_layer_type(category: str | None, status: dict, nrrd_path: str | None) -> str: + """image for templates and expression patterns, segmentation for objects. + Without a KB category (filesystem scan): a volume_man.obj with faces means an + object; otherwise a single-valued mask is an object and intensities are an image.""" + if category == CATEGORY_TEMPLATE or category == CATEGORY_EXPRESSION: + return "image" + if category == CATEGORY_OBJECT: + return "segmentation" + if status["has_obj_man_faces"] or status["has_swc"]: + return "segmentation" + if nrrd_path: + import nrrd + data, _ = nrrd.read(nrrd_path) + return "segmentation" if len(np.unique(data[data > 0])) <= 1 else "image" + return "segmentation" + + +def _write_provenance(folder: str, **fields) -> None: + with open(os.path.join(folder, PROVENANCE_NAME), "w") as f: + json.dump({"pipeline_version": PIPELINE_VERSION, + "generated": _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + **fields}, f, indent=1, sort_keys=True) + + +def _replace_into(src: str, dest: str) -> None: + """Move a finished file into place atomically for readers: copy to a sibling + tmp name in the destination folder, then rename over the final name.""" + tmp = f"{dest}.tmp-{os.getpid()}" + try: + shutil.copyfile(src, tmp) + os.replace(tmp, dest) + finally: + if os.path.exists(tmp): + os.remove(tmp) + if os.path.exists(src): + os.remove(src) - # --overwrite: remove existing neuroglancer/ (and/or its zipped artifact -- see - # the compress step below, which removes the folder after zipping, so a - # completed --compress run leaves only neuroglancer.zip) so it will be regenerated - ng_dir = os.path.join(image_dir, "neuroglancer") - ng_zip = ng_dir + ".zip" - if overwrite: - if os.path.isdir(ng_dir): - if dry_run: - log.info(" [%s] Would delete existing neuroglancer/ for overwrite", vfb_id) - else: - log.info(" [%s] Deleting existing neuroglancer/ (--overwrite)", vfb_id) - shutil.rmtree(ng_dir) - if os.path.isfile(ng_zip): - if dry_run: - log.info(" [%s] Would delete existing neuroglancer.zip for overwrite", vfb_id) - else: - log.info(" [%s] Deleting existing neuroglancer.zip (--overwrite)", vfb_id) - os.remove(ng_zip) +def process_image(image_dir: str, vfb_id: str, template_id: str, category: str | None, + work_dir: str, force: bool = False, dry_run: bool = False, + resolution: list[float] = DEFAULT_RESOLUTION, + mask: str = "none", mesh_min_intensity: int | None = None, + mesh_max_intensity: int | None = None, mesh_percentile: float | None = None, + mesh_format: str = "legacy", decimate_fraction: float = 0.0, + max_simplification_error: int = 10, layer_type: str = "auto", + compress: bool = True) -> dict: + """Build precomputed.zip for one image folder. Returns a status dict.""" status = classify_dir(image_dir) - result = { - "vfb_id": vfb_id, - "template_id": template_id, - "image_dir": image_dir, - "obj_generated": False, - "precomputed_generated": False, - "skipped": False, - "error": None, - } + result = {"vfb_id": vfb_id, "template_id": template_id, "image_dir": image_dir, + "obj_generated": False, "precomputed_generated": False, + "skipped": False, "error": None} - # Template images are volume data (the brain/VNC itself). Always go via - # the NRRD path so neuroglancer/ contains the 0/ volume chunks, not just - # a mesh from volume_man.obj. - is_template_image = vfb_id == template_id - - needs_obj = status["has_swc"] and (not status["has_obj_man"] or - (status["has_obj_man"] and not status["has_obj_man_faces"])) - needs_precomputed = not status["has_neuroglancer"] - # Template images need volume chunks, not just a mesh. If the existing - # neuroglancer/ output was produced by the OBJ-only path, neuroglancer/0/ - # will be missing and we need to regenerate via the NRRD path. - if (is_template_image and status["has_nrrd"] - and status["has_neuroglancer"] - and not status["has_volume_chunks"]): - needs_precomputed = True - # Wipe the mesh-only output (folder and/or its zipped artifact -- compress - # removes the folder after zipping, see the compress step below) so - # convert_nrrd writes a clean tree. - ng_path = Path(image_dir) / "neuroglancer" - ng_zip_path = Path(ng_zip) - if not dry_run: - if ng_path.is_dir(): - log.info(" [%s] Existing neuroglancer/ has no 0/ chunks — removing for regeneration", vfb_id) - shutil.rmtree(ng_path) - if ng_zip_path.is_file(): - log.info(" [%s] Existing neuroglancer.zip has no 0/ chunks — removing for regeneration", vfb_id) - ng_zip_path.unlink() - has_usable_obj = status["has_obj_man"] and status["has_obj_man_faces"] - - if force: - if status["has_swc"]: - needs_obj = True - needs_precomputed = True - - if not needs_obj and not needs_precomputed: + if status["up_to_date"] and not force: result["skipped"] = True - log.debug(" [%s] Already complete, skipping", vfb_id) + log.debug(" [%s] precomputed.zip is current, skipping", vfb_id) + return result + if not status["has_nrrd"] and not status["has_obj_man_faces"] and not status["has_swc"]: + result["skipped"] = True + log.info(" [%s] nothing to convert (no volume.nrrd, volume_man.obj or volume.swc)", vfb_id) return result - obj_status = ("mesh" if status["has_obj_man_faces"] - else "no-faces" if status["has_obj_man"] - else "missing") - log.info("[%s] %s (swc=%s, nrrd=%s, obj_man=%s, ng=%s, ng_0=%s)", - vfb_id, image_dir, - status["has_swc"], status["has_nrrd"], obj_status, - status["has_neuroglancer"], status["has_volume_chunks"]) + nrrd_path = os.path.join(image_dir, "volume.nrrd") if status["has_nrrd"] else None + lt = layer_type if layer_type != "auto" else decide_layer_type(category, status, nrrd_path) + result.update(category=category, layer_type=lt, pipeline_version=PIPELINE_VERSION, + sources=status["sources"]) + needs_obj = lt == "segmentation" and status["has_swc"] and not status["has_obj_man_faces"] + have_obj = status["has_obj_man_faces"] or needs_obj + if lt == "segmentation": + mesh_source = ("volume_man.obj" if status["has_obj_man_faces"] + else "volume.swc" if needs_obj + else "marching-cubes") + else: + mesh_source = None + log.info("[%s] %s category=%s layer=%s nrrd=%s obj=%s swc=%s zip=%s%s", + vfb_id, image_dir, category, lt, status["has_nrrd"], + "faces" if status["has_obj_man_faces"] else status["has_obj_man"], + status["has_swc"], status["has_zip"], + " (stale)" if status["has_zip"] else "") if dry_run: if needs_obj: log.info(" Would generate: volume_man.obj from volume.swc") - # Mirrors the real Step 2a/2b dispatch below (has_usable_obj may still flip to - # True post-dry-run once Step 1 actually generates the OBJ from SWC). - predicted_has_obj = has_usable_obj or needs_obj - predicted_use_nrrd = status["has_nrrd"] and ( - is_template_image or not predicted_has_obj or generate_mesh - ) - suffix = " (template image)" if is_template_image else "" - if needs_precomputed and predicted_use_nrrd: - if generate_mesh and mesh_from_obj and predicted_has_obj: - log.info(" Would generate: neuroglancer/ (including 0/ chunks) from volume.nrrd, " - "mesh from volume_man.obj%s", suffix) - else: - log.info(" Would generate: neuroglancer/ (including 0/ chunks) from volume.nrrd%s", suffix) - elif needs_precomputed and predicted_has_obj: - log.info(" Would generate: neuroglancer/ from volume_man.obj") + log.info(" Would write: %s (%s%s%s)", OUTPUT_ZIP, lt, + ", chunks from volume.nrrd" if nrrd_path else ", mesh only", + f", mesh from {mesh_source}" if mesh_source else "") return result - # Step 1: Generate OBJ from SWC if needed + # Step 1: volume_man.obj from volume.swc when an object has no usable mesh if needs_obj: try: generate_obj_from_swc(image_dir) result["obj_generated"] = True - has_usable_obj = True + status["sources"] = source_stamps(image_dir) except Exception as e: result["error"] = f"OBJ generation failed: {e}" log.error(" ERROR generating OBJ: %s", e) return result - # Template images always need volume chunks, so always go via NRRD. Non-template - # images with a usable obj normally take the lightweight OBJ-only path (Step 2a) - # and skip NRRD entirely -- but generate_mesh is an explicit request to run the - # NRRD-based mesh pipeline, so it forces the NRRD path too, for any image; - # mesh_from_obj then picks the mesh source within it (see Step 2b below). - use_nrrd_path = needs_precomputed and status["has_nrrd"] and ( - is_template_image or not has_usable_obj or generate_mesh - ) - - # Step 2a: Generate precomputed from OBJ (mesh-only) - if needs_precomputed and has_usable_obj and not use_nrrd_path: - try: - obj_path = os.path.join(image_dir, "volume_man.obj") - ng_dir = os.path.join(image_dir, "neuroglancer") - # Prefer this image's own volume.nrrd header for the physical voxel size -- - # matches the NRRD path's convention exactly (see convert_nrrd.detect_spacing), - # so an OBJ-path mesh sits in the same coordinate space as anything produced - # via the NRRD path (e.g. the template it's aligned to). Only falls back to - # the passed-in `resolution` (default: DEFAULT_RESOLUTION) when this image - # has no volume.nrrd of its own to read. - obj_resolution = resolution - if status["has_nrrd"] and _read_nrrd_voxel_size is not None: - try: - obj_resolution = _read_nrrd_voxel_size(os.path.join(image_dir, "volume.nrrd")) - except Exception as e: - log.warning(" [%s] Could not read volume.nrrd header for resolution, " - "falling back to %s: %s", vfb_id, resolution, e) - # status["has_obj_man_faces"] reflects classify_dir()'s PRE-run snapshot -- - # True only if the obj already existed (and had faces) before Step 1 ran, - # i.e. a pre-existing external obj (needs the Z,Y,X->X,Y,Z swap), never one - # generate_obj_from_swc() just built this run from a .swc. - write_precomputed(obj_path, ng_dir, resolution=obj_resolution, - swap_xz=status["has_obj_man_faces"]) - result["precomputed_generated"] = True - except Exception as e: - result["error"] = f"Precomputed generation failed: {e}" - log.error(" ERROR generating precomputed: %s", e) - - # Step 2b: Generate precomputed (with 0/ volume chunks) from NRRD - elif use_nrrd_path: - if _convert_nrrd is None: - result["error"] = "convert_nrrd module not available" - log.error(" ERROR: convert_nrrd module could not be imported") + # Step 2: build the dataset in the work dir + t0 = time.time() + build_root = os.path.join(work_dir, f"{vfb_id}-{template_id}") + out_dir = os.path.join(build_root, OUTPUT_NAME) + shutil.rmtree(build_root, ignore_errors=True) + os.makedirs(build_root) + obj_path = os.path.join(image_dir, "volume_man.obj") if have_obj else None + try: + if nrrd_path: + _convert_nrrd(nrrd_path=nrrd_path, output_dir=build_root, dataset_name=OUTPUT_NAME, + layer_type=lt, generate_mesh=(lt == "segmentation"), + mesh_obj_path=obj_path if lt == "segmentation" else None, + mask=mask, mesh_min_intensity=mesh_min_intensity, + mesh_max_intensity=mesh_max_intensity, mesh_percentile=mesh_percentile, + mesh_format=mesh_format, decimate_fraction=decimate_fraction, + max_simplification_error=max_simplification_error, + verbose=log.isEnabledFor(logging.DEBUG)) else: - try: - nrrd_path = os.path.join(image_dir, "volume.nrrd") - mesh_obj_path = (os.path.join(image_dir, "volume_man.obj") - if generate_mesh and mesh_from_obj and has_usable_obj - else None) - if mesh_obj_path: - log.info(" Generating neuroglancer/ (with 0/ chunks) from NRRD: %s, " - "mesh from volume_man.obj", nrrd_path) - else: - log.info(" Generating neuroglancer/ (with 0/ chunks) from NRRD: %s", nrrd_path) - # convert_nrrd writes to {output_dir}/{dataset_name}/, so passing - # image_dir + "neuroglancer" produces image_dir/neuroglancer/ with - # the 0/ chunk directory, mesh/, segment_properties/ all inside it. - _convert_nrrd( - nrrd_path=nrrd_path, - output_dir=image_dir, - dataset_name="neuroglancer", - merge_segments=merge_segments, - min_intensity=min_intensity, - max_intensity=max_intensity, - generate_mesh=generate_mesh, - mask=mask, - mesh_min_intensity=mesh_min_intensity, - mesh_max_intensity=mesh_max_intensity, - mesh_percentile=mesh_percentile, - mesh_format=mesh_format, - decimate_fraction=decimate_fraction, - max_simplification_error=max_simplification_error, - mesh_obj_path=mesh_obj_path, - # status["has_obj_man_faces"] is classify_dir()'s pre-run snapshot -- - # True only for a pre-existing external obj (needs the swap), never - # one generate_obj_from_swc() just built this run. - mesh_obj_swap_xz=bool(mesh_obj_path) and status["has_obj_man_faces"], - verbose=log.isEnabledFor(logging.DEBUG), - ) - result["precomputed_generated"] = True - except Exception as e: - result["error"] = f"NRRD precomputed generation failed: {e}" - log.error(" ERROR generating precomputed from NRRD: %s", e) - - if result["precomputed_generated"] and compress: - try: - mesh_compression.zip_neuroglancer_dir(ng_dir, verbose=log.isEnabledFor(logging.DEBUG)) - # Remove the uncompressed source now that it's safely inside the zip -- - # otherwise both copies linger on disk (see classify_dir(), which treats - # neuroglancer.zip alone as a complete, already-done output). - shutil.rmtree(ng_dir) - except Exception as e: - result["error"] = f"Zipping neuroglancer/ failed: {e}" - log.error(" ERROR zipping neuroglancer/: %s", e) - + write_mesh_only_precomputed(obj_path, out_dir, resolution=resolution) + _write_provenance(out_dir, vfb_id=vfb_id, template_id=template_id, category=category, + layer_type=lt, mesh_source=mesh_source, sources=status["sources"]) + + # Step 3: zip and move the one finished file into the image folder + if compress: + zip_path = mesh_compression.zip_neuroglancer_dir(out_dir, verbose=log.isEnabledFor(logging.DEBUG)) + _replace_into(zip_path, os.path.join(image_dir, OUTPUT_ZIP)) + else: + final = os.path.join(image_dir, OUTPUT_NAME) + shutil.rmtree(final, ignore_errors=True) + shutil.copytree(out_dir, final) + result["precomputed_generated"] = True + result["bytes"] = os.path.getsize(os.path.join(image_dir, OUTPUT_ZIP)) if compress else None + result["seconds"] = round(time.time() - t0, 1) + log.info(" [%s] wrote %s (%s, %.1f MB) in %.1fs", vfb_id, OUTPUT_ZIP if compress else OUTPUT_NAME, lt, + (result["bytes"] or 0) / 1e6, result["seconds"]) + except Exception as e: + result["error"] = f"Precomputed generation failed: {e}" + log.error(" ERROR generating precomputed: %s", e, exc_info=log.isEnabledFor(logging.DEBUG)) + finally: + shutil.rmtree(build_root, ignore_errors=True) return result # --------------------------------------------------------------------------- -# Main +# CLI # --------------------------------------------------------------------------- +def _order_targets(targets: list[tuple], template_order: list[str]) -> list[tuple]: + """Template groups in the requested order (then the rest); within a group the + template image itself first, then by id.""" + rank = {tid: i for i, tid in enumerate(template_order)} + return sorted(targets, key=lambda t: (rank.get(t[2], len(rank)), t[2], + 0 if t[1] == t[2] else 1, t[1])) + + def main(): parser = argparse.ArgumentParser( - description="VFB Jenkins Pipeline: generate volume_man.obj and neuroglancer precomputed data" - ) - input_group = parser.add_mutually_exclusive_group() - input_group.add_argument("--ids", nargs="+", - help="Specific VFB IDs to process") - input_group.add_argument("--ids-file", - help="File with VFB IDs (one per line)") - + description="VFB pipeline: precomputed.zip (Neuroglancer precomputed) for each image folder") + g = parser.add_mutually_exclusive_group() + g.add_argument("--ids", nargs="+", help="Specific VFB IDs to process") + g.add_argument("--ids-file", help="File with VFB IDs (one per line; '#' comments)") + g.add_argument("--use-kb", action="store_true", + help="Discover live images (production datasets) and their category from the KB") + g.add_argument("--targets-file", + help="TSV of image_dirvfb_idtemplate_idcategory (as --list-targets " + "writes it): one batch of a planned run, no KB access needed") + parser.add_argument("--list-targets", metavar="TSV", + help="Write the discovered targets (after --template filtering and ordering) " + "to this TSV and exit without converting anything") + parser.add_argument("--results", metavar="JSONL", + help="Append one JSON line per processed image (status, size, seconds, error)") parser.add_argument("--image-root", default=IMAGE_ROOT, - help="Root of VFB image data (default: /IMAGE_WRITE)") - parser.add_argument("--use-kb", action="store_true", - help="Query kb.virtualflybrain.org for live images instead of scanning the filesystem") + help="Directory that contains VFB/i/ (default: %(default)s)") + parser.add_argument("--work-dir", default=None, + help="Local scratch for building each dataset before its zip is moved into " + "the image folder (default: a temp dir). Needs room for one uncompressed " + "dataset (a full template-sized image volume is ~120 MB raw chunks).") parser.add_argument("--template", nargs="+", metavar="TEMPLATE_ID", - help="Only process image directories aligned to the given template(s), " - "given as the anatomical template individual's short_form " - "(e.g. VFB_00101567 for JRC2018Unisex). Applied to the KB template " - "node (not the VFBc_ channel) and to the filesystem directory name. " - "When omitted, all templates are processed in the order defined " - "by DEFAULT_TEMPLATE_ORDER (JRC2018U, then JRCVNC2018U), then the rest. " - "Within each template group, the template image itself " - "(vfb_id == template_id) is processed first.") - parser.add_argument("--resolution", type=float, nargs=3, - default=DEFAULT_RESOLUTION, - help="Fallback voxel resolution in um [x y z] (default: JRC2018U) for " - "the OBJ-only mesh path -- only used when an image directory has no " - "volume.nrrd of its own; when it does, that file's own header " - "spacing is used instead, to stay in the same coordinate space as " - "the NRRD path (see process_image()'s Step 2a).") + help="Only process images aligned to these template short_forms " + "(e.g. VFB_00101567), in this order. Required (except with " + "--targets-file): space is limited, so only alignments named here get a " + "precomputed.zip. The template image itself always goes first.") + parser.add_argument("--layer-type", choices=["auto", "image", "segmentation"], default="auto", + help="Override the per-image decision (default: auto = from the KB category)") + parser.add_argument("--resolution", type=float, nargs=3, default=DEFAULT_RESOLUTION, + help="Voxel size [x y z] in um for a mesh-only build of a folder with no " + "volume.nrrd (default: JRC2018U)") parser.add_argument("--force", action="store_true", - help="Regenerate even if output already exists") - parser.add_argument("--overwrite", action="store_true", - help="Delete existing neuroglancer/ folder and regenerate from scratch") - parser.add_argument("--merge-segments", action="store_true", - help="Merge all non-zero voxels into a single segment for NRRD conversion") - parser.add_argument("--min-intensity", type=int, default=None, - help="Minimum segment ID/intensity to keep in the STORED volume " - "(destructive, values below will be set to 0)") - parser.add_argument("--max-intensity", type=int, default=None, - help="Maximum segment ID/intensity to keep in the STORED volume " - "(destructive, values above will be set to 0)") - parser.add_argument("--generate-mesh", action="store_true", - help="Generate a mesh for the volume (default: off) -- most instances " - "already have a usable volume_man.obj and don't need one regenerated. " - "Forces the NRRD path (with 0/ volume chunks) even for a non-template " - "image that would otherwise take the lightweight OBJ-only path. By " - "default this runs marching cubes on the volume's external boundary; " - "pass --mesh-from-obj to source the mesh from an existing " - "volume_man.obj instead.") - parser.add_argument("--mesh-from-obj", action="store_true", - help="With --generate-mesh: if this image directory has a usable " - "volume_man.obj, use it as the mesh source instead of running " - "marching cubes on the NRRD volume -- --mask/--mesh-*/" - "--decimate-fraction/--max-simplification-error are ignored for " - "that image, since no marching-cubes step runs. Falls back to " - "marching-cubes NRRD generation, same as without this flag, when no " - "usable volume_man.obj exists. Volume chunks (0/) are still " - "generated from the NRRD either way -- only the mesh source changes.") + help="Regenerate even when precomputed.zip is current") + parser.add_argument("--no-compress", action="store_true", + help="Debug: leave an uncompressed precomputed/ folder in the image dir " + "instead of precomputed.zip") parser.add_argument("--mask", choices=["none", "otsu", "minmax"], default="none", - help="NRRD path, OPTIONAL. 'none' (default): no mask cleanup. 'otsu': " - "automatic threshold. 'minmax': explicit band -- also set " - "--mesh-percentile, OR --mesh-min-intensity/--mesh-max-intensity " - "(not both). Pick at most one. Known to backfire on dense data " - "(e.g. whole-brain templates) -- safest on sparse data.") - parser.add_argument("--mesh-min-intensity", type=int, default=None, - help="--mask minmax only: fixed band floor (stored volume untouched)") - parser.add_argument("--mesh-max-intensity", type=int, default=None, - help="--mask minmax only: fixed band ceiling (stored volume untouched)") - parser.add_argument("--mesh-percentile", type=float, default=None, - help="--mask minmax only: per-sample percentile-derived floor, instead of " - "a fixed --mesh-min-intensity/--mesh-max-intensity band") - parser.add_argument("--mesh-format", choices=["legacy", "multires_draco"], default="legacy", - help="NRRD path, pick at most one. 'legacy' (default): marching cubes, no " - "extra deps -- optionally add --decimate-fraction to simplify " - "afterward. 'multires_draco': CZI's multi-res Draco mesh instead " - "(extra deps: igneous/zmesh/DracoPy) -- tune with " - "--max-simplification-error. Can't combine legacy decimation with Draco.") + help="Marching-cubes path only (objects with no mesh): mask cleanup before " + "meshing. 'minmax' also needs --mesh-percentile or " + "--mesh-min-intensity/--mesh-max-intensity.") + parser.add_argument("--mesh-min-intensity", type=int, default=None) + parser.add_argument("--mesh-max-intensity", type=int, default=None) + parser.add_argument("--mesh-percentile", type=float, default=None) + parser.add_argument("--mesh-format", choices=["legacy", "multires_draco"], default="legacy") parser.add_argument("--decimate-fraction", type=float, default=0.0, - help="NRRD path, OPTIONAL, --mesh-format legacy only. pyfqmr decimation " - "target reduction (default: 0.0 = off; e.g. 0.7 removes ~70%% of " - "triangles). Safe on both sparse and dense data.") - parser.add_argument("--max-simplification-error", type=int, default=10, - help="NRRD path, --mesh-format multires_draco only. Draco simplification " - "error tolerance (default: 10) -- lower is gentler.") - parser.add_argument("--compress", action="store_true", - help="Zip each instance's neuroglancer/ folder into a single artifact " - "(default: off, leaves the raw uncompressed tree as-is). No " - "gzip/brotli choice anymore -- if set, this simply zips the whole " - "folder; see mesh_compression/zip_output.py.") - parser.add_argument("--dry-run", action="store_true", - help="Show what would be done without making changes") - parser.add_argument("--verbose", "-v", action="store_true", - help="Verbose output") + help="Marching-cubes path, legacy format: pyfqmr target reduction (0 = off)") + parser.add_argument("--max-simplification-error", type=int, default=10) + parser.add_argument("--dry-run", action="store_true", help="Show what would be done") + parser.add_argument("--verbose", "-v", action="store_true") args = parser.parse_args() - if _validate_mesh_params is not None: - try: - _validate_mesh_params(args.mask, args.mesh_min_intensity, args.mesh_max_intensity, - args.mesh_percentile, args.mesh_format, args.decimate_fraction, - args.generate_mesh, args.verbose) - except ValueError as e: - parser.error(str(e)) - - # Setup logging - level = logging.DEBUG if args.verbose else logging.INFO - logging.basicConfig( - level=level, - format="%(asctime)s [%(levelname)s] %(message)s", - datefmt="%Y-%m-%d %H:%M:%S", - ) + try: + _validate_mesh_params(args.mask, args.mesh_min_intensity, args.mesh_max_intensity, + args.mesh_percentile, args.mesh_format, args.decimate_fraction, + True, args.verbose) + except ValueError as e: + parser.error(str(e)) - vfb_data_dir = os.path.join(args.image_root, "VFB", "i") + logging.basicConfig(level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S") + if args.verbose: + log.setLevel(logging.DEBUG) # ours only -- cloud-volume's schema layer is very chatty at DEBUG + vfb_data_dir = os.path.join(args.image_root, "VFB", "i") if not os.path.isdir(vfb_data_dir): - log.error("VFB data directory not found: %s", vfb_data_dir) - log.error("Set --image-root to the directory that contains VFB/i/") + log.error("VFB data directory not found: %s (set --image-root to the dir containing VFB/i/)", + vfb_data_dir) sys.exit(1) - # Collect targets - if args.ids: + if not args.template and not args.targets_file: + parser.error("--template is required: name the template alignment(s) to convert (e.g. VFB_00101567)") + + # Collect (image_dir, vfb_id, template_id, category) + if args.ids or args.ids_file: + ids = args.ids or [l.strip() for l in open(args.ids_file) if l.strip() and not l.startswith("#")] targets = [] - for vfb_id in args.ids: - for d in find_image_dir(vfb_id, vfb_data_dir): - template_id = os.path.basename(d) - targets.append((d, vfb_id, template_id)) - if not find_image_dir(vfb_id, vfb_data_dir): + for vfb_id in ids: + dirs = find_image_dir(vfb_id, vfb_data_dir) + if not dirs: log.warning("No directories found for %s", vfb_id) - elif args.ids_file: + for d in dirs: + tid = os.path.basename(d) + targets.append((d, vfb_id, tid, CATEGORY_TEMPLATE if vfb_id == tid else None)) + elif args.targets_file: targets = [] - with open(args.ids_file) as f: + with open(args.targets_file) as f: for line in f: - vfb_id = line.strip() - if not vfb_id or vfb_id.startswith("#"): - continue - for d in find_image_dir(vfb_id, vfb_data_dir): - template_id = os.path.basename(d) - targets.append((d, vfb_id, template_id)) + if line.strip() and not line.startswith("#"): + d, v, t, c = line.rstrip("\n").split("\t") + targets.append((d, v, t, c or None)) elif args.use_kb: - log.info("Using KB to discover live image directories...") - targets = list(iter_kb_image_dirs(args.image_root, templates=args.template)) - log.info("Found %d live image directories from KB", len(targets)) + targets = list(iter_kb_template_dirs(args.image_root, args.template)) + seen = {t[0] for t in targets} + targets += [t for t in iter_kb_image_dirs(args.image_root, args.template) if t[0] not in seen] else: - # Scan all log.info("Scanning %s for image directories...", vfb_data_dir) - targets = list(iter_image_dirs(vfb_data_dir)) + targets = [(d, v, t, CATEGORY_TEMPLATE if v == t else None) for d, v, t in iter_image_dirs(vfb_data_dir)] log.info("Found %d image directories", len(targets)) - # Filter / order by template. Template images (vfb_id == template_id) are - # fetched directly from the KB and prepended so they always run first, - # regardless of how (or whether) the main query returned them. - if args.template: - wanted = set(args.template) - before = len(targets) - targets = [t for t in targets if t[2] in wanted] - log.info("Template filter %s: %d / %d directories match", - sorted(wanted), len(targets), before) - - order = {tid: i for i, tid in enumerate(args.template)} - - template_targets: list[tuple] = [] - if args.use_kb: - try: - template_targets = get_kb_template_image_dirs(args.template, args.image_root) - except Exception as e: - log.warning("Could not fetch template image folders from KB: %s", e) - - # Drop any main-query entries that point at the same folder as a - # template image, so we don't process the template directory twice. - template_dirs = {tt[0] for tt in template_targets} - if template_dirs: - targets = [t for t in targets if t[0] not in template_dirs] - - template_targets.sort(key=lambda t: order.get(t[2], len(order))) - targets.sort(key=lambda t: (order.get(t[2], len(order)), t[1])) - - for tt in template_targets: - log.info("Template image first: %s (%s)", tt[0], tt[1]) - targets = template_targets + targets - else: - # Default: order by template priority; within a group, template image - # first (vfb_id == template_id), then the rest by vfb_id. - priority = {tid: i for i, tid in enumerate(DEFAULT_TEMPLATE_ORDER)} - targets.sort(key=lambda t: (priority.get(t[2], len(priority)), - t[2], - 0 if t[1] == t[2] else 1, - t[1])) - + # Only the templates named with --template (space is limited: the operator says which alignments get a + # precomputed.zip) and never an excluded one. A --targets-file was already made by a --template run. + wanted = set(args.template) if args.template else None + before = len(targets) + targets = [t for t in targets if t[2] not in EXCLUDED_TEMPLATES and (wanted is None or t[2] in wanted)] + log.info("Template filter %s (excluding %s): %d / %d directories match", + sorted(wanted) if wanted else "targets file", sorted(EXCLUDED_TEMPLATES), len(targets), before) + targets = _order_targets(targets, args.template or []) if not targets: log.info("No image directories to process") return + if args.list_targets: + with open(args.list_targets, "w") as f: + for d, v, t, c in targets: + f.write(f"{d}\t{v}\t{t}\t{c or ''}\n") + log.info("Wrote %d targets to %s", len(targets), args.list_targets) + return - # Process - start = time.time() - stats = { - "total": len(targets), - "obj_generated": 0, - "precomputed_generated": 0, - "skipped": 0, - "errors": 0, - } + work_dir = args.work_dir or os.path.join(os.environ.get("TMPDIR", "/tmp"), "vfb-precomputed") + os.makedirs(work_dir, exist_ok=True) - for i, (image_dir, vfb_id, template_id) in enumerate(targets, 1): + start = time.time() + stats = {"total": len(targets), "obj_generated": 0, "precomputed_generated": 0, "skipped": 0, "errors": 0} + for i, (image_dir, vfb_id, template_id, category) in enumerate(targets, 1): if i % 500 == 0 or args.verbose: log.info("Progress: %d / %d", i, stats["total"]) + r = process_image(image_dir, vfb_id, template_id, category, work_dir, + force=args.force, dry_run=args.dry_run, resolution=args.resolution, + mask=args.mask, mesh_min_intensity=args.mesh_min_intensity, + mesh_max_intensity=args.mesh_max_intensity, mesh_percentile=args.mesh_percentile, + mesh_format=args.mesh_format, decimate_fraction=args.decimate_fraction, + max_simplification_error=args.max_simplification_error, + layer_type=args.layer_type, compress=not args.no_compress) + for k in ("obj_generated", "precomputed_generated", "skipped"): + stats[k] += bool(r[k]) + stats["errors"] += bool(r["error"]) + if args.results and not args.dry_run: + with open(args.results, "a") as f: + f.write(json.dumps(r, sort_keys=True) + "\n") - result = process_image( - image_dir, vfb_id, template_id, - force=args.force, overwrite=args.overwrite, - dry_run=args.dry_run, - merge_segments=args.merge_segments, - min_intensity=args.min_intensity, - max_intensity=args.max_intensity, - resolution=args.resolution, - generate_mesh=args.generate_mesh, - mesh_from_obj=args.mesh_from_obj, - mask=args.mask, - mesh_min_intensity=args.mesh_min_intensity, - mesh_max_intensity=args.mesh_max_intensity, - mesh_percentile=args.mesh_percentile, - mesh_format=args.mesh_format, - decimate_fraction=args.decimate_fraction, - max_simplification_error=args.max_simplification_error, - compress=args.compress, - ) - - if result["obj_generated"]: - stats["obj_generated"] += 1 - if result["precomputed_generated"]: - stats["precomputed_generated"] += 1 - if result["skipped"]: - stats["skipped"] += 1 - if result["error"]: - stats["errors"] += 1 - - elapsed = time.time() - start - - # Summary log.info("=" * 60) log.info("Pipeline Summary%s", " (DRY RUN)" if args.dry_run else "") log.info("=" * 60) @@ -1090,8 +794,7 @@ def main(): log.info(" Precomputed generated: %d", stats["precomputed_generated"]) log.info(" Skipped (up to date): %d", stats["skipped"]) log.info(" Errors: %d", stats["errors"]) - log.info(" Elapsed: %.1fs", elapsed) - + log.info(" Elapsed: %.1fs", time.time() - start) if stats["errors"] > 0: sys.exit(1) diff --git a/applications/virtual-fly-brain/frontend/src/utils/neuroglassStateConfig.js b/applications/virtual-fly-brain/frontend/src/utils/neuroglassStateConfig.js index 3d87e838..66dee26b 100644 --- a/applications/virtual-fly-brain/frontend/src/utils/neuroglassStateConfig.js +++ b/applications/virtual-fly-brain/frontend/src/utils/neuroglassStateConfig.js @@ -4,24 +4,29 @@ const DEFAULT_CONTRAST_RANGE = [0, 123]; const neuroglassLayerUrlCache = new Map(); // ─── Coordinate space shared by all VFB instances ──────────────────────────── +// The precomputed datasets are X, Y, Z with resolution and mesh vertices in +// nanometres (the precomputed spec's unit; the pipeline converts VFB's micron +// sources), so the shared space is 1 nm per unit on every axis and positions are +// in nm. JRC2018U is 1210 x 566 x 174 voxels of 0.519 x 0.519 x 1.0 um, so its +// centre is (314, 147, 87) um. Identity orientation = the anterior view (x right, +// y down), which is how VFB shows the brain. const SHARED_VIEWPORT = { dimensions: [ { name: 'x', scale: [1e-9, 'm'] }, - { name: 'y', scale: [5.189161e-10, 'm'] }, - { name: 'z', scale: [5.189161e-10, 'm'] }, + { name: 'y', scale: [1e-9, 'm'] }, + { name: 'z', scale: [1e-9, 'm'] }, ], - relativeDisplayScales: { x: 2, y: 2, z: 2 }, - position: [87.5, 280.5, 605.5], - crossSectionScale: 0.5, - projectionOrientation: [ - 0.03356223925948143, - -0.7611185908317566, - -0.049303606152534485, - -0.645864725112915, - ], - projectionScale: 1024, + position: [314000, 147000, 87000], + crossSectionScale: 500, + projectionOrientation: [0, 0, 0, 1], + projectionScale: 700000, }; +// Each image folder holds one precomputed.zip (info, chunks, mesh/) that +// Neuroglancer reads through its zip kvstore via HTTP Range requests: +// https://host/data/VFB/i/0010/1567/VFB_00101567/precomputed.zip|zip:|neuroglancer-precomputed: +const PRECOMPUTED_ZIP = 'precomputed.zip'; + export const NEUROGLASS_DATASOURCE = { protocol: import.meta.env.NEUROGLASS_DATA_PROTOCOL, baseUrl: import.meta.env.NEUROGLASS_DATA_BASE_URL, @@ -62,77 +67,28 @@ function isHttpUrl(baseUrl = '') { return baseUrl.startsWith('http://') || baseUrl.startsWith('https://'); } -async function buildNeuroglassLayerUrl(protocol, baseUrl, instanceId) { - let path = instanceId; +// Default template folder for an instance: the KB knows which template(s) an +// image is registered to; until that is wired through, JRC2018U is the one +// every brain image in VFB3 is shown on. +const DEFAULT_TEMPLATE_ID = 'VFB_00101567'; - // Check if the protocol is 'neuroglancer-precomputed' +async function buildNeuroglassLayerUrl(protocol, baseUrl, instancePath, templateId = DEFAULT_TEMPLATE_ID) { if (protocol === 'neuroglancer-precomputed') { if (isObjectStoreUrl(baseUrl)) { - return `${baseUrl}/${path}/|${protocol}:`; + return `${baseUrl}/${instancePath}/|${protocol}:`; } - if (isHttpUrl(baseUrl)) { - const url = `${baseUrl}/${path}`; - try { - // Fetch the folder contents of the URL - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch URL: ${url}`); - } - - // Check if the response is HTML - const contentType = response.headers.get('Content-Type'); - if (contentType && contentType.includes('text/html')) { - // Parse the HTML response - const html = await response.text(); - const folderNames = extractFolderNamesFromHtml(html); - - // Find the folder starting with VFB_ - const vfbFolder = folderNames.find((name) => name.startsWith('VFB_')); - - if (vfbFolder) { - // Check if the VFB_ folder contains a 'neuroglancer' folder - const vfbFolderUrl = `${url}/${vfbFolder}`; - const vfbResponse = await fetch(vfbFolderUrl); - if (!vfbResponse.ok) { - throw new Error(`Failed to fetch VFB folder: ${vfbFolderUrl}`); - } - - const vfbHtml = await vfbResponse.text(); - const vfbFolderNames = extractFolderNamesFromHtml(vfbHtml); - const neuroglancerFolder = vfbFolderNames.find( - (name) => name === 'neuroglancer/' - ); - - if (neuroglancerFolder) { - return `${vfbFolderUrl}${neuroglancerFolder}|${protocol}:`; - } - } - } else { - throw new Error(`Unexpected Content-Type: ${contentType}`); - } - } catch (error) { - console.error(`[buildNeuroglassLayerUrl] Error: ${error.message}`); - } + // No directory listing round-trips: the layout is fixed, one zip per image folder. + return `${baseUrl}/${instancePath}${templateId}/${PRECOMPUTED_ZIP}|zip:|${protocol}:`; } - return `${baseUrl}/${path}/|${protocol}:`; + return `${baseUrl}/${instancePath}/|${protocol}:`; } if (protocol === 'gs' || protocol === 'n5') { - return `${baseUrl}/${path}/|${protocol}:`; + return `${baseUrl}/${instancePath}/|${protocol}:`; } } -function extractFolderNamesFromHtml(html) { - const parser = new DOMParser(); - const doc = parser.parseFromString(html, 'text/html'); - const links = doc.querySelectorAll('a'); // Select all tags - const folderNames = Array.from(links) - .map((link) => link.textContent.trim()) // Extract text content - .filter((name) => name && !name.startsWith('..')); // Exclude parent directory links - return folderNames; -} - // Fixed GLSL shader template : Only shaderControls.color and layer.opacity change per instance. export const LAYER_SHADER = [ '#uicontrol invlerp contrast', @@ -209,8 +165,12 @@ function normalizeContrast(inst) { async function buildSingleInstanceLayer(inst) { const source = await NEUROGLASS_DATASOURCE.buildUrl(inst.metadata.Id); + // The pipeline writes templates and expression patterns as image layers + // (intensities) and neurons/clones/domains as segmentation layers (segment 1 + // + mesh). 'auto' lets Neuroglancer pick the layer type from the source's + // info; the image-only fields are ignored on a segmentation and vice versa. const layer = { - type: 'image', + type: 'auto', source: source, tab: 'rendering', opacity: alphaToOpacity(inst.color?.a), @@ -222,6 +182,9 @@ async function buildSingleInstanceLayer(inst) { }, volumeRenderingDepthSamples: 256, volumeRendering: 'on', + // segmentation layers: show the one segment, in the instance colour + segments: ['1'], + segmentDefaultColor: colorToHex(inst.color), name: inst.metadata.Id, };