From 39e9cd4474a866ef585f28e5c5f983d3ef09db88 Mon Sep 17 00:00:00 2001 From: Eric Trautman Date: Tue, 1 Dec 2026 07:14:58 -0500 Subject: [PATCH 1/5] first draft of incorporating SOFIMA stitch fix data into the import process --- .../client/multisem/ImportSofimaClient.java | 33 +- .../client/multisem/SofimaStitchFix.java | 341 ++++++++++++++++++ .../client/parameter/SofimaParameters.java | 45 ++- 3 files changed, 407 insertions(+), 12 deletions(-) create mode 100644 render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/ImportSofimaClient.java b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/ImportSofimaClient.java index a93cf0992..f1d63ad87 100644 --- a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/ImportSofimaClient.java +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/ImportSofimaClient.java @@ -48,6 +48,11 @@ * The modified tile specs are written to a target stack named by appending {@code --targetStackSuffix} to the source * stack name (the stack is derived from the source if it does not yet exist), and that target stack is completed once * all layers have been saved. + *

+ * If {@code --stitchFixUri} is given, the layers that SOFIMA restitched for this slab (see {@link SofimaStitchFix}) + * have a transform of each tile replaced before the displacement field is appended. The fix is applied to tiles + * read from the unchanged source stack, so the field's offset still comes from the original stack bounds, which is + * what the field was computed on. * * @author Michael Innerberger */ @@ -131,13 +136,26 @@ public void addDisplacementField() throws Exception { throw new IllegalArgumentException("Failed to process SOFIMA field at " + fieldUri, e); } + final List zValues = renderClient.getStackZValues(params.stack); + + // Load and check any stitch fixes before the target stack is touched, so a mismatch fails up front. + // Fixed layers are numbered from the stack's minZ, like the field's z-slices. + final SofimaStitchFix stitchFix; + if (params.sofima.hasStitchFixUri()) { + stitchFix = SofimaStitchFix.load(params.sofima.stitchFixUri, + SofimaParameters.getSlabForStack(params.stack), + offset[2]); + stitchFix.validateZValues(zValues); + } else { + stitchFix = null; + } + // Set up the target stack. The suffix is validated as non-empty, so the target stack // is always distinct from the source stack and is always derived from it. final String targetStack = params.sofima.getTargetStackId(sourceStackMetaData.getStackId()).getStack(); renderClient.setupDerivedStack(sourceStackMetaData, targetStack); - // Get and process all z values - final List zValues = renderClient.getStackZValues(params.stack); + // Process all z values LOG.info("addDisplacementField: processing {} layers with {} threads", zValues.size(), params.numThreads); // One pool, reused for the tiles of each layer in turn (see addFieldToLayer for why tiles and not layers) @@ -146,7 +164,7 @@ public void addDisplacementField() throws Exception { // Derive the slice from z itself rather than from the running layer index, so that a gap in the // stack's z values does not shift every later layer onto the wrong slice. final long fieldZIndex = Math.round(z - offset[2]); - addFieldToLayer(z, buildDataString(fieldUri, fieldZIndex, scale, offset), targetStack, pool); + addFieldToLayer(z, buildDataString(fieldUri, fieldZIndex, scale, offset), stitchFix, targetStack, pool); } } @@ -158,19 +176,26 @@ public void addDisplacementField() throws Exception { } /** - * Adds the transform to every tile spec of one layer and saves them. Deriving a bounding box evaluates the + * Applies the layer's stitch fix (if any), adds the transform to every tile spec of one layer and saves them. Deriving a bounding box evaluates the * transform over the tile's footprint, so this is where the (blocking) field chunk reads happen. Tiles are the * natural axis to parallelize: they cover disjoint parts of the field, so concurrent tiles load disjoint chunks * and the round-trip latency of those reads overlaps. */ private void addFieldToLayer(final Double z, final String dataString, + final SofimaStitchFix stitchFix, final String targetStack, final ForkJoinPool pool) throws IOException { final ResolvedTileSpecCollection tileSpecs = renderClient.getResolvedTiles(params.stack, z); + // Replace the restitched transforms first (cheap, and checked for all tiles before any is changed), so + // that the bounding boxes below are derived once from the final transform lists. + if ((stitchFix != null) && stitchFix.hasFixForZ(z)) { + stitchFix.apply(z, tileSpecs); + } + // Run the parallel stream inside the given pool. Balances the load internally pool.invoke(ForkJoinTask.adapt(() -> tileSpecs.getTileSpecs().parallelStream().forEach(tileSpec -> { final LeafTransformSpec transformSpec = new LeafTransformSpec(DisplacementFieldTransform.class.getName(), dataString); diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java new file mode 100644 index 000000000..5f3c0ae30 --- /dev/null +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java @@ -0,0 +1,341 @@ +package org.janelia.render.client.multisem; + +import com.fasterxml.jackson.databind.JsonNode; +import com.google.cloud.storage.BlobId; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; + +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import org.janelia.alignment.json.JsonUtils; +import org.janelia.alignment.spec.LeafTransformSpec; +import org.janelia.alignment.spec.ListTransformSpec; +import org.janelia.alignment.spec.ResolvedTileSpecCollection; +import org.janelia.alignment.spec.TileSpec; +import org.janelia.alignment.spec.TransformSpec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The SOFIMA stitch fixes for one slab: restitched layers whose tiles get a replacement for one transform in their + * transform list (for multi-SEM, the {@code AffineModel2D} after the {@code ExponentialFunctionOffsetTransform} + * becomes a tile-local {@code DisplacementFieldTransform} followed by a translation). + *

+ * The fixes live under a base URI holding a {@code manifest.json} that lists every fixed layer as + * {@code { "layer": "w61_s077_r00_layer10", "slab": "w61_s077_r00", "layer_z_0based": 10, "render_z_1based": 11 }}, + * and one {@code /transforms.json} per layer that maps each tile's mipmap level 0 image URL to the + * replacement spec list. + *

+ * A layer's z is derived like the SOFIMA field's z-slice index: {@code layer_z_0based} counts from the stack's + * {@code minZ}. Everything about a fix is checked before it is applied (layer z, the transform being replaced and + * the one before it, and a one-to-one match of tiles and mapping entries), so a mismatch fails the import rather + * than leaving a partly fixed layer. + */ +public class SofimaStitchFix { + + /** Replacement spec lists for one layer, keyed by tile image URL, plus where they go in the transform list. */ + private record LayerFix(String layerName, + int replacedIndex, + String replacedClassName, + String precedingClassName, + Map> imageUrlToSpecs) { + } + + private final String slab; + private final Map zToLayerFix; + + private SofimaStitchFix(final String slab, + final Map zToLayerFix) { + this.slab = slab; + this.zToLayerFix = zToLayerFix; + } + + /** + * Loads all stitch fixes for one slab. + * + * @param stitchFixUri base URI holding manifest.json and one directory per fixed layer + * (gs://, file:// or a plain local path). + * @param slab slab name as it appears in the manifest (e.g. w61_s077_r00). + * @param stackMinZ minimum z of the source stack, which layer_z_0based counts from. + * + * @return the fixes for the slab (empty if the manifest lists none for it). + * + * @throws IllegalArgumentException + * if the manifest or a layer's transforms.json cannot be read or is inconsistent. + */ + public static SofimaStitchFix load(final String stitchFixUri, + final String slab, + final double stackMinZ) + throws IllegalArgumentException { + + final String baseUri = stitchFixUri.replaceAll("/+$", ""); + final String manifestUri = baseUri + "/manifest.json"; + final JsonNode manifest = readJson(manifestUri); + + final Map zToLayerFix = new TreeMap<>(); + for (final JsonNode layer : requiredNode(manifest, "layers", manifestUri)) { + if (! slab.equals(requiredText(layer, "slab", manifestUri))) { + continue; + } + + final String layerName = requiredText(layer, "layer", manifestUri); + final int layerZ0 = requiredInt(layer, "layer_z_0based", manifestUri); + final double z = stackMinZ + layerZ0; + checkRenderZ(layer, z, layerName, manifestUri); + + // derive the location from the base uri (rather than using the manifest's absolute transforms_json) + // so that a copy of the fixes in another location works the same way + final String transformsUri = baseUri + "/" + layerName + "/transforms.json"; + final LayerFix layerFix = loadLayerFix(transformsUri, layerName, slab, layerZ0); + + if (zToLayerFix.put(z, layerFix) != null) { + throw new IllegalArgumentException( + manifestUri + " lists more than one layer for slab " + slab + " z " + z); + } + } + + LOG.info("load: found {} stitch fix layer(s) for slab {} in {}", zToLayerFix.size(), slab, manifestUri); + + return new SofimaStitchFix(slab, zToLayerFix); + } + + /** @return true if the layer with the specified z has a stitch fix. */ + public boolean hasFixForZ(final Double z) { + return zToLayerFix.containsKey(z); + } + + /** + * Checks that every fixed layer is a layer of the stack, so a mismatch fails before any stack is touched. + * + * @throws IllegalArgumentException + * if a fixed layer's z is not one of the specified stack z values. + */ + public void validateZValues(final Collection stackZValues) + throws IllegalArgumentException { + final Set missingZValues = new HashSet<>(zToLayerFix.keySet()); + stackZValues.forEach(missingZValues::remove); + if (! missingZValues.isEmpty()) { + throw new IllegalArgumentException( + "stitch fix layer z values " + missingZValues + " for slab " + slab + + " are not in the stack"); + } + } + + /** + * Replaces the fixed transform of every tile in the specified layer. + * All tiles are checked before any is changed. + * + * @throws IllegalArgumentException + * if the layer has no fix, a tile has no replacement, a replacement has no tile, or a tile's + * transform list does not hold the expected transforms. + */ + public void apply(final Double z, + final ResolvedTileSpecCollection tileSpecs) + throws IllegalArgumentException { + + final LayerFix layerFix = zToLayerFix.get(z); + if (layerFix == null) { + throw new IllegalArgumentException("slab " + slab + " has no stitch fix for z " + z); + } + + // match tiles to mapping entries first, so that a bad layer is rejected before any tile is changed + final Map> tileToSpecs = new HashMap<>(); + final List problems = new ArrayList<>(); + final Set unusedImageUrls = new HashSet<>(layerFix.imageUrlToSpecs().keySet()); + for (final TileSpec tileSpec : tileSpecs.getTileSpecs()) { + final String imageUrl = tileSpec.getTileImageUrl(); + final List replacementSpecs = layerFix.imageUrlToSpecs().get(imageUrl); + if (replacementSpecs == null) { + problems.add("tile " + tileSpec.getTileId() + " (" + imageUrl + ") has no replacement"); + continue; + } + unusedImageUrls.remove(imageUrl); + + final String transformProblem = findTransformProblem(tileSpec, layerFix); + if (transformProblem != null) { + problems.add(transformProblem); + continue; + } + tileToSpecs.put(tileSpec, replacementSpecs); + } + unusedImageUrls.forEach(imageUrl -> problems.add("replacement for " + imageUrl + " matches no tile")); + + if (! problems.isEmpty()) { + throw new IllegalArgumentException( + "cannot apply stitch fix " + layerFix.layerName() + " to z " + z + ", found " + problems.size() + + " problem(s), the first are: " + problems.subList(0, Math.min(5, problems.size()))); + } + + tileToSpecs.forEach((tileSpec, replacementSpecs) -> replaceTransform(tileSpec, + layerFix.replacedIndex(), + replacementSpecs)); + + LOG.info("apply: replaced transform {} of {} tiles in z {} with stitch fix {}", + layerFix.replacedIndex(), tileToSpecs.size(), z, layerFix.layerName()); + } + + /** @return a description of why the tile's transforms can't take the fix, or null if they can. */ + private static String findTransformProblem(final TileSpec tileSpec, + final LayerFix layerFix) { + final ListTransformSpec transforms = tileSpec.getTransforms(); + final int index = layerFix.replacedIndex(); + if ((transforms == null) || (transforms.size() <= index)) { + return "tile " + tileSpec.getTileId() + " has fewer than " + (index + 1) + " transforms"; + } + if (isNotA(transforms.getSpec(index), layerFix.replacedClassName())) { + return "tile " + tileSpec.getTileId() + " transform " + index + " is not a " + + layerFix.replacedClassName(); + } + if ((layerFix.precedingClassName() != null) && + ((index == 0) || isNotA(transforms.getSpec(index - 1), layerFix.precedingClassName()))) { + return "tile " + tileSpec.getTileId() + " transform " + (index - 1) + " is not a " + + layerFix.precedingClassName(); + } + return null; + } + + /** @return true unless the spec is a leaf for the specified transform class. */ + private static boolean isNotA(final TransformSpec spec, + final String className) { + return ! ((spec instanceof LeafTransformSpec) && className.equals(((LeafTransformSpec) spec).getClassName())); + } + + private static void replaceTransform(final TileSpec tileSpec, + final int index, + final List replacementSpecs) { + final ListTransformSpec transforms = tileSpec.getTransforms(); + final List specs = transforms.toUtilList(); + final ListTransformSpec fixedTransforms = new ListTransformSpec(transforms.getId(), transforms.getMetaData()); + fixedTransforms.addAllSpecs(specs.subList(0, index)); + fixedTransforms.addAllSpecs(replacementSpecs); + fixedTransforms.addAllSpecs(specs.subList(index + 1, specs.size())); + tileSpec.setTransforms(fixedTransforms); + } + + private static LayerFix loadLayerFix(final String transformsUri, + final String layerName, + final String slab, + final int layerZ0) + throws IllegalArgumentException { + + final JsonNode layerJson = readJson(transformsUri); + + // the per-layer file repeats the manifest's identifying values, so check that they agree + final String fileSlab = requiredText(layerJson, "slab", transformsUri); + final int fileLayerZ0 = requiredInt(layerJson, "layer_z_0based", transformsUri); + if ((! slab.equals(fileSlab)) || (layerZ0 != fileLayerZ0)) { + throw new IllegalArgumentException( + transformsUri + " is for slab " + fileSlab + " layer_z_0based " + fileLayerZ0 + + " but the manifest lists it for slab " + slab + " layer_z_0based " + layerZ0); + } + + final int replacedIndex = requiredInt(layerJson, "replaces_transform_index", transformsUri); + final String replacedClassName = requiredText(layerJson, "replaces_transform_class", transformsUri); + final JsonNode precedingNode = layerJson.get("keep_preceding_transform"); + final String precedingClassName = (precedingNode == null) || precedingNode.isNull() ? + null : precedingNode.asText(); + + final Map> imageUrlToSpecs = new HashMap<>(); + final JsonNode tiles = requiredNode(layerJson, "tiles", transformsUri); + for (final Iterator> it = tiles.fields(); it.hasNext(); ) { + final Map.Entry entry = it.next(); + final JsonNode specList = requiredNode(entry.getValue(), "specList", transformsUri); + try { + final TransformSpec[] specs = JsonUtils.MAPPER.treeToValue(specList, TransformSpec[].class); + imageUrlToSpecs.put(entry.getKey(), Arrays.asList(specs)); + } catch (final IOException e) { + throw new IllegalArgumentException( + "failed to parse specList for " + entry.getKey() + " in " + transformsUri, e); + } + } + + final JsonNode numTiles = layerJson.get("num_tiles"); + if ((numTiles != null) && (numTiles.asInt() != imageUrlToSpecs.size())) { + throw new IllegalArgumentException( + transformsUri + " has num_tiles " + numTiles.asInt() + " but maps " + + imageUrlToSpecs.size() + " tiles"); + } + + LOG.info("loadLayerFix: loaded {} tile replacement(s) from {}", imageUrlToSpecs.size(), transformsUri); + + return new LayerFix(layerName, replacedIndex, replacedClassName, precedingClassName, imageUrlToSpecs); + } + + /** + * Cross-checks the derived z against the manifest's render_z_1based (if present), which assumes a stack + * starting at z 1. A mismatch means the stack does not start where the fix producer assumed. + */ + private static void checkRenderZ(final JsonNode layer, + final double z, + final String layerName, + final String manifestUri) { + final JsonNode renderZ = layer.get("render_z_1based"); + if ((renderZ != null) && (renderZ.asDouble() != z)) { + throw new IllegalArgumentException( + manifestUri + " lists render_z_1based " + renderZ.asDouble() + " for " + layerName + + " but layer_z_0based plus the stack's minZ gives z " + z); + } + } + + private static JsonNode requiredNode(final JsonNode parent, + final String name, + final String sourceUri) { + final JsonNode node = parent.get(name); + if ((node == null) || node.isNull()) { + throw new IllegalArgumentException("missing '" + name + "' in " + sourceUri); + } + return node; + } + + private static String requiredText(final JsonNode parent, + final String name, + final String sourceUri) { + return requiredNode(parent, name, sourceUri).asText(); + } + + private static int requiredInt(final JsonNode parent, + final String name, + final String sourceUri) { + final JsonNode node = requiredNode(parent, name, sourceUri); + if (! node.canConvertToInt()) { + throw new IllegalArgumentException("'" + name + "' in " + sourceUri + " is not an integer"); + } + return node.asInt(); + } + + /** + * Reads JSON from a gs:// URI (anonymously, like {@link org.janelia.alignment.transform.DisplacementFieldTransform} + * reads its fields), a file:// URI, or a plain local path. + */ + private static JsonNode readJson(final String uri) + throws IllegalArgumentException { + try { + final byte[] bytes; + if (uri.startsWith("gs://")) { + final Storage storage = StorageOptions.getUnauthenticatedInstance().getService(); + bytes = storage.readAllBytes(BlobId.fromGsUtilUri(uri)); + } else { + final String path = uri.startsWith("file://") ? URI.create(uri).getPath() : uri; + bytes = Files.readAllBytes(Paths.get(path)); + } + return JsonUtils.MAPPER.readTree(bytes); + } catch (final Exception e) { + throw new IllegalArgumentException("failed to read " + uri, e); + } + } + + private static final Logger LOG = LoggerFactory.getLogger(SofimaStitchFix.class); +} diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/parameter/SofimaParameters.java b/render-ws-java-client/src/main/java/org/janelia/render/client/parameter/SofimaParameters.java index 47ddc59e9..df92aa648 100644 --- a/render-ws-java-client/src/main/java/org/janelia/render/client/parameter/SofimaParameters.java +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/parameter/SofimaParameters.java @@ -38,16 +38,27 @@ public class SofimaParameters "(e.g. _sofima)") public String targetStackSuffix; + @Parameter( + names = "--stitchFixUri", + description = "URI of the directory containing SOFIMA stitch fixes for restitched layers: a " + + "manifest.json listing the fixed layers and one _layer/transforms.json per " + + "layer (e.g. gs://janelia-spark-test/SOFIMA/stitch_fix_261130). Each tile in a " + + "fixed layer has a transform replaced before the displacement field is added. " + + "Omit if there are no stitch fixes") + public String stitchFixUri; + public SofimaParameters() { - this(null, null, null); + this(null, null, null, null); } public SofimaParameters(final String sofimaFieldUri, final Double scale, - final String targetStackSuffix) { + final String targetStackSuffix, + final String stitchFixUri) { this.sofimaFieldUri = sofimaFieldUri; this.scale = scale; this.targetStackSuffix = targetStackSuffix; + this.stitchFixUri = stitchFixUri; } public Double getScale() { @@ -73,16 +84,33 @@ public StackId getTargetStackId(final StackId sourceStackId) { */ public String getFieldUriForStack(final String stack) throws IllegalArgumentException { + // trim any trailing slashes so that a configured uri with or without one works the same way + return sofimaFieldUri.replaceAll("/+$", "") + "/" + getSlabForStack(stack); + } + + /** @return true if stitch fixes should be applied before the displacement field is added. */ + public boolean hasStitchFixUri() { + return (stitchFixUri != null) && (! stitchFixUri.trim().isEmpty()); + } + + /** + * @param stack name of the source stack (e.g. w61_s070_r00_gc_icc_par_asoi_3d). + * + * @return the slab name at the start of the specified stack name (e.g. w61_s070_r00). + * + * @throws IllegalArgumentException + * if the stack name does not start with a slab name. + */ + public static String getSlabForStack(final String stack) + throws IllegalArgumentException { final Matcher matcher = SLAB_PATTERN.matcher(stack); if (! matcher.find()) { throw new IllegalArgumentException( - "cannot derive a SOFIMA field container from stack '" + stack + - "' because the stack name does not start with a slab name (e.g. w61_s070_r00)"); + "cannot derive a slab name from stack '" + stack + + "' because the stack name does not start with one (e.g. w61_s070_r00)"); } - - // trim any trailing slashes so that a configured uri with or without one works the same way - return sofimaFieldUri.replaceAll("/+$", "") + "/" + matcher.group(1); + return matcher.group(1); } /** @@ -109,6 +137,7 @@ public void validate() @Override public String toString() { return "{sofimaFieldUri='" + sofimaFieldUri + "', scale=" + scale + - ", targetStackSuffix='" + targetStackSuffix + "'}"; + ", targetStackSuffix='" + targetStackSuffix + + "', stitchFixUri='" + stitchFixUri + "'}"; } } From 57b3a2643b6cfe8ec86d864a72cc343e0883923a Mon Sep 17 00:00:00 2001 From: Eric Trautman Date: Tue, 1 Dec 2026 13:47:29 -0500 Subject: [PATCH 2/5] Change SOFIMA stitch fix process to replace AffineModel2D transform and any StageCreepCorrectionTransform (if one exists). The stitch fix data was not built with any creep correction transform. --- .../client/multisem/SofimaStitchFix.java | 114 +++++++++++------- 1 file changed, 72 insertions(+), 42 deletions(-) diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java index 5f3c0ae30..37f520672 100644 --- a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java @@ -26,13 +26,17 @@ import org.janelia.alignment.spec.ResolvedTileSpecCollection; import org.janelia.alignment.spec.TileSpec; import org.janelia.alignment.spec.TransformSpec; +import org.janelia.alignment.transform.StageCreepCorrectionTransform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The SOFIMA stitch fixes for one slab: restitched layers whose tiles get a replacement for one transform in their - * transform list (for multi-SEM, the {@code AffineModel2D} after the {@code ExponentialFunctionOffsetTransform} - * becomes a tile-local {@code DisplacementFieldTransform} followed by a translation). + * transform list. For multi-SEM, a tile's transforms are {@code [ExponentialFunctionOffsetTransform, + * AffineModel2D]}, or in early layers {@code [ExponentialFunctionOffsetTransform, StageCreepCorrectionTransform, + * AffineModel2D]}. Everything after the first transform is replaced by a tile-local + * {@code DisplacementFieldTransform} followed by a translation. The stage creep correction goes too, because the + * SOFIMA restitching worked on tiles with only the first transform applied, so its field already accounts for creep. *

* The fixes live under a base URI holding a {@code manifest.json} that lists every fixed layer as * {@code { "layer": "w61_s077_r00_layer10", "slab": "w61_s077_r00", "layer_z_0based": 10, "render_z_1based": 11 }}, @@ -40,17 +44,22 @@ * replacement spec list. *

* A layer's z is derived like the SOFIMA field's z-slice index: {@code layer_z_0based} counts from the stack's - * {@code minZ}. Everything about a fix is checked before it is applied (layer z, the transform being replaced and - * the one before it, and a one-to-one match of tiles and mapping entries), so a mismatch fails the import rather - * than leaving a partly fixed layer. + * {@code minZ}. Everything about a fix is checked before it is applied (layer z, each tile's transform layout, and a + * one-to-one match of tiles and mapping entries), so a mismatch fails the import rather than leaving a partly + * fixed layer. + *

+ * The layout is checked by class rather than with the {@code replaces_transform_index} in transforms.json, since + * that index assumes there is no stage creep correction transform. */ public class SofimaStitchFix { - /** Replacement spec lists for one layer, keyed by tile image URL, plus where they go in the transform list. */ + /** + * Replacement spec lists for one layer, keyed by tile image URL, plus the classes of the transform that is kept + * (the tile's first) and of the transform that must be its last (replaced along with any creep correction). + */ private record LayerFix(String layerName, - int replacedIndex, String replacedClassName, - String precedingClassName, + String firstClassName, Map> imageUrlToSpecs) { } @@ -164,9 +173,10 @@ public void apply(final Double z, } unusedImageUrls.remove(imageUrl); - final String transformProblem = findTransformProblem(tileSpec, layerFix); - if (transformProblem != null) { - problems.add(transformProblem); + if (! hasExpectedLayout(tileSpec.getTransforms(), layerFix)) { + problems.add("tile " + tileSpec.getTileId() + " transforms " + describe(tileSpec.getTransforms()) + + " are not [" + layerFix.firstClassName() + ", (" + STAGE_CREEP_CLASS_NAME + ")*, " + + layerFix.replacedClassName() + "]"); continue; } tileToSpecs.put(tileSpec, replacementSpecs); @@ -179,32 +189,53 @@ public void apply(final Double z, " problem(s), the first are: " + problems.subList(0, Math.min(5, problems.size()))); } - tileToSpecs.forEach((tileSpec, replacementSpecs) -> replaceTransform(tileSpec, - layerFix.replacedIndex(), - replacementSpecs)); + // count the tiles that lose a creep correction, so the log shows how many had one + int creepCorrectedTileCount = 0; + for (final Map.Entry> entry : tileToSpecs.entrySet()) { + final TileSpec tileSpec = entry.getKey(); + if (tileSpec.getTransforms().size() > 2) { + creepCorrectedTileCount++; + } + replaceAllButFirstTransform(tileSpec, entry.getValue()); + } - LOG.info("apply: replaced transform {} of {} tiles in z {} with stitch fix {}", - layerFix.replacedIndex(), tileToSpecs.size(), z, layerFix.layerName()); + LOG.info("apply: replaced all but the first transform of {} tiles ({} with stage creep correction) " + + "in z {} with stitch fix {}", + tileToSpecs.size(), creepCorrectedTileCount, z, layerFix.layerName()); } - /** @return a description of why the tile's transforms can't take the fix, or null if they can. */ - private static String findTransformProblem(final TileSpec tileSpec, - final LayerFix layerFix) { - final ListTransformSpec transforms = tileSpec.getTransforms(); - final int index = layerFix.replacedIndex(); - if ((transforms == null) || (transforms.size() <= index)) { - return "tile " + tileSpec.getTileId() + " has fewer than " + (index + 1) + " transforms"; + /** + * @return true if the transforms are the kept first transform, any number of stage creep corrections, and the + * replaced transform last. + */ + private static boolean hasExpectedLayout(final ListTransformSpec transforms, + final LayerFix layerFix) { + if ((transforms == null) || (transforms.size() < 2)) { + return false; + } + final int lastIndex = transforms.size() - 1; + if (isNotA(transforms.getSpec(0), layerFix.firstClassName()) || + isNotA(transforms.getSpec(lastIndex), layerFix.replacedClassName())) { + return false; } - if (isNotA(transforms.getSpec(index), layerFix.replacedClassName())) { - return "tile " + tileSpec.getTileId() + " transform " + index + " is not a " + - layerFix.replacedClassName(); + for (int i = 1; i < lastIndex; i++) { + if (isNotA(transforms.getSpec(i), STAGE_CREEP_CLASS_NAME)) { + return false; + } } - if ((layerFix.precedingClassName() != null) && - ((index == 0) || isNotA(transforms.getSpec(index - 1), layerFix.precedingClassName()))) { - return "tile " + tileSpec.getTileId() + " transform " + (index - 1) + " is not a " + - layerFix.precedingClassName(); + return true; + } + + /** @return the class names of the transforms (or kind of spec for a non-leaf), e.g. for error messages. */ + private static String describe(final ListTransformSpec transforms) { + if (transforms == null) { + return "[]"; } - return null; + return transforms.toUtilList().stream() + .map(spec -> (spec instanceof LeafTransformSpec) ? + ((LeafTransformSpec) spec).getClassName() : spec.getClass().getSimpleName()) + .toList() + .toString(); } /** @return true unless the spec is a leaf for the specified transform class. */ @@ -213,15 +244,12 @@ private static boolean isNotA(final TransformSpec spec, return ! ((spec instanceof LeafTransformSpec) && className.equals(((LeafTransformSpec) spec).getClassName())); } - private static void replaceTransform(final TileSpec tileSpec, - final int index, - final List replacementSpecs) { + private static void replaceAllButFirstTransform(final TileSpec tileSpec, + final List replacementSpecs) { final ListTransformSpec transforms = tileSpec.getTransforms(); - final List specs = transforms.toUtilList(); final ListTransformSpec fixedTransforms = new ListTransformSpec(transforms.getId(), transforms.getMetaData()); - fixedTransforms.addAllSpecs(specs.subList(0, index)); + fixedTransforms.addSpec(transforms.getSpec(0)); fixedTransforms.addAllSpecs(replacementSpecs); - fixedTransforms.addAllSpecs(specs.subList(index + 1, specs.size())); tileSpec.setTransforms(fixedTransforms); } @@ -242,11 +270,10 @@ private static LayerFix loadLayerFix(final String transformsUri, " but the manifest lists it for slab " + slab + " layer_z_0based " + layerZ0); } - final int replacedIndex = requiredInt(layerJson, "replaces_transform_index", transformsUri); + // replaces_transform_index is not used (see class comment), and keep_preceding_transform names the kept + // first transform, which is right before the replaced one only for tiles without creep correction final String replacedClassName = requiredText(layerJson, "replaces_transform_class", transformsUri); - final JsonNode precedingNode = layerJson.get("keep_preceding_transform"); - final String precedingClassName = (precedingNode == null) || precedingNode.isNull() ? - null : precedingNode.asText(); + final String firstClassName = requiredText(layerJson, "keep_preceding_transform", transformsUri); final Map> imageUrlToSpecs = new HashMap<>(); final JsonNode tiles = requiredNode(layerJson, "tiles", transformsUri); @@ -271,7 +298,7 @@ private static LayerFix loadLayerFix(final String transformsUri, LOG.info("loadLayerFix: loaded {} tile replacement(s) from {}", imageUrlToSpecs.size(), transformsUri); - return new LayerFix(layerName, replacedIndex, replacedClassName, precedingClassName, imageUrlToSpecs); + return new LayerFix(layerName, replacedClassName, firstClassName, imageUrlToSpecs); } /** @@ -337,5 +364,8 @@ private static JsonNode readJson(final String uri) } } + /** Stage creep correction is replaced along with the affine, since the restitching did not apply it. */ + private static final String STAGE_CREEP_CLASS_NAME = StageCreepCorrectionTransform.class.getName(); + private static final Logger LOG = LoggerFactory.getLogger(SofimaStitchFix.class); } From 4485a0d1e68e31148948fbbfb9516874cb9c7934 Mon Sep 17 00:00:00 2001 From: Eric Trautman Date: Wed, 2 Dec 2026 15:19:45 -0500 Subject: [PATCH 3/5] When SofimaStitchFix loads a transforms.json, each entry's specList must now be exactly [DisplacementFieldTransform, AffineModel2D], both as leaf transforms. Otherwise loading fails with a message naming the image URL and the file. Because this happens during loading, a bad entry stops the import before the target stack is even created. --- .../client/multisem/SofimaStitchFix.java | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java index 37f520672..a840a9ccc 100644 --- a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java @@ -20,12 +20,15 @@ import java.util.Set; import java.util.TreeMap; +import mpicbg.trakem2.transform.AffineModel2D; + import org.janelia.alignment.json.JsonUtils; import org.janelia.alignment.spec.LeafTransformSpec; import org.janelia.alignment.spec.ListTransformSpec; import org.janelia.alignment.spec.ResolvedTileSpecCollection; import org.janelia.alignment.spec.TileSpec; import org.janelia.alignment.spec.TransformSpec; +import org.janelia.alignment.transform.DisplacementFieldTransform; import org.janelia.alignment.transform.StageCreepCorrectionTransform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -280,13 +283,22 @@ private static LayerFix loadLayerFix(final String transformsUri, for (final Iterator> it = tiles.fields(); it.hasNext(); ) { final Map.Entry entry = it.next(); final JsonNode specList = requiredNode(entry.getValue(), "specList", transformsUri); + final TransformSpec[] specs; try { - final TransformSpec[] specs = JsonUtils.MAPPER.treeToValue(specList, TransformSpec[].class); - imageUrlToSpecs.put(entry.getKey(), Arrays.asList(specs)); + specs = JsonUtils.MAPPER.treeToValue(specList, TransformSpec[].class); } catch (final IOException e) { throw new IllegalArgumentException( "failed to parse specList for " + entry.getKey() + " in " + transformsUri, e); } + // the replacement removes the tile's affine (and any creep correction), so anything other than the + // stitch fix field plus its placing affine (e.g. an empty list) would leave the tile misplaced + if ((specs == null) || (specs.length != 2) || + isNotA(specs[0], DISPLACEMENT_FIELD_CLASS_NAME) || isNotA(specs[1], AFFINE_CLASS_NAME)) { + throw new IllegalArgumentException( + "specList for " + entry.getKey() + " in " + transformsUri + " is not [" + + DISPLACEMENT_FIELD_CLASS_NAME + ", " + AFFINE_CLASS_NAME + "]"); + } + imageUrlToSpecs.put(entry.getKey(), Arrays.asList(specs)); } final JsonNode numTiles = layerJson.get("num_tiles"); @@ -367,5 +379,9 @@ private static JsonNode readJson(final String uri) /** Stage creep correction is replaced along with the affine, since the restitching did not apply it. */ private static final String STAGE_CREEP_CLASS_NAME = StageCreepCorrectionTransform.class.getName(); + /** Classes of the two replacement specs: the tile-local stitch fix field and the affine that places it. */ + private static final String DISPLACEMENT_FIELD_CLASS_NAME = DisplacementFieldTransform.class.getName(); + private static final String AFFINE_CLASS_NAME = AffineModel2D.class.getName(); + private static final Logger LOG = LoggerFactory.getLogger(SofimaStitchFix.class); } From ca32d0f578b8f589adc57b6ad2d5d8599a0d37de Mon Sep 17 00:00:00 2001 From: Eric Trautman Date: Wed, 2 Dec 2026 15:26:31 -0500 Subject: [PATCH 4/5] prevent duplicate image URLs from reusing replacement entries --- .../janelia/render/client/multisem/SofimaStitchFix.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java index a840a9ccc..9e3efb4dc 100644 --- a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java @@ -174,7 +174,12 @@ public void apply(final Double z, problems.add("tile " + tileSpec.getTileId() + " (" + imageUrl + ") has no replacement"); continue; } - unusedImageUrls.remove(imageUrl); + // the replacement exists, so failing to remove it means an earlier tile with the same image used it + if (! unusedImageUrls.remove(imageUrl)) { + problems.add("tile " + tileSpec.getTileId() + " has the same image as another tile (" + imageUrl + + "), so the replacement for it matches more than one tile"); + continue; + } if (! hasExpectedLayout(tileSpec.getTransforms(), layerFix)) { problems.add("tile " + tileSpec.getTileId() + " transforms " + describe(tileSpec.getTransforms()) + From 94af6cf2a6933523631da7f3deb62aa22eb3fc0f Mon Sep 17 00:00:00 2001 From: Eric Trautman Date: Wed, 2 Dec 2026 15:34:39 -0500 Subject: [PATCH 5/5] flatten resolved transform chains before validating and retaining them --- .../render/client/multisem/SofimaStitchFix.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java index 9e3efb4dc..f3944cffe 100644 --- a/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java +++ b/render-ws-java-client/src/main/java/org/janelia/render/client/multisem/SofimaStitchFix.java @@ -181,6 +181,18 @@ public void apply(final Double z, continue; } + // getResolvedTiles resolves references but does not flatten them, so flatten first for the layout + // check (and the replacement) to see the effective leaf transforms. Changing the tile here is safe even + // if the layer is rejected below, because a rejected layer fails the import before anything is saved. + try { + if (tileSpec.getTransforms() != null) { + tileSpec.flattenTransforms(); + } + } catch (final IllegalStateException e) { + problems.add("tile " + tileSpec.getTileId() + " transforms cannot be flattened: " + e.getMessage()); + continue; + } + if (! hasExpectedLayout(tileSpec.getTransforms(), layerFix)) { problems.add("tile " + tileSpec.getTileId() + " transforms " + describe(tileSpec.getTransforms()) + " are not [" + layerFix.firstClassName() + ", (" + STAGE_CREEP_CLASS_NAME + ")*, " +