Cremi example#

This example shows how to use volara to process a realistic dataset. In this case we are using CREMI. We used volara to generate the predictions blockwise. To see how to use volara to generate predictions blockwise, see the volara-torch plugin example

[1]:
import multiprocessing as mp

mp.set_start_method("fork", force=True)  # type: ignore[call-arg]
[2]:
import logging
from pathlib import Path

from funlib.geometry import Coordinate

logging.basicConfig(level=logging.WARNING)

Path("_static/cremi").mkdir(parents=True, exist_ok=True)

First things first lets visualize the data we’ve been given.

[3]:
import matplotlib.animation as animation
import matplotlib.pyplot as plt

from volara.datasets import Affs, Raw

raw = Raw(store="sample_A+_20160601.zarr/raw", scale_shift=(1 / 255, 0))  # type: ignore[arg-type]
affs = Affs(store="sample_A+_20160601.zarr/affs")  # type: ignore[arg-type]

fig, axes = plt.subplots(1, 3, figsize=(14, 8))

ims = []
for i, (raw_slice, affs_slice) in enumerate(
    zip(raw.array("r")[:], affs.array("r")[:].transpose([1, 0, 2, 3]), strict=False)
):
    # Show the raw data
    if i == 0:
        im_raw = axes[0].imshow(raw_slice, cmap="gray")
        axes[0].set_title("Raw")
        im_affs_short = axes[1].imshow(
            affs_slice[0:3].transpose([1, 2, 0]), vmin=0, vmax=255, interpolation="none"
        )
        axes[1].set_title("Affs (short range)")
        im_affs_long = axes[2].imshow(
            affs_slice[[0, 5, 6]].transpose([1, 2, 0]),
            vmin=0,
            vmax=255,
            interpolation="none",
        )
        axes[2].set_title("Affs (long range)")
    else:
        im_raw = axes[0].imshow(raw_slice, cmap="gray", animated=True)
        axes[0].set_title("Raw")
        im_affs_short = axes[1].imshow(
            affs_slice[0:3].transpose([1, 2, 0]),
            vmin=0,
            vmax=255,
            interpolation="none",
            animated=True,
        )
        axes[1].set_title("Affs (short range)")
        im_affs_long = axes[2].imshow(
            affs_slice[[0, 5, 6]].transpose([1, 2, 0]),
            vmin=0,
            vmax=255,
            interpolation="none",
            animated=True,
        )
        axes[2].set_title("Affs (long range)")
    ims.append([im_raw, im_affs_short, im_affs_long])

ims = ims + ims[::-1]
ani = animation.ArtistAnimation(fig, ims, blit=True)
ani.save("_static/cremi/inputs.gif", writer="pillow", fps=10)
plt.close()

inputs

Now we can convert the results to a segmentation. We will run mutex watershed on the affinities in a multi step process.

  1. Local fragment extraction - This step runs blockwise and generates fragments from the affinities. For each fragment we save a node in a graph with attributes such as its spatial position and size.

  2. Edge extraction - This step runs blockwise and computes mean affinities between fragments, adding edges to the fragment graph.

  3. Graph Mutex Watershed - This step runs on the fragment graph, and creates a lookup table from fragment id -> segment id.

  4. Relabel fragments - This step runs blockwise and creates the final segmentation.

[4]:
from volara.blockwise import AffAgglom, ExtractFrags, GraphMWS, Relabel
from volara.datasets import Labels
from volara.dbs import SQLite
from volara.lut import LUT

First lets define the graph and arrays we are going to use.

because our graph is in an sql database, we need to define a schema with column names and types for node and edge attributes. For nodes: The defaults such as “id”, “position”, and “size” are already defined so we only need to define the additional attributes, in this case we have no additional node attributes. For edges: The defaults such as “id”, “u”, “v” are already defined, so we are only adding the additional attributes “xy_aff”, “z_aff”, and “lr_aff” for saving the mean affinities between fragments.

[5]:
fragments_graph = SQLite(
    path="sample_A+_20160601.zarr/fragments.db",  # type: ignore[arg-type]
    edge_attrs={"xy_aff": "float", "z_aff": "float", "lr_aff": "float"},
)
fragments_dataset = Labels(store="sample_A+_20160601.zarr/fragments")  # type: ignore[arg-type]
segments_dataset = Labels(store="sample_A+_20160601.zarr/segments")  # type: ignore[arg-type]

Now we define the tasks with the parameters we want to use.

[6]:

block_size = raw.array("r")._source_data.chunks # Generate fragments in blocks extract_frags = ExtractFrags( db=fragments_graph, affs_data=affs, frags_data=fragments_dataset, block_size=block_size, context=Coordinate(6, 12, 12), bias=[-0.6] + [-0.4] * 2 + [-0.6] * 2 + [-0.8] * 2, strides=( [Coordinate(1, 1, 1)] * 3 + [Coordinate(1, 3, 3)] * 2 # We use larger strides for larger affinities + [Coordinate(1, 6, 6)] * 2 # This is to avoid excessive splitting ), randomized_strides=True, # converts strides to probabilities of sampling affinities (1/prod(stride)) remove_debris=64, # remove excessively small fragments num_workers=4, ) # Generate agglomerated edge scores between fragments via mean affinity accross all edges connecting two fragments aff_agglom = AffAgglom( db=fragments_graph, affs_data=affs, frags_data=fragments_dataset, block_size=block_size, context=Coordinate(3, 6, 6) * 1, scores={ "z_aff": affs.neighborhood[0:1], "xy_aff": affs.neighborhood[1:3], "lr_aff": affs.neighborhood[3:], }, num_workers=4, ) # Run mutex watershed again, this time on the fragment graph with agglomerated edges # instead of the voxel graph of affinities lut = LUT(path="sample_A+_20160601.zarr/lut.npz") # type: ignore[arg-type] total_roi = raw.array("r").roi graph_mws = GraphMWS( db=fragments_graph, lut=lut, weights={"xy_aff": (1, -0.4), "z_aff": (1, -0.6), "lr_aff": (1, -0.6)}, roi=total_roi, ) # Relabel the fragments into segments relabel = Relabel( lut=lut, frags_data=fragments_dataset, seg_data=segments_dataset, block_size=block_size, num_workers=4, ) pipeline = extract_frags + aff_agglom + graph_mws + relabel pipeline.run_blockwise(multiprocessing=True)

Execution Summary
-----------------

    task                        blocks   completed  skipped  failed  orphaned
    ─────────────────────────  ───────  ──────────  ───────  ──────  ────────
    fragments-extract-frags ✔      128         128        0       0         0
    fragments-aff-agglom ✔         128         128        0       0         0
    lut-graph-mws ✔                  1           1        0       0         0
    segments-relabel ✔             128         128        0       0         0

Resource Utilization
--------------------

  fragments-extract-frags   128 blocks, 4 workers, 250.58 s wall
    blocks   round trip 7.17 s ± 1.08 s
             wall 7.17 s ± 1.08 s   cpu 5.91 s ± 0.62 s   peak RSS 1.8 GB ± 94.4 MB
             io read 4.6 GB  write 47.4 MB   overhead 1.8 ms ± 1.8 ms   trend ∠ -1.9194 ms/block
    workers  startup 2.23 s ± 0.08 s   idle 1.4 ms ± 1.5 ms   teardown 1.14 s ± 0.19 s
             exits 4 clean
        id    startup  blocks       idle         idle / block    compute      compute / block   teardown  exit
         0     2.27 s      32    36.2 ms      1.1 ms ± 0.9 ms   227.20 s      7.10 s ± 1.18 s     1.24 s  clean
         1     2.15 s      32    57.6 ms      1.8 ms ± 2.2 ms   229.84 s      7.18 s ± 1.04 s     1.15 s  clean
         2     2.32 s      32    43.7 ms      1.4 ms ± 1.4 ms   228.66 s      7.15 s ± 1.12 s     1.29 s  clean
         3     2.17 s      32    40.0 ms      1.2 ms ± 1.2 ms   232.27 s      7.26 s ± 1.02 s   870.2 ms  clean

  fragments-aff-agglom   128 blocks, 4 workers, 250.58 s wall
    blocks   round trip 1.78 s ± 0.43 s
             wall 1.77 s ± 0.43 s   cpu 936.0 ms ± 116.9 ms   peak RSS 648.5 MB ± 31.6 MB
             io read 4.2 GB  write 37.2 MB   overhead 3.1 ms ± 2.8 ms   trend ∠ -3.5998 ms/block
    workers  startup 4.96 s ± 0.27 s   idle 4.15 s ± 3.66 s   teardown 426.6 ms ± 13.1 ms
             exits 4 clean
        id    startup  blocks       idle         idle / block    compute      compute / block   teardown  exit
         4     4.94 s      32   134.01 s      4.19 s ± 3.54 s    56.22 s      1.76 s ± 0.41 s   443.0 ms  clean
         5     4.59 s      31   133.41 s      4.30 s ± 3.85 s    56.52 s      1.82 s ± 0.46 s   410.9 ms  clean
         6     5.15 s      33   132.98 s      4.03 s ± 3.86 s    56.30 s      1.71 s ± 0.42 s   425.7 ms  clean
         7     5.16 s      32   131.10 s      4.10 s ± 3.56 s    58.23 s      1.82 s ± 0.42 s   426.8 ms  clean

  lut-graph-mws   1 blocks, 1 worker, 250.58 s wall
    blocks   round trip 2.97 s
             wall 2.97 s   cpu 2.96 s   peak RSS 537.6 MB
             io read 16.1 MB  write 10.4 MB   overhead 450.4 µs   trend ∠ +0.0000 ms/block
    workers  startup 1.73 s   idle 467.2 µs   teardown 658.6 ms
             exits 1 clean
        id    startup  blocks       idle         idle / block    compute      compute / block   teardown  exit
         8     1.73 s       1   467.2 µs             467.2 µs     2.97 s               2.97 s   658.6 ms  clean

  segments-relabel   128 blocks, 4 workers, 250.58 s wall
    blocks   round trip 121.7 ms ± 26.3 ms
             wall 119.5 ms ± 26.1 ms   cpu 117.2 ms ± 13.0 ms   peak RSS 472.8 MB ± 22.0 MB
             io read 20.5 MB  write 17.0 MB   overhead 2.2 ms ± 1.8 ms   trend ∠ -0.1383 ms/block
    workers  startup 4.74 s ± 0.15 s   idle 315.3 µs ± 365.4 µs   teardown 626.1 ms ± 31.1 ms
             exits 4 clean
        id    startup  blocks       idle         idle / block    compute      compute / block   teardown  exit
         9     4.64 s      33    13.0 ms  393.5 µs ± 529.9 µs     3.98 s   120.7 ms ± 25.3 ms   620.6 ms  clean
        10     4.61 s      34    12.0 ms  352.4 µs ± 461.3 µs     4.00 s   117.8 ms ± 26.1 ms   641.4 ms  clean
        11     4.77 s      30     7.1 ms   237.3 µs ± 67.5 µs     3.91 s   130.5 ms ± 25.5 ms   585.3 ms  clean
        12     4.94 s      31     8.3 ms  266.8 µs ± 102.8 µs     3.67 s   118.5 ms ± 27.7 ms   657.2 ms  clean
[6]:
{'fragments-aff-agglom': Started: true
 Total Blocks: 128
 Ready: 0
 Processing: 0
 Pending: 0
 Completed: 128
 Skipped: 0
 Failed: 0
 Orphaned: 0,
 'segments-relabel': Started: true
 Total Blocks: 128
 Ready: 0
 Processing: 0
 Pending: 0
 Completed: 128
 Skipped: 0
 Failed: 0
 Orphaned: 0,
 'lut-graph-mws': Started: true
 Total Blocks: 1
 Ready: 0
 Processing: 0
 Pending: 0
 Completed: 1
 Skipped: 0
 Failed: 0
 Orphaned: 0,
 'fragments-extract-frags': Started: true
 Total Blocks: 128
 Ready: 0
 Processing: 0
 Pending: 0
 Completed: 128
 Skipped: 0
 Failed: 0
 Orphaned: 0}

Let’s visualize

If you are following through on your own, I highly recommend installing funlib.show.neuroglancer, and running the command line tool via neuroglancer -d sample_A+_20160601.zarr/* to visualize the results in neuroglancer.

For the purposes of visualizing here, we will make a simple gif

[7]:
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

fragments = fragments_dataset.array("r")[:, ::2, ::2]
segments = segments_dataset.array("r")[:, ::2, ::2]
raw_data = raw.array("r")[:, ::2, ::2]

# Get unique labels
unique_labels = set(np.unique(fragments)) | set(np.unique(segments))
num_labels = len(unique_labels)


def random_color(label):
    rs = np.random.RandomState(np.random.MT19937(np.random.SeedSequence(label)))
    return np.array((rs.random(), rs.random(), rs.random()))


# Generate random colors for each label
random_fragment_colors = [random_color(label) for label in range(num_labels)]

# Create a colormap
cmap_labels = ListedColormap(random_fragment_colors)

# Map labels to indices for the colormap
label_to_index = {label: i for i, label in enumerate(unique_labels)}
indexed_fragments = np.vectorize(label_to_index.get)(fragments)
indexed_segments = np.vectorize(label_to_index.get)(segments)

fig, axes = plt.subplots(1, 3, figsize=(18, 8))

ims = []
for i, (raw_slice, fragments_slice, segments_slice) in enumerate(
    zip(raw_data, indexed_fragments, indexed_segments, strict=False)
):
    # Show the raw data
    if i == 0:
        im_raw = axes[0].imshow(raw_slice, cmap="gray")
        axes[0].set_title("Raw")
        im_fragments = axes[1].imshow(
            fragments_slice,
            cmap=cmap_labels,
            vmin=0,
            vmax=num_labels,
            interpolation="none",
        )
        axes[1].set_title("Fragments")
        im_segments = axes[2].imshow(
            segments_slice,
            cmap=cmap_labels,
            vmin=0,
            vmax=num_labels,
            interpolation="none",
        )
        axes[2].set_title("Segments")
    else:
        im_raw = axes[0].imshow(raw_slice, animated=True, cmap="gray")
        im_fragments = axes[1].imshow(
            fragments_slice,
            cmap=cmap_labels,
            vmin=0,
            vmax=num_labels,
            interpolation="none",
            animated=True,
        )
        im_segments = axes[2].imshow(
            segments_slice,
            cmap=cmap_labels,
            vmin=0,
            vmax=num_labels,
            interpolation="none",
            animated=True,
        )
    ims.append([im_raw, im_fragments, im_segments])

ims = ims + ims[::-1]
ani = animation.ArtistAnimation(fig, ims, blit=True)
ani.save("_static/cremi/segmentation.gif", writer="pillow", fps=10)
plt.close()

The final segmentation is shown below. Obviously this is not a great segmentation, but it is reasonably good for a model small enough to process a CREMI dataset in 20 minutes on a github action. segmentation