Zaimi et al. (2018), AxonDeepSeg, tested on dandiset 001436¶

Paper. Zaimi A, Wabartha M, Herman V, Antonsanti P-L, Perone CS, Cohen-Adad J (2018). AxonDeepSeg: automatic axon and myelin segmentation from microscopy data using convolutional neural networks. Scientific Reports 8, 3816. doi:10.1038/s41598-018-22181-4.

Dataset. DANDI:001436, "TEM Images of Corpus Callosum in Control and Cuprizone-Intoxicated Mice with Axon and Myelin Segmentations", version 0.250512.1625 (doi:10.48324/dandi.001436/0.250512.1625). The paper cites no version of the dandiset (the dandiset was created in 2025, after the paper). 0.250512.1625 is the only published version, and the draft (modified 2026-09-23) has the same 660 assets and size, so the most recent published version is pinned. The dataset is a BIDS microscopy dataset of png images, not NWB; the files are read from the archive into memory.

Text the claims were written from. The version of record (PMC5830647), with Methods, figure legends and Tables 1 to 3; the paper has no supplement. Claims file: claims/zaimi-2018.yaml.

Outside inputs. (1) The paper's released TEM model, default_TEM_model_v1, at commit 7f6013221b2a862e107a7e23f3c8662eba3ba64b of https://github.com/neuropoly/axondeepseg, with the inference code at the same commit (claims data: with_inputs). (2) The folder names of the NYU mouse component (OSF node adrcs) of the White Matter Microscopy Database (https://osf.io/yp4qg/, doi:10.17605/OSF.IO/YP4QG), which the paper's Data availability statement names, to label each mouse as control or cuprizone (data: with_labels, tested by the link claim osf-group-labels-link). (3) The macaque TEM images and masks of ref. 7 in the same database (OSF node yp4qg, folder MontrealNeurologicalInstitute/histology/Macaque), for the two macaque claims (data: elsewhere). (4) The SEM dataset of AxonDeepSeg, https://github.com/axondeepseg/data_axondeepseg_sem at tag r20211130 (commit d7884f9, doi:10.5281/zenodo.5498378), whose rat images include two with the pixel size, field of view and fixation of the paper's SEM test images, for table3-sem-rat-accuracy (data: elsewhere).

Ground truth. The dandiset's masks are not those the paper scored against: its CHANGES file (printed below) says that in 2025 the masks of 155 of the 158 images were changed "to separate all fibers with a 2px delineation", and one mask was corrected in 2022. The earlier masks are not public. A variant that fills the delineation lines bounds the effect on the mouse scores.

Claim Tested here
osf-group-labels-link (added by this attempt) tested
table3-tem-mice-accuracy tested
table3-tem-mice-dice-detection tested
myelin-dice-below-axon-dice tested (mouse images only)
sensitivity-above-93 tested (mouse images only)
table3-sem-rat-accuracy tested on the SEM dataset of AxonDeepSeg (data elsewhere)
table3-sem-human-accuracy blocked, the human SEM test image is not public
table3-tem-macaque-accuracy tested on the macaque images of the White Matter Microscopy Database (data elsewhere)
table3-other-samples-dice-detection blocked, the human SEM test image is not public (rat and macaque values shown)
macaque-myelin-underestimated tested on the macaque images of the White Matter Microscopy Database (data elsewhere)
full-slice-processing-time blocked, no SEM slice in the dandiset
fig7-corticospinal-tract blocked, no rat spinal cord in the dandiset
fig7-larger-axons-periphery blocked, as above
fig7-tract-diameters blocked, as above
fig7-gratio-range blocked, as above
In [1]:
import os
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
import itertools
import json
import time

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import axondeepseg_tem as ads

pd.set_option("display.width", 200)
pd.set_option("display.max_columns", 40)
print("dandiset", ads.DANDISET_ID, "version", ads.DANDISET_VERSION)
print("AxonDeepSeg commit", ads.ADS_COMMIT)
dandiset 001436 version 0.250512.1625
AxonDeepSeg commit 7f6013221b2a862e107a7e23f3c8662eba3ba64b

Data¶

The archive's metadata, the file list and the sidecar files. Each mouse has one sidecar (sub-<mouse>_TEM.json) giving the pixel size.

In [2]:
meta = ads.version_metadata()
print(meta["name"])
print("assets", meta["assetsSummary"]["numberOfFiles"], "bytes", meta["assetsSummary"]["numberOfBytes"],
      "subjects", meta["assetsSummary"]["numberOfSubjects"], "samples (archive summary)",
      meta["assetsSummary"]["numberOfSamples"])
print(meta["description"])

assets = ads.list_assets()
kind = assets.path.str.replace(r"sub-nyuMouse\d+", "sub-*", regex=True).str.replace(r"sample-\d+", "sample-*", regex=True)
print(kind.value_counts().to_string())
for p in ["README", "CHANGES", "participants.tsv", "samples.json", "derivatives/labels/dataset_description.json"]:
    print("=====", p)
    print(ads.read_bytes(assets.set_index("path").asset_id[p]).decode())
TEM Images of  Corpus Callosum in Control and Cuprizone-Intoxicated Mice with Axon and Myelin Segmentations
assets 660 bytes 1042211940 subjects 20 samples (archive summary) 11
- TEM dataset for AxonDeepSeg (https://axondeepseg.readthedocs.io/)

- 158 brain (splenium) samples from 20 mice with axon and myelin manual segmentation labels.

- Every individual axon is separated from neighboring fibers with a 2 pixel delineation, such that this semantic segmentation dataset also doubles as an instance segmentation dataset.

- In our original paper (Zaimi et al. 2018), the FOV was reported to be 6x9 um^2. This is because 1) these original values were reported in the original data reference (below), and 2) our images here are slightly cropped at the bottom relative to the original data in order to remove the scale bar.

- Our original paper (Zaimi et al. 2018) reported the resolution as being 0.002 micrometer, which was (for an unknown reason) rounded in the paper from the true value of 0.00236 micrometer, as reported in the original data reference (below).

- Reference for the origin of the data: Jelescu, I. O. et al. In vivo quantification of demyelination and recovery using compartment-specific diffusion MRI metrics validated by electron microscopy. Neuroimage 132, 104–114 (2016). See https://doi.org/10.1016/j.neuroimage.2016.02.004 (Center for Biomedical Imaging, Department of Radiology, New York University School of Medicine, New York, NY, USA)

- The original aim of the 2016 study was to quantify demyelination in mice intoxicated with cuprizone in both accute (6 weeks) and chronic (12 weeks) scenarios. As such, this dataset includes samples from both healthy and intoxicated mouse groups.
path
derivatives/labels/sub-*/micr/sub-*_sample-*_TEM_seg-axon-manual.png          158
derivatives/labels/sub-*/micr/sub-*_sample-*_TEM_seg-myelin-manual.png        158
derivatives/labels/sub-*/micr/sub-*_sample-*_TEM_seg-axonmyelin-manual.png    158
sub-*/micr/sub-*_sample-*_TEM.png                                             158
sub-*/micr/sub-*_TEM.json                                                      20
README                                                                          1
CHANGES                                                                         1
derivatives/labels/dataset_description.json                                     1
dataset_description.json                                                        1
participants.json                                                               1
participants.tsv                                                                1
samples.json                                                                    1
samples.tsv                                                                     1
===== README
- TEM dataset for AxonDeepSeg (https://axondeepseg.readthedocs.io/)
- 158 brain (splenium) samples from 20 mice with axon and myelin manual segmentation labels.
- In our original paper (Zaimi et al. 2018), the FOV was reported to be 6x9 um^2. This is because 1) these original values were reported in the original data reference (below), and 2) our images here are slightly cropped at the bottom relative to the original data in order to remove the scale bar.
- Our original paper (Zaimi et al. 2018) reported the resolution as being 0.002 micrometer, which was (for an unknown reason) rounded in the paper from the true value of 0.00236 micrometer, as reported in the original data reference (below).
- Reference for the origin of the dataset: Jelescu, I. O. et al. In vivo quantification of demyelination and recovery using compartment-specific diffusion MRI metrics validated by electron microscopy. Neuroimage 132, 104–114 (2016). See https://doi.org/10.1016/j.neuroimage.2016.02.004.

- BIDS version 1.6.0 - Microscopy BEP031 version 0.0.4 (2021-07-13T15:14:00)

===== CHANGES
The following is a high-level summary of the changes this dataset underwent
over the years, based on its git history.

0.04 2025-04-30

- Modify the masks of 155 images to separate all fibers with a 2px delineation

- Add author list and cleanup README

0.03 2022-02-22

- Correct the mask of sub-nyuMouse15_sample-0005

- Update dataset for BIDS 1.7.0

0.02 2014-10-09

- Update README

- Replace sample sub-nyuMouse26_sample-0004 with its full size version

- Remove fuzzy values in the masks

0.01 2014-07-14

- Initial data upload and BIDS formatting
===== participants.tsv
participant_id	species
sub-nyuMouse07	mus musculus
sub-nyuMouse09	mus musculus
sub-nyuMouse10	mus musculus
sub-nyuMouse11	mus musculus
sub-nyuMouse12	mus musculus
sub-nyuMouse13	mus musculus
sub-nyuMouse14	mus musculus
sub-nyuMouse15	mus musculus
sub-nyuMouse25	mus musculus
sub-nyuMouse26	mus musculus
sub-nyuMouse27	mus musculus
sub-nyuMouse28	mus musculus
sub-nyuMouse29	mus musculus
sub-nyuMouse30	mus musculus
sub-nyuMouse31	mus musculus
sub-nyuMouse32	mus musculus
sub-nyuMouse33	mus musculus
sub-nyuMouse34	mus musculus
sub-nyuMouse35	mus musculus
sub-nyuMouse36	mus musculus

===== samples.json
{
    "sample_id": {
        "Description": "Sample ID"
    },
    "participant_id": {
        "Description": "Participant ID from whom tissue samples have been acquired"
    },
    "sample_type": {
        "Description": "Type of sample from ENCODE Biosample Type (https://www.encodeproject.org/profiles/biosample_type)"
    }
}
===== derivatives/labels/dataset_description.json
{
    "Name": "data_axondeepseg_tem labels",
    "BIDSVersion": "1.7.0",
    "PipelineDescription": {
        "Name": "Axon and myelin manual segmentation labels"
    },
    "GeneratedBy": [{
	"Name": "Axon and myelin manual segmentation labels"
    }]
}

In [3]:
table = ads.sample_table(assets)
sidecars = {s: json.loads(ads.read_bytes(a)) for s, a in table.groupby("subject").sidecar.first().items()}
print(pd.DataFrame(sidecars).T.astype(str).drop_duplicates().to_string())
table["pixel_um"] = table.subject.map({s: d["PixelSize"][0] for s, d in sidecars.items()})
samples_tsv = pd.read_csv(pd.io.common.BytesIO(ads.read_bytes(assets.set_index("path").asset_id["samples.tsv"])), sep="\t")
listed = set(zip(samples_tsv.participant_id, samples_tsv.sample_id))
found = set(zip(table.subject, table["sample"]))
print("images", len(table), "with all three masks", int(table[["axon", "myelin", "axonmyelin"]].notna().all(axis=1).sum()))
print("samples.tsv rows", len(samples_tsv), "| listed but no image", sorted(listed - found), "| image not listed", sorted(found - listed))
print("images per mouse:", table.groupby("subject").size().to_dict())
               BodyPart BodyPartDetails                            SampleFixation SampleEnvironment           PixelSize PixelSizeUnits
sub-nyuMouse07    BRAIN        splenium  2% paraformaldehyde, 2.5% glutaraldehyde           ex vivo  [0.00236, 0.00236]             um
images 158 with all three masks 158
samples.tsv rows 158 | listed but no image [] | image not listed []
images per mouse: {'sub-nyuMouse07': 8, 'sub-nyuMouse09': 8, 'sub-nyuMouse10': 8, 'sub-nyuMouse11': 8, 'sub-nyuMouse12': 8, 'sub-nyuMouse13': 8, 'sub-nyuMouse14': 8, 'sub-nyuMouse15': 8, 'sub-nyuMouse25': 6, 'sub-nyuMouse26': 8, 'sub-nyuMouse27': 8, 'sub-nyuMouse28': 8, 'sub-nyuMouse29': 8, 'sub-nyuMouse30': 8, 'sub-nyuMouse31': 8, 'sub-nyuMouse32': 8, 'sub-nyuMouse33': 8, 'sub-nyuMouse34': 8, 'sub-nyuMouse35': 8, 'sub-nyuMouse36': 8}

Group labels from the White Matter Microscopy Database¶

The dandiset does not say which mice are controls and which received cuprizone, though its description says it holds both. The claims name, as one reading of the test set, the control mice only. The paper's Data availability statement names the White Matter Microscopy Database; its NYU component (OSF node adrcs) holds the raw micrographs of ref. 27 in one folder per diet group and time point, with one sub-folder per mouse named by the mouse's number. Only the folder names are used.

In [4]:
osf = ads.osf_mouse_folders()
print(osf[["group_folder", "mouse_folder", "mouse"]].to_string())
                          group_folder mouse_folder  mouse
0                            ctl_12wks          25G     25
1                            ctl_12wks          25S     25
2                            ctl_12wks          26G     26
3                            ctl_12wks          26S     26
4                            ctl_12wks          27G     27
5                            ctl_12wks          27S     27
6                            ctl_18wks          34G     34
7                            ctl_18wks          34S     34
8                            ctl_18wks          35G     35
9                            ctl_18wks          35S     35
10                           ctl_18wks          36G     36
11                           ctl_18wks          36S     36
12                            ctl_6wks          7SG      7
13                            ctl_6wks          9SC      9
14                            ctl_6wks         17SG     17
15   cpz6_treatment_6wks_recovery_6wks          21G     21
16   cpz6_treatment_6wks_recovery_6wks          21S     21
17   cpz6_treatment_6wks_recovery_6wks          28G     28
18   cpz6_treatment_6wks_recovery_6wks          28S     28
19   cpz6_treatment_6wks_recovery_6wks          29G     29
20   cpz6_treatment_6wks_recovery_6wks          29S     29
21   cpz6_treatment_6wks_recovery_6wks          30G     30
22   cpz6_treatment_6wks_recovery_6wks          30S     30
23   cpz6_treatment_6wks_recovery_6wks          19G     19
24   cpz6_treatment_6wks_recovery_6wks          19S     19
25   cpz6_treatment_6wks_recovery_6wks          20G     20
26   cpz6_treatment_6wks_recovery_6wks          20S     20
27  cpz6_treatment_12wks_recovery_6wks          22G     22
28  cpz6_treatment_12wks_recovery_6wks          22S     22
29  cpz6_treatment_12wks_recovery_6wks          23G     23
30  cpz6_treatment_12wks_recovery_6wks          23S     23
31  cpz6_treatment_12wks_recovery_6wks          24G     24
32  cpz6_treatment_12wks_recovery_6wks          24S     24
33  cpz6_treatment_12wks_recovery_6wks          31G     31
34  cpz6_treatment_12wks_recovery_6wks          31S     31
35  cpz6_treatment_12wks_recovery_6wks          32G     32
36  cpz6_treatment_12wks_recovery_6wks          32S     32
37  cpz6_treatment_12wks_recovery_6wks          33G     33
38  cpz6_treatment_12wks_recovery_6wks          33S     33
39               cpz6_treatement_12wks          1SG      1
40               cpz6_treatement_12wks          2SG      2
41               cpz6_treatement_12wks          3SG      3
42               cpz6_treatement_12wks         13SG     13
43               cpz6_treatement_12wks         14SG     14
44               cpz6_treatement_12wks         15SG     15
45                 cpz6_treatment_6wks          4SG      4
46                 cpz6_treatment_6wks          5SG      5
47                 cpz6_treatment_6wks          6SG      6
48                 cpz6_treatment_6wks          10G     10
49                 cpz6_treatment_6wks          10S     10
50                 cpz6_treatment_6wks          11G     11
51                 cpz6_treatment_6wks          11S     11
52                 cpz6_treatment_6wks          12G     12
53                 cpz6_treatment_6wks     12S_redo     12

The model¶

The paper's TEM model is read from GitHub at the pinned commit. Its network is rebuilt from the checkpoint (see the helper's docstring), and checked here against the model's own saved TensorFlow graph (model.ckpt.meta), run with training_phase False, on the four patches of the first image.

In [5]:
weights, config = ads.load_tem_model()
print("variables", len(weights), "parameters", sum(int(np.prod(v.shape)) for v in weights.values()))
print({k: config[k] for k in ["depth", "trainingset_patchsize", "n_classes", "convolution_per_layer", "downsampling", "batch_norm_activate"]})

first = table.iloc[0]
img0, gt0, _ = ads.load_sample(first)
from skimage.transform import rescale
rs0 = rescale((255 - img0.astype(int)).astype(np.uint8), first.pixel_um / ads.WORKING_PIXEL_UM, order=1,
              mode="constant", preserve_range=True, anti_aliasing=False).astype(int)
patches0, pos0 = ads.im2patches_overlap(rs0)
mine = ads.unet_forward(weights, config, patches0)
theirs = ads.original_graph_output(patches0)
print("patches", len(patches0), "positions", pos0)
print("largest absolute difference of the outputs", float(np.abs(mine - theirs).max()),
      "| output range", float(theirs.min()), float(theirs.max()))
print("fraction of pixels with the same class", float((mine.argmax(3) == theirs.argmax(3)).mean()))
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1794327645.933291    2540 port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1794327650.510465    2540 port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
variables 122 parameters 1555267
{'depth': 4, 'trainingset_patchsize': 512, 'n_classes': 3, 'convolution_per_layer': [2, 2, 2, 2], 'downsampling': 'convolution', 'batch_norm_activate': True}
WARNING:tensorflow:The saved meta_graph is possibly from an older release:
'model_variables' collection should be of type 'byte_list', but instead is of type 'node_list'.
INFO:tensorflow:Restoring parameters from /tmp/tmpke35c7qw/model.ckpt
patches 4 positions [[0, 0], [27, 0], [0, 376], [27, 376]]
largest absolute difference of the outputs 1.1444091796875e-05 | output range 0.0 16.016094207763672
fraction of pixels with the same class 1.0

The inference steps of the original code¶

The parts of the pinned code that the helper repeats outside the network, printed so that they can be compared with segment and resize_back: the contrast inversion for this model (segment.py), the working pixel sizes, the resampling of the input, the preprocessing of each patch, and the resize of the class map back to the native shape followed by the cast to uint8 (apply_model.py). The code ran with scikit-image 0.13 (it required >= 0.12.3); the lines of scikit-image 0.13.1 that set the defaults of resize and rescale (order 1, mode 'constant' when none is given) and the exact integer histogram of equalize_hist are printed too, as these defaults changed later. The original pipeline (Python 2, TensorFlow 1) cannot be installed here, so its output is not compared end to end.

In [6]:
for path, a, b in [("AxonDeepSeg/segment.py", 149, 154), ("AxonDeepSeg/segment.py", 239, 249),
                   ("AxonDeepSeg/apply_model.py", 332, 335), ("AxonDeepSeg/patch_management_tools.py", 5, 16),
                   ("AxonDeepSeg/apply_model.py", 416, 421)]:
    print(f"----- {path}, lines {a} to {b}, at {ads.ADS_COMMIT[:7]}")
    print(ads.code_lines(path, a, b))
for path, a, b in [("skimage/transform/_warps.py", 21, 22), ("skimage/transform/_warps.py", 82, 83),
                   ("skimage/transform/_warps.py", 140, 141), ("skimage/exposure/exposure.py", 67, 86)]:
    print(f"----- scikit-image v0.13.1, {path}, lines {a} to {b}")
    print(ads.code_lines(path, a, b, commit="v0.13.1", repo="scikit-image/scikit-image"))
# The cast after the bilinear resize truncates: a pixel halfway between axon (2) and background (0) becomes myelin (1).
demo = np.array([[2.0, 0.0]])
print("resize_back of [[2, 0]] to 1 x 3:", ads.resize_back(demo, (1, 3)).tolist(), "| nearest neighbour:", ads.resize_back(demo, (1, 3), order=0).tolist())
----- AxonDeepSeg/segment.py, lines 149 to 154, at 7f60132
 149  		if (file_.endswith(".png")) and (selected_model == "default_TEM_model_v1"):
 150  
 151  			# Read image for contrast change
 152  			img = imageio.imread(os.path.join(path_testing_images_folder,file_))
 153  			new_filename = os.path.join(path_testing_images_folder,file_)
 154  			imageio.imwrite(new_filename,255-img)
----- AxonDeepSeg/segment.py, lines 239 to 249, at 7f60132
 239  	dict_size = {
 240  		"SEM":{
 241  			"512":0.1,
 242  			"256":0.2
 243  		},
 244  		"TEM":{
 245  			"512":0.01
 246  		}
 247  	}
 248  
 249  	return dict_size[str(type_acquisition)][str(model_input_size)]
----- AxonDeepSeg/apply_model.py, lines 332 to 335, at 7f60132
 332  
 333  	for i, current_original_acquisition in enumerate(original_acquisitions):
 334  		resampled_acquisitions.append(rescale(current_original_acquisition, resampling_coeffs[i],
 335  											  preserve_range=True).astype(int))
----- AxonDeepSeg/patch_management_tools.py, lines 5 to 16, at 7f60132
   5  def apply_legacy_preprocess(patch):
   6      """
   7      Apply legacy preprocessing (histogram equalization + normalization per patch).
   8      :param patch: The patch (just an image) to preprocess.
   9      :return: Preprocessed patch.
  10      """
  11  
  12      patch = exposure.equalize_hist(patch)
  13      patch = (patch - np.mean(patch)) / np.std(patch)
  14  
  15      return patch
  16  
----- AxonDeepSeg/apply_model.py, lines 416 to 421, at 7f60132
 416  	prediction_stitcheds = [patches2im_overlap(pred_list, L_positions[i], overlap_value, patch_size) for i, pred_list in
 417  							enumerate(L_predictions)]
 418  	predictions = [resize(prediction_stitched, L_original_acquisitions_shapes[i]) for i, prediction_stitched in
 419  				   enumerate(prediction_stitcheds)]
 420  	predictions = [prediction.astype(np.uint8) for prediction in
 421  				   predictions]  # Rescaling operation can change the value of the pixels to float.
----- scikit-image v0.13.1, skimage/transform/_warps.py, lines 21 to 22
  21  def resize(image, output_shape, order=1, mode=None, cval=0, clip=True,
  22             preserve_range=False):
----- scikit-image v0.13.1, skimage/transform/_warps.py, lines 82 to 83
  82      if mode is None:
  83          mode = 'constant'
----- scikit-image v0.13.1, skimage/transform/_warps.py, lines 140 to 141
 140  def rescale(image, scale, order=1, mode=None, cval=0, clip=True,
 141              preserve_range=False):
----- scikit-image v0.13.1, skimage/exposure/exposure.py, lines 67 to 86
  67      # For integer types, histogramming with bincount is more efficient.
  68      if np.issubdtype(image.dtype, np.integer):
  69          offset = 0
  70          image_min = np.min(image)
  71          if image_min < 0:
  72              offset = image_min
  73              image_range = np.max(image).astype(np.int64) - image_min
  74              # get smallest dtype that can hold both minimum and offset maximum
  75              offset_dtype = np.promote_types(np.min_scalar_type(image_range),
  76                                              np.min_scalar_type(image_min))
  77              if image.dtype != offset_dtype:
  78                  # prevent overflow errors when offsetting
  79                  image = image.astype(offset_dtype)
  80              image = image - offset
  81          hist = np.bincount(image.ravel())
  82          bin_centers = np.arange(len(hist)) + offset
  83  
  84          # clip histogram to start with a non-zero bin
  85          idx = np.nonzero(hist)[0][0]
  86          return hist[idx:], bin_centers[idx:]
resize_back of [[2, 0]] to 1 x 3: [[1, 1, 0]] | nearest neighbour: [[2, 0, 0]]

Segmenting every image¶

Each image is segmented as segment.py does for this model (contrast inverted once, 0.01 um working pixel size, 512 x 512 patches with an overlap of 25 pixels), and, as the variant the criterion asks for, without the inversion. Scores are computed against the dandiset's masks at the native pixel size.

In [7]:
t0 = time.time()
res = ads.run_all(table, weights, config)
res["mouse"] = res.subject.str.extract(r"(\d+)$")[0].astype(int)
print(f"{len(res)} images segmented twice in {(time.time() - t0) / 60:.1f} min")
158 images segmented twice in 9.7 min

Data check¶

The masks are checked against their images below. They are the 2025 revision (CHANGES, printed above), in which touching fibres are separated by a 2-pixel line of background; the masks of 2018 are not in the dandiset, which has one published version.

In [8]:
print("images", len(res), "mice", res.subject.nunique())
print("images per mouse:", res.groupby("subject").size().to_dict())
print("pixel size (um) in the sidecars:", sorted(table.pixel_um.unique()), "| Table 1 of the paper gives 0.002")
print("image shapes:", res.groupby(["height", "width"]).size().to_dict())
print("field of view (um): %.2f x %.2f" % (res.height.iloc[0] * table.pixel_um.iloc[0], res.width.iloc[0] * table.pixel_um.iloc[0]),
      "| Table 1 gives 6 x 9")
print("grey levels: min over images", res.img_min.min(), "max", res.img_max.max(), "| lowest image max", res.img_max.min())
print("axon mask values:", res.axon_values.value_counts().to_dict())
print("myelin mask values:", res.myelin_values.value_counts().to_dict())
print("axonmyelin mask values:", res.axonmyelin_values.value_counts().to_dict())
print("dimensions of the axon mask, myelin mask and image:", res.mask_dims.value_counts().to_dict())
print("axonmyelin pngs with 1 channel (grey) and 2 (grey and alpha):", res.axonmyelin_channels.value_counts().to_dict(),
      "| alpha values:", res.axonmyelin_alpha.dropna().value_counts().to_dict())
print("axonmyelin mask (grey channel) equals axon (255) and myelin (128) masks in", int(res.am_agrees.sum()), "of", len(res), "images")
print("pixels both axon and myelin: total", int(res.axon_myelin_overlap.sum()))
print("ground-truth fractions: axon %.3f to %.3f, myelin %.3f to %.3f" % (res.inv_gt_axon_frac.min(), res.inv_gt_axon_frac.max(),
      res.inv_gt_myelin_frac.min(), res.inv_gt_myelin_frac.max()))
print("ground-truth axon objects per image: %d to %d" % (res.inv_P.min(), res.inv_P.max()))

# Masks in register with their images: myelin is the darkest structure in TEM.
print("grey-level contrast, rest of image minus myelin: masks in place median %.1f (min %.1f); "
      "shifted by 50 px median %.1f (max %.1f); larger in place in %d of %d images" % (
      res.contrast.median(), res.contrast.min(), res.contrast_shifted.median(), res.contrast_shifted.max(),
      int((res.contrast > res.contrast_shifted).sum()), len(res)))

# Images deposited twice.
print("distinct images by content hash:", res.sha1.nunique(), "| distinct ground truths:", res.gt_sha1.nunique())
T = np.asarray(list(res.thumb), float)
T = (T - T.mean(1, keepdims=True)) / T.std(1, keepdims=True)
R = T @ T.T / T.shape[1]
iu = np.triu_indices(len(res), 1)
print("largest thumbnail correlation between two different images: %.3f; pairs above 0.95: %d" % (
      R[iu].max(), int((R[iu] > 0.95).sum())))

# The pixel size of the paper (0.002 um) would give images too small for a 512 x 512 patch.
h002 = np.round(res.height * 0.002 / ads.WORKING_PIXEL_UM).astype(int)
print("height after resampling with 0.002 um: %d to %d px (a patch is 512); with the sidecar's %.5f um: %s" % (
      h002.min(), h002.max(), table.pixel_um.iloc[0], sorted({s[0] for s in res.resampled_shape})))
print("patches per image:", res.n_patches.value_counts().to_dict())
images 158 mice 20
images per mouse: {'sub-nyuMouse07': 8, 'sub-nyuMouse09': 8, 'sub-nyuMouse10': 8, 'sub-nyuMouse11': 8, 'sub-nyuMouse12': 8, 'sub-nyuMouse13': 8, 'sub-nyuMouse14': 8, 'sub-nyuMouse15': 8, 'sub-nyuMouse25': 6, 'sub-nyuMouse26': 8, 'sub-nyuMouse27': 8, 'sub-nyuMouse28': 8, 'sub-nyuMouse29': 8, 'sub-nyuMouse30': 8, 'sub-nyuMouse31': 8, 'sub-nyuMouse32': 8, 'sub-nyuMouse33': 8, 'sub-nyuMouse34': 8, 'sub-nyuMouse35': 8, 'sub-nyuMouse36': 8}
pixel size (um) in the sidecars: [np.float64(0.00236)] | Table 1 of the paper gives 0.002
image shapes: {(2286, 3762): 158}
field of view (um): 5.39 x 8.88 | Table 1 gives 6 x 9
grey levels: min over images 0 max 254 | lowest image max 254
axon mask values: {(0, 255): 158}
myelin mask values: {(0, 255): 158}
axonmyelin mask values: {(0, 128, 255): 158}
dimensions of the axon mask, myelin mask and image: {(2, 2, 2): 158}
axonmyelin pngs with 1 channel (grey) and 2 (grey and alpha): {1: 137, 2: 21} | alpha values: {(255,): 21}
axonmyelin mask (grey channel) equals axon (255) and myelin (128) masks in 158 of 158 images
pixels both axon and myelin: total 0
ground-truth fractions: axon 0.048 to 0.521, myelin 0.031 to 0.333
ground-truth axon objects per image: 9 to 90
grey-level contrast, rest of image minus myelin: masks in place median 84.4 (min 50.7); shifted by 50 px median 11.8 (max 29.3); larger in place in 158 of 158 images
distinct images by content hash: 158 | distinct ground truths: 158
largest thumbnail correlation between two different images: 0.534; pairs above 0.95: 0
height after resampling with 0.002 um: 457 to 457 px (a patch is 512); with the sidecar's 0.00236 um: [539]
patches per image: {4: 158}

osf-group-labels-link¶

Each mouse of the dandiset is found, by its number, in exactly one diet-group folder of the NYU component of the White Matter Microscopy Database, and the deposits agree on what both hold (added by this attempt; see the claims file for the criterion).

In [9]:
grp = osf.groupby("mouse").group_folder.agg(lambda s: sorted(set(s)))
dmice = sorted(res.mouse.unique())
link = pd.DataFrame({"mouse": dmice})
link["osf_groups"] = link.mouse.map(lambda m: grp.get(m, []))
link["n_groups"] = link.osf_groups.map(len)
link["group"] = link.osf_groups.map(lambda g: g[0] if len(g) == 1 else None)
link["control"] = link.group.str.startswith("ctl")
print(link.to_string())
print("dandiset mice matched to exactly one group folder:", int((link.n_groups == 1).sum()), "of", len(link))
print("mice per group folder in the dandiset:", link.group.value_counts().to_dict())
print("mice per group folder on OSF:", osf.groupby("group_folder").mouse.nunique().to_dict())
print("controls:", list(link.mouse[link.control]), "| cuprizone:", list(link.mouse[~link.control]))
    mouse                            osf_groups  n_groups                               group  control
0       7                            [ctl_6wks]         1                            ctl_6wks     True
1       9                            [ctl_6wks]         1                            ctl_6wks     True
2      10                 [cpz6_treatment_6wks]         1                 cpz6_treatment_6wks    False
3      11                 [cpz6_treatment_6wks]         1                 cpz6_treatment_6wks    False
4      12                 [cpz6_treatment_6wks]         1                 cpz6_treatment_6wks    False
5      13               [cpz6_treatement_12wks]         1               cpz6_treatement_12wks    False
6      14               [cpz6_treatement_12wks]         1               cpz6_treatement_12wks    False
7      15               [cpz6_treatement_12wks]         1               cpz6_treatement_12wks    False
8      25                           [ctl_12wks]         1                           ctl_12wks     True
9      26                           [ctl_12wks]         1                           ctl_12wks     True
10     27                           [ctl_12wks]         1                           ctl_12wks     True
11     28   [cpz6_treatment_6wks_recovery_6wks]         1   cpz6_treatment_6wks_recovery_6wks    False
12     29   [cpz6_treatment_6wks_recovery_6wks]         1   cpz6_treatment_6wks_recovery_6wks    False
13     30   [cpz6_treatment_6wks_recovery_6wks]         1   cpz6_treatment_6wks_recovery_6wks    False
14     31  [cpz6_treatment_12wks_recovery_6wks]         1  cpz6_treatment_12wks_recovery_6wks    False
15     32  [cpz6_treatment_12wks_recovery_6wks]         1  cpz6_treatment_12wks_recovery_6wks    False
16     33  [cpz6_treatment_12wks_recovery_6wks]         1  cpz6_treatment_12wks_recovery_6wks    False
17     34                           [ctl_18wks]         1                           ctl_18wks     True
18     35                           [ctl_18wks]         1                           ctl_18wks     True
19     36                           [ctl_18wks]         1                           ctl_18wks     True
dandiset mice matched to exactly one group folder: 20 of 20
mice per group folder in the dandiset: {'cpz6_treatment_6wks': 3, 'cpz6_treatement_12wks': 3, 'ctl_12wks': 3, 'cpz6_treatment_6wks_recovery_6wks': 3, 'cpz6_treatment_12wks_recovery_6wks': 3, 'ctl_18wks': 3, 'ctl_6wks': 2}
mice per group folder on OSF: {'cpz6_treatement_12wks': 6, 'cpz6_treatment_12wks_recovery_6wks': 6, 'cpz6_treatment_6wks': 6, 'cpz6_treatment_6wks_recovery_6wks': 6, 'ctl_12wks': 3, 'ctl_18wks': 3, 'ctl_6wks': 3}
controls: [7, 9, 25, 26, 27, 34, 35, 36] | cuprizone: [10, 11, 12, 13, 14, 15, 28, 29, 30, 31, 32, 33]
In [10]:
# Content: for each matched mouse whose OSF folder holds full-size micrographs, up to four of them
# (in name order, max_files=4 in osf_thumbnails) are compared with every dandiset image by thumbnail correlation.
shape = (int(res.height.iloc[0]), int(res.width.iloc[0]))
rows = []
for _, fr in osf[osf.mouse.isin(dmice)].iterrows():
    files = ads.osf_files(fr.files_url)
    modified = dict(zip(files.id, files.modified))
    for name, fid, oshape, th in ads.osf_thumbnails(files, shape):
        if th is None:
            rows.append({"osf_folder": fr.mouse_folder, "file": name, "shape": oshape, "note": "smaller than the dandiset images"})
            continue
        b = ads.best_match(th, list(res.thumb))
        i = int(np.argmax(b))
        same = b[(res.mouse == fr.mouse).values]
        other = b[(res.mouse != fr.mouse).values]
        rows.append({"osf_folder": fr.mouse_folder, "file": name, "id": fid, "modified": str(modified.get(fid))[:10], "shape": oshape,
                     "best_image": f"{res.subject[i]} {res['sample'][i]}", "r_best": round(float(b[i]), 3),
                     "best_same_mouse_r": round(float(same.max()), 3), "best_other_mouse_r": round(float(other.max()), 3)})
content = pd.DataFrame(rows)
print(content.to_string())
ok = content.dropna(subset=["r_best"]).copy()
ok["mouse"] = ok.osf_folder.str.extract(r"^(\d+)")[0].astype(int)
ok["best_mouse"] = ok.best_image.str.extract(r"nyuMouse(\d+)")[0].astype(int)
cp = ok[ok.r_best > 0.5]
print("OSF micrographs compared:", len(ok), "from", ok.mouse.nunique(), "mice | with a counterpart (r > 0.5):", len(cp),
      "| counterpart of the same mouse:", int((cp.mouse == cp.best_mouse).sum()),
      "| of another mouse:", int((cp.mouse != cp.best_mouse).sum()))
print("mice with at least one counterpart:", sorted(cp.mouse.unique()), "| mice checked without one:",
      sorted(set(ok.mouse) - set(cp.mouse)))
print("r of counterparts: %.3f to %.3f; largest r of the others: %.3f" % (
      cp.r_best.min(), cp.r_best.max(), ok[ok.r_best <= 0.5].r_best.max() if (ok.r_best <= 0.5).any() else float("nan")))
print("modification dates of the compared OSF micrographs:", sorted(ok.modified.unique()))
print("matched dandiset mice whose OSF folders hold no full-size micrograph:",
      sorted(set(dmice) - set(ok.mouse)))
   osf_folder        file                        id    modified            shape                  best_image  r_best  best_same_mouse_r  best_other_mouse_r
0         25S    0001.tif  58b9b90b594d9001fa4fd71b  2017-03-03  (2486, 3762, 3)  sub-nyuMouse25 sample-0001   0.836              0.836               0.114
1         25S    0002.tif  58b9b90e9ad5a101fcdf14e3  2017-03-03  (2486, 3762, 3)  sub-nyuMouse30 sample-0004   0.189              0.073               0.189
2         25S    0003.tif  58b9b9176c613b01efbb2a32  2017-03-03  (2486, 3762, 3)  sub-nyuMouse25 sample-0003   0.844              0.844               0.141
3         25S    0004.tif  58b9b9269ad5a101fddf14af  2017-03-03  (2486, 3762, 3)  sub-nyuMouse25 sample-0004   0.864              0.864               0.151
4         26S    0001.tif  58b9bb5a594d9001fb4fd732  2017-03-03  (2486, 3762, 3)  sub-nyuMouse26 sample-0001   0.837              0.837               0.118
5         26S    0002.tif  58b9bb7e9ad5a101fadf146c  2017-03-03  (2486, 3762, 3)  sub-nyuMouse26 sample-0002   0.888              0.888               0.187
6         26S    0003.tif  58b9bb81594d9001fa4fd732  2017-03-03  (2486, 3762, 3)  sub-nyuMouse26 sample-0003   0.810              0.810               0.164
7         26S    0004.tif  58b9bb9a6c613b01f2bb2a87  2017-03-03  (2486, 3762, 3)  sub-nyuMouse26 sample-0004   0.778              0.778               0.141
8         27S    0001.tif  58b9c1636c613b01f4bb2b25  2017-03-03  (2486, 3762, 3)  sub-nyuMouse27 sample-0001   0.851              0.851               0.137
9         27S    0002.tif  58b9c1629ad5a101fbdf1459  2017-03-03  (2486, 3762, 3)  sub-nyuMouse27 sample-0002   0.885              0.885               0.127
10        27S    0006.tif  58b9c166594d9001fa4fd753  2017-03-03  (2486, 3762, 3)  sub-nyuMouse27 sample-0006   0.889              0.889               0.156
11        27S    0007.tif  58b9c15cb83f6901f3b47b36  2017-03-03  (2486, 3762, 3)  sub-nyuMouse27 sample-0007   0.903              0.903               0.137
12        7SG    7G_1.tif  58bde89e6c613b01f43b3aaa  2017-03-06  (2486, 3762, 3)  sub-nyuMouse09 sample-0007   0.128              0.081               0.128
13        7SG   7S_12.tif  58bde8a2b83f6901f2271df0  2017-03-06  (2486, 3762, 3)  sub-nyuMouse30 sample-0009   0.129              0.089               0.129
14        7SG   7S_13.tif  58bde8ba6c613b01f43b3aac  2017-03-06  (2486, 3762, 3)  sub-nyuMouse13 sample-0007   0.229              0.123               0.229
15        7SG   7S_14.tif  58bde8b39ad5a101fe00eb99  2017-03-06  (2486, 3762, 3)  sub-nyuMouse10 sample-0004   0.261              0.203               0.261
16        9SC   9G_11.tif  58bde9a1b83f6901f3271e5a  2017-03-06  (2486, 3762, 3)  sub-nyuMouse15 sample-0003   0.157              0.111               0.157
17        9SC   9G_13.tif  58bde99ab83f6901f4271dfa  2017-03-06  (2486, 3762, 3)  sub-nyuMouse30 sample-0002   0.160              0.084               0.160
18        9SC    9G_4.tif  58bde994b83f6901f4271df8  2017-03-06  (2486, 3762, 3)  sub-nyuMouse07 sample-0004   0.170              0.115               0.170
19        9SC    9G_7.tif  58bde998b83f6901f2271e08  2017-03-06  (2486, 3762, 3)  sub-nyuMouse28 sample-0009   0.226              0.131               0.226
20        28S    0001.tif  58b9d5b06c613b01fc713f19  2017-03-03  (2486, 3762, 3)  sub-nyuMouse28 sample-0001   0.744              0.744               0.167
21       13SG   13S_6.tif  58bdf4649ad5a101ff00ed69  2017-03-06  (2486, 3762, 3)  sub-nyuMouse13 sample-0006   0.593              0.593               0.176
22       13SG   13S_7.tif  58bdf468b83f6901f1272037  2017-03-06  (2486, 3762, 3)  sub-nyuMouse13 sample-0007   0.487              0.487               0.128
23       14SG   14S_5.tif  58bdf52bb83f6901f0271cb0  2017-03-06  (2486, 3762, 3)  sub-nyuMouse14 sample-0005   0.830              0.830               0.165
24       15SG   15S_1.tif  58bdf5f7b83f6901ee271def  2017-03-06  (2486, 3762, 3)  sub-nyuMouse15 sample-0001   0.839              0.839               0.139
25       15SG  15S_11.tif  58bdf5f69ad5a101ff00ed84  2017-03-06  (2486, 3762, 3)  sub-nyuMouse09 sample-0006   0.127              0.110               0.127
26       15SG  15S_12.tif  58bdf607b83f6901ee271df1  2017-03-06  (2486, 3762, 3)  sub-nyuMouse36 sample-0007   0.146              0.073               0.146
27       15SG  15S_13.tif  58bdf6069ad5a1020000eaa4  2017-03-06  (2486, 3762, 3)  sub-nyuMouse07 sample-0002   0.153              0.084               0.153
28        10G    0011.tif  58bdf95a9ad5a101fa00ec22  2017-03-07  (2486, 3762, 3)  sub-nyuMouse13 sample-0008   0.161              0.082               0.161
29        10G   10G_1.tif  58bdf8f99ad5a101fb00eb91  2017-03-07  (2486, 3762, 3)  sub-nyuMouse28 sample-0004   0.206              0.085               0.206
30        10G   10G_2.tif  58bdf90cb83f6901f2271f0a  2017-03-07  (2486, 3762, 3)  sub-nyuMouse10 sample-0005   0.272              0.272               0.266
31        10G   10G_3.tif  58bdf90c9ad5a101fa00ec1e  2017-03-07  (2486, 3762, 3)  sub-nyuMouse15 sample-0002   0.164              0.124               0.164
32        10S    0021.tif  58bdf9cdb83f6901ef271d94  2017-03-07  (2486, 3762, 3)  sub-nyuMouse11 sample-0008   0.208              0.076               0.208
33        10S  10S_10.tif  58bdf9786c613b01ef3b3b8d  2017-03-07  (2486, 3762, 3)  sub-nyuMouse10 sample-0006   0.184              0.184               0.165
34        10S   10S_7.tif  58bdf970594d9001f4b59b26  2017-03-07  (2486, 3762, 3)  sub-nyuMouse10 sample-0007   0.800              0.800               0.136
35        10S   10S_9.tif  58bdf96b9ad5a1020000eace  2017-03-07  (2486, 3762, 3)  sub-nyuMouse32 sample-0001   0.134              0.105               0.134
36        11G    0012.tif  58bdfa309ad5a101fc00ea8f  2017-03-07  (2486, 3762, 3)  sub-nyuMouse07 sample-0004   0.237              0.193               0.237
37        11G    0013.tif  58bdfa39b83f6901f5271e3f  2017-03-07  (2486, 3762, 3)  sub-nyuMouse07 sample-0001   0.200              0.111               0.200
38        11G    0018.tif  58bdfa3e6c613b01f53b3cbb  2017-03-07  (2486, 3762, 3)  sub-nyuMouse10 sample-0006   0.202              0.120               0.202
OSF micrographs compared: 39 from 11 mice | with a counterpart (r > 0.5): 16 | counterpart of the same mouse: 16 | of another mouse: 0
mice with at least one counterpart: [np.int64(10), np.int64(13), np.int64(14), np.int64(15), np.int64(25), np.int64(26), np.int64(27), np.int64(28)] | mice checked without one: [7, 9, 11]
r of counterparts: 0.593 to 0.903; largest r of the others: 0.487
modification dates of the compared OSF micrographs: ['2017-03-03', '2017-03-06', '2017-03-07']
matched dandiset mice whose OSF folders hold no full-size micrograph: [np.int64(12), np.int64(29), np.int64(30), np.int64(31), np.int64(32), np.int64(33), np.int64(34), np.int64(35), np.int64(36)]

Result: reproduced. All 20 dandiset mice are matched by number to exactly one group folder of the NYU component of the White Matter Microscopy Database, and no group folder holds more than 3 dandiset mice (the control group at 6 weeks holds 2: mouse 17 is not in the dandiset). Of 39 OSF micrographs compared, 16 have a counterpart in the dandiset (r from 0.593 to 0.903), every one an image of the same mouse, from 8 of the 11 mice checked; the others correlate at most 0.487 with any dandiset image, as expected for the OSF images the dandiset does not hold. Nine dandiset mice (12 and 29 to 36) have no full-size micrograph on OSF, so they are linked by number alone. The link gives 8 control mice (7, 9, 25, 26, 27, 34, 35, 36) and 12 cuprizone mice.

Per-image scores, and the test-set readings¶

The paper's test set is 8 images from each of 3 mice not used for training (Table 1). The dandiset holds the 20 mice of the paper's training and test sets together, without saying which 3 were tested. The claims name two readings: (a) every image of the dandiset, and (b) the images of the control mice only. The results for the cuprizone mice apart, per mouse, and, as a variant, the range over every possible set of 3 mice (all 1140), are shown too.

In [11]:
res["control"] = res.mouse.map(dict(zip(link.mouse, link.control)))
res["group"] = res.mouse.map(dict(zip(link.mouse, link.group)))
M = ["axon_dice", "myelin_dice", "accuracy", "sensitivity", "precision"]
EXPECTED = {"accuracy": (0.9451, 0.0945), "axon_dice": (0.9493, 0.0949), "myelin_dice": (0.8552, 0.0855),
            "sensitivity": (0.9597, 0.0960), "precision": (0.9647, 0.0965)}
readings = {"(a) all images": res, "(b) control mice": res[res.control], "cuprizone mice (not a reading)": res[~res.control]}

def summary(tag):
    rows = {}
    for name, d in readings.items():
        rows[name] = {"images": len(d), "mice": d.mouse.nunique(), **{m: d[f"{tag}_{m}"].mean() for m in M}}
    return pd.DataFrame(rows).T

per_mouse = res.groupby(["mouse", "group"])[[f"inv_{m}" for m in M]].mean().round(4)
per_mouse.columns = M
print("Per mouse, contrast inverted (segment.py):")
print(per_mouse.to_string())
mouse_means = res.groupby("mouse")[[f"inv_{m}" for m in M]].mean()
mouse_n = res.groupby("mouse").size()
combos = list(itertools.combinations(mouse_means.index, 3))
sub = {m: [] for m in M}
for c in combos:
    w = mouse_n[list(c)].values
    for m in M:
        sub[m].append(np.average(mouse_means.loc[list(c), f"inv_{m}"].values, weights=w))
ctl_mice = list(link.mouse[link.control])
ctl_combos = [c for c in combos if set(c) <= set(ctl_mice)]
print(len(combos), "sets of 3 mice;", len(ctl_combos), "of them all controls")
Per mouse, contrast inverted (segment.py):
                                          axon_dice  myelin_dice  accuracy  sensitivity  precision
mouse group                                                                                       
7     ctl_6wks                               0.9385       0.8176    0.9396       0.9794     0.9711
9     ctl_6wks                               0.9333       0.8382    0.9311       0.9709     0.9765
10    cpz6_treatment_6wks                    0.9480       0.8401    0.9687       0.9975     0.9975
11    cpz6_treatment_6wks                    0.9401       0.8300    0.9241       0.9949     0.9418
12    cpz6_treatment_6wks                    0.9280       0.8048    0.9230       0.9682     0.9502
13    cpz6_treatement_12wks                  0.9532       0.8460    0.9740       0.9934     0.9636
14    cpz6_treatement_12wks                  0.9631       0.8710    0.9624       0.9864     0.9717
15    cpz6_treatement_12wks                  0.9443       0.8368    0.9340       0.9842     0.9094
25    ctl_12wks                              0.9542       0.8703    0.9202       0.9882     0.9743
26    ctl_12wks                              0.9651       0.8762    0.9376       0.9965     0.9869
27    ctl_12wks                              0.9627       0.8719    0.9299       0.9855     0.9798
28    cpz6_treatment_6wks_recovery_6wks      0.9286       0.8364    0.9267       0.9774     0.9401
29    cpz6_treatment_6wks_recovery_6wks      0.9517       0.8663    0.9518       0.9878     0.9814
30    cpz6_treatment_6wks_recovery_6wks      0.9558       0.8518    0.9370       0.9885     0.9779
31    cpz6_treatment_12wks_recovery_6wks     0.9609       0.8400    0.9592       0.9855     0.9936
32    cpz6_treatment_12wks_recovery_6wks     0.9428       0.8518    0.9488       0.9788     0.9776
33    cpz6_treatment_12wks_recovery_6wks     0.9502       0.8482    0.9410       0.9819     0.9559
34    ctl_18wks                              0.9588       0.8572    0.9511       0.9935     0.9935
35    ctl_18wks                              0.9545       0.8550    0.9243       0.9968     0.9848
36    ctl_18wks                              0.9672       0.8735    0.9415       0.9920     0.9866
1140 sets of 3 mice; 56 of them all controls

table3-tem-mice-accuracy¶

The TEM model trained on mouse images segments the mouse test images with a mean three-class pixel-wise accuracy of 95% (0.9451 in Table 3, mean over 24 test images).

Expected 0.9451, tolerance 0.0945 (0.8506 to 1.0396).

In [12]:
lo, hi = EXPECTED["accuracy"][0] - EXPECTED["accuracy"][1], EXPECTED["accuracy"][0] + EXPECTED["accuracy"][1]
s_inv, s_no = summary("inv"), summary("noinv")
print("Contrast inverted once (segment.py):")
print(s_inv[["images", "mice", "accuracy"]].round(4).to_string())
print("Variant, no inversion:")
print(s_no[["images", "mice", "accuracy"]].round(4).to_string())
for name in ["(a) all images", "(b) control mice"]:
    v = s_inv.loc[name, "accuracy"]
    print(f"{name}: {v:.4f}, within {lo:.4f} to {hi:.4f}: {lo <= v <= hi}")
print("per-image accuracy: %.4f to %.4f (median %.4f); per-mouse means %.4f to %.4f" % (
      res.inv_accuracy.min(), res.inv_accuracy.max(), res.inv_accuracy.median(),
      per_mouse.accuracy.min(), per_mouse.accuracy.max()))
print("over all 1140 sets of 3 mice: %.4f to %.4f; over the %d sets of 3 control mice: %.4f to %.4f" % (
      min(sub["accuracy"]), max(sub["accuracy"]), len(ctl_combos),
      min(sub["accuracy"][combos.index(c)] for c in ctl_combos), max(sub["accuracy"][combos.index(c)] for c in ctl_combos)))
print("images below the lower bound %.4f: %d of %d" % (lo, int((res.inv_accuracy < lo).sum()), len(res)))
print("Variant, ground truth with the 2025 delineation lines filled (fill_delineation): pixels changed per image "
      "%.4f to %.4f (median %.4f); images with no pixel changed: %d" % (
      res.fill_frac.min(), res.fill_frac.max(), res.fill_frac.median(), int((res.fill_frac == 0).sum())))
for name in ["(a) all images", "(b) control mice"]:
    d = readings[name]
    print(f"  {name}: accuracy {d.fill_accuracy.mean():.4f} (against {d.inv_accuracy.mean():.4f} with the dandiset's masks)")
Contrast inverted once (segment.py):
                                images  mice  accuracy
(a) all images                   158.0  20.0    0.9416
(b) control mice                  62.0   8.0    0.9349
cuprizone mice (not a reading)    96.0  12.0    0.9459
Variant, no inversion:
                                images  mice  accuracy
(a) all images                   158.0  20.0    0.5027
(b) control mice                  62.0   8.0    0.3934
cuprizone mice (not a reading)    96.0  12.0    0.5733
(a) all images: 0.9416, within 0.8506 to 1.0396: True
(b) control mice: 0.9349, within 0.8506 to 1.0396: True
per-image accuracy: 0.8954 to 0.9884 (median 0.9395); per-mouse means 0.9202 to 0.9740
over all 1140 sets of 3 mice: 0.9226 to 0.9683; over the 56 sets of 3 control mice: 0.9252 to 0.9441
images below the lower bound 0.8506: 0 of 158
Variant, ground truth with the 2025 delineation lines filled (fill_delineation): pixels changed per image 0.0000 to 0.0058 (median 0.0012); images with no pixel changed: 0
  (a) all images: accuracy 0.9427 (against 0.9416 with the dandiset's masks)
  (b) control mice: accuracy 0.9366 (against 0.9349 with the dandiset's masks)
In [13]:
fig, ax = plt.subplots(1, 2, figsize=(11, 3.5))
order = per_mouse.sort_values("accuracy").index
for i, (key, d) in enumerate(res.groupby("mouse")):
    ax[0].scatter(np.full(len(d), list(order.get_level_values(0)).index(key)), d.inv_accuracy,
                  c="tab:blue" if d.control.iloc[0] else "tab:orange", s=12)
ax[0].axhspan(lo, min(hi, 1.0), color="0.9", zorder=0)
ax[0].axhline(0.9451, color="k", lw=0.8)
ax[0].set_xticks(range(len(order)), [str(m) for m in order.get_level_values(0)], fontsize=7)
ax[0].set_xlabel("mouse (blue control, orange cuprizone)"); ax[0].set_ylabel("pixel-wise accuracy")
ax[0].set_ylim(0.85, 1.0)
ax[1].hist(sub["accuracy"], bins=30, color="0.5")
ax[1].axvline(0.9451, color="k", lw=0.8)
ax[1].set_xlabel("mean accuracy, every set of 3 mice"); ax[1].set_ylabel("sets")
plt.tight_layout(); plt.show()
print("left panel: %d images, accuracy %.4f to %.4f; points below 0.85 (outside the axis): %d" % (
      len(res), res.inv_accuracy.min(), res.inv_accuracy.max(), int((res.inv_accuracy < 0.85).sum())))
print("right panel: %d sets, %.4f to %.4f" % (len(sub["accuracy"]), min(sub["accuracy"]), max(sub["accuracy"])))
No description has been provided for this image
left panel: 158 images, accuracy 0.8954 to 0.9884; points below 0.85 (outside the axis): 0
right panel: 1140 sets, 0.9226 to 0.9683

Result: reproduced. The mean pixel-wise accuracy is 0.9416 over all 158 images (reading a) and 0.9349 over the 62 images of the 8 control mice (reading b), both inside 0.8506 to 1.0396; the cuprizone mice give 0.9459. Every set of 3 mice, which includes the paper's unnamed test set, gives 0.9226 to 0.9683, and no single image is below the lower bound (lowest 0.8954), so the outcome does not depend on which mice the paper tested. Both readings include images of the mice the model was trained on, so the match is weaker evidence than a test on the paper's held-out mice. If the dandiset's 20 mice are the paper's 20, 12 of them cuprizone mice, then the paper's training set held cuprizone tissue, which bears on reading (b) and its premise of healthy tissue; this does not change the outcome, as every set of 3 mice passes. With the 2025 delineation lines filled in the ground truth (a variant for the masks the paper scored against, which are not public) the accuracy is 0.9427 (a) and 0.9366 (b), within 0.002 of the values with the dandiset's masks. Without the contrast inversion the accuracy falls to 0.5027 (a) and 0.3934 (b): the inversion that segment.py applies for this model is needed.

table3-tem-mice-dice-detection¶

On the mouse test images the TEM model reaches a mean axon Dice of 0.9493, a mean myelin Dice of 0.8552, a mean axon detection sensitivity of 0.9597 and a mean precision of 0.9647.

Tolerance 10% of each value.

In [14]:
q = ["axon_dice", "myelin_dice", "sensitivity", "precision"]
for name in ["(a) all images", "(b) control mice", "cuprizone mice (not a reading)"]:
    within = []
    for m in q:
        v = s_inv.loc[name, m]; e, t = EXPECTED[m]
        within.append(abs(v - e) <= t)
        print(f"{name:32s} {m:12s} {v:.4f}  expected {e} +/- {t}  within: {abs(v - e) <= t}")
    print(f"{name}: {sum(within)} of 4 within tolerance")
print("Variant, no inversion:")
print(s_no[q].round(4).to_string())
print("per-image ranges:", {m: (round(res[f'inv_{m}'].min(), 4), round(res[f'inv_{m}'].max(), 4)) for m in q})
print("per-mouse ranges:", {m: (round(per_mouse[m].min(), 4), round(per_mouse[m].max(), 4)) for m in q})
print("over all 1140 sets of 3 mice:", {m: (round(min(sub[m]), 4), round(max(sub[m]), 4)) for m in q})
for name, d in readings.items():
    print(f"{name}: ground-truth axons {int(d.inv_P.sum())}, detected (TP) {int(d.inv_TP.sum())}, false positives {int(d.inv_FP.sum())}")
print("Variant, ground truth with the 2025 delineation lines filled: mean myelin Dice",
      {name: round(readings[name].fill_myelin_dice.mean(), 4) for name in ["(a) all images", "(b) control mice"]},
      "| axon Dice, sensitivity and precision are unchanged, as the filled pixels become myelin")
(a) all images                   axon_dice    0.9500  expected 0.9493 +/- 0.0949  within: True
(a) all images                   myelin_dice  0.8489  expected 0.8552 +/- 0.0855  within: True
(a) all images                   sensitivity  0.9863  expected 0.9597 +/- 0.096  within: True
(a) all images                   precision    0.9707  expected 0.9647 +/- 0.0965  within: True
(a) all images: 4 of 4 within tolerance
(b) control mice                 axon_dice    0.9543  expected 0.9493 +/- 0.0949  within: True
(b) control mice                 myelin_dice  0.8571  expected 0.8552 +/- 0.0855  within: True
(b) control mice                 sensitivity  0.9878  expected 0.9597 +/- 0.096  within: True
(b) control mice                 precision    0.9819  expected 0.9647 +/- 0.0965  within: True
(b) control mice: 4 of 4 within tolerance
cuprizone mice (not a reading)   axon_dice    0.9472  expected 0.9493 +/- 0.0949  within: True
cuprizone mice (not a reading)   myelin_dice  0.8436  expected 0.8552 +/- 0.0855  within: True
cuprizone mice (not a reading)   sensitivity  0.9854  expected 0.9597 +/- 0.096  within: True
cuprizone mice (not a reading)   precision    0.9634  expected 0.9647 +/- 0.0965  within: True
cuprizone mice (not a reading): 4 of 4 within tolerance
Variant, no inversion:
                                axon_dice  myelin_dice  sensitivity  precision
(a) all images                     0.0029       0.0006       0.0114     0.3169
(b) control mice                   0.0029       0.0003       0.0085     0.4980
cuprizone mice (not a reading)     0.0029       0.0008       0.0133     0.1886
per-image ranges: {'axon_dice': (np.float64(0.9062), np.float64(0.971)), 'myelin_dice': (np.float64(0.7779), np.float64(0.9015)), 'sensitivity': (np.float64(0.898), np.float64(1.0)), 'precision': (np.float64(0.778), np.float64(1.0))}
per-mouse ranges: {'axon_dice': (np.float64(0.928), np.float64(0.9672)), 'myelin_dice': (np.float64(0.8048), np.float64(0.8762)), 'sensitivity': (np.float64(0.9682), np.float64(0.9975)), 'precision': (np.float64(0.9094), np.float64(0.9975))}
over all 1140 sets of 3 mice: {'axon_dice': (np.float64(0.93), np.float64(0.9651)), 'myelin_dice': (np.float64(0.8175), np.float64(0.8739)), 'sensitivity': (np.float64(0.9722), np.float64(0.9969)), 'precision': (np.float64(0.9304), np.float64(0.9949))}
(a) all images: ground-truth axons 7868, detected (TP) 7757, false positives 239
(b) control mice: ground-truth axons 3900, detected (TP) 3853, false positives 70
cuprizone mice (not a reading): ground-truth axons 3968, detected (TP) 3904, false positives 169
Variant, ground truth with the 2025 delineation lines filled: mean myelin Dice {'(a) all images': np.float64(0.8521), '(b) control mice': np.float64(0.8611)} | axon Dice, sensitivity and precision are unchanged, as the filled pixels become myelin

Result: reproduced. Under reading (a) the means are axon Dice 0.9500, myelin Dice 0.8489, sensitivity 0.9863 and precision 0.9707; under reading (b) 0.9543, 0.8571, 0.9878 and 0.9819. All four are within tolerance under both readings, and over every set of 3 mice each measure stays within its tolerance (axon Dice 0.9300 to 0.9651, myelin Dice 0.8175 to 0.8739, sensitivity 0.9722 to 0.9969, precision 0.9304 to 0.9949). Sensitivity and precision are above the paper's values under both readings. Without the inversion all four collapse (axon Dice 0.0029). With the 2025 delineation lines filled in the ground truth the mean myelin Dice is 0.8521 (a) and 0.8611 (b); the other three measures do not change.

myelin-dice-below-axon-dice¶

In both models and every test sample the myelin Dice is lower than the axon Dice, which the authors attribute to myelin having two boundaries (with the axon and with the background).

Tested on the mouse images only: (i) the means of a test set, (ii) every single image.

In [15]:
for name in ["(a) all images", "(b) control mice"]:
    d = readings[name]
    below = d.inv_myelin_dice < d.inv_axon_dice
    print(f"{name}: (i) mean myelin Dice {d.inv_myelin_dice.mean():.4f} < mean axon Dice {d.inv_axon_dice.mean():.4f}: "
          f"{d.inv_myelin_dice.mean() < d.inv_axon_dice.mean()}; (ii) single images with myelin below axon: "
          f"{int(below.sum())} of {len(d)}")
diff = res.inv_axon_dice - res.inv_myelin_dice
print("axon minus myelin Dice per image: %.4f to %.4f, median %.4f" % (diff.min(), diff.max(), diff.median()))
print("per mouse, myelin below axon in", int((per_mouse.myelin_dice < per_mouse.axon_dice).sum()), "of", len(per_mouse), "mice")
(a) all images: (i) mean myelin Dice 0.8489 < mean axon Dice 0.9500: True; (ii) single images with myelin below axon: 158 of 158
(b) control mice: (i) mean myelin Dice 0.8571 < mean axon Dice 0.9543: True; (ii) single images with myelin below axon: 62 of 62
axon minus myelin Dice per image: 0.0655 to 0.1556, median 0.0976
per mouse, myelin below axon in 20 of 20 mice

Result: reproduced on the mouse images. Myelin Dice is below axon Dice in the means of both readings (0.8489 against 0.9500, and 0.8571 against 0.9543) and in every one of the 158 single images (the difference ranges from 0.0655 to 0.1556). The SEM rows and the macaque row of Table 3 are not part of this test.

sensitivity-above-93¶

Axon detection sensitivity is above 93% in every test set.

Tested on the mouse images only, with the mean sensitivity under each test-set reading.

In [16]:
for name in ["(a) all images", "(b) control mice"]:
    v = readings[name].inv_sensitivity.mean()
    print(f"{name}: mean sensitivity {v:.4f}, above 0.93: {v > 0.93}")
print("images with sensitivity at or below 0.93: %d of %d (lowest %.3f)" % (
      int((res.inv_sensitivity <= 0.93).sum()), len(res), res.inv_sensitivity.min()))
print("lowest per-mouse mean %.4f; lowest over all 1140 sets of 3 mice %.4f" % (per_mouse.sensitivity.min(), min(sub["sensitivity"])))
(a) all images: mean sensitivity 0.9863, above 0.93: True
(b) control mice: mean sensitivity 0.9878, above 0.93: True
images with sensitivity at or below 0.93: 2 of 158 (lowest 0.898)
lowest per-mouse mean 0.9682; lowest over all 1140 sets of 3 mice 0.9722

Result: reproduced on the mouse images. The mean sensitivity is 0.9863 under reading (a) and 0.9878 under reading (b), above 0.93; the lowest per-mouse mean is 0.9682 and the lowest over every set of 3 mice 0.9722. Two of the 158 single images are at or below 0.93 (lowest 0.898). The SEM rows and the macaque row are not part of this test.

The SEM rat test images (data elsewhere)¶

The SEM test images are not in the dandiset. The AxonDeepSeg project publishes an SEM dataset, https://github.com/axondeepseg/data_axondeepseg_sem (DOI 10.5281/zenodo.5498378 in its dataset_description.json, whose authors include the paper's authors): 10 rat cervical spinal cord SEM images, "small cropped sections extracted from larger mosaic images" acquired from 2015 to 2017, with manual axon, myelin and axonmyelin masks. It is read here at commit d7884f9 (tag r20211130, the release archived under that DOI), the last before the masks of 6 samples were changed in 2025 to separate touching fibres; the 2025 masks are a variant. Each image is matched to the rows of Table 1 by pixel size, field of view and fixation. The images that match the two SEM test rows are segmented with the paper's default_SEM_model_v1 as segment.py does (0.1 um working pixel size for a 512 patch, generate_resolution; overlap 25; no contrast inversion, which segment.py applies only for default_TEM_model_v1).

In [17]:
sem_list = ads.sem_list()
print(sem_list.to_string())
# Table 1 of the paper, SEM rows: (role, number of images, pixel size in um, field of view in um2, fixation PFA-GA %)
TABLE1_SEM = [("training", 1, "0.18", "230 x 166", "4-2"), ("training", 3, "0.05 to 0.17", "132 x 90 to 218 x 162", "4-0"),
              ("training", 3, "0.1", "74 x 76 to 77 x 84", "3-3"), ("training", 1, "0.13", "247 x 234", "3-3"),
              ("training", 1, "0.1", "82 x 77", "3-3"), ("test Rat 1", 1, "0.13", "150 x 97", "3-3"),
              ("test Rat 2", 1, "0.07", "108 x 77", "3-3"), ("test Human", 1, "0.13", "715 x 735", "4-2")]
print(pd.DataFrame(TABLE1_SEM, columns=["Table 1 row", "images", "pixel_um", "fov_um2", "fixation"]).to_string())
for name, (subj, samp) in ads.SEM_TEST.items():
    r = sem_list[(sem_list.subject == subj) & (sem_list["sample"] == samp)].iloc[0]
    print(f"{name}: {subj} {samp}, {r.pixel_um} um, {r.width_px} x {r.height_px} px = {r.fov_um} um, fixation {r.fixation}")

sem_weights, sem_config = ads.load_tem_model(ads.SEM_MODEL_DIR)
print("SEM model: variables", len(sem_weights), {k: sem_config[k] for k in ["depth", "trainingset_patchsize", "n_classes", "convolution_per_layer"]})
sem_rows, sem_conf = [], {}
for name, (subj, samp) in ads.SEM_TEST.items():
    img, gt, masks, px, raw = ads.load_sem(subj, samp)
    print(f"{name}: image {raw.shape} {raw.dtype}, grey {img.min()} to {img.max()}" +
          (f", alpha values {np.unique(raw[..., 1]).tolist()}" if raw.ndim == 3 else "") +
          f"; mask values axon {np.unique(masks['axon']).tolist()}, myelin {np.unique(masks['myelin']).tolist()}, "
          f"axonmyelin {np.unique(masks['axonmyelin']).tolist()}; axonmyelin agrees with axon and myelin masks: "
          f"{bool(np.array_equal(masks['axonmyelin'] == 255, masks['axon'] > 127) and np.array_equal(masks['axonmyelin'] == 127, masks['myelin'] > 127))}; "
          f"class fractions bg, myelin, axon {np.round(np.bincount(gt.ravel(), minlength=3) / gt.size, 3).tolist()}")
    if name == "Rat 1":
        rs = rescale(img, px / ads.SEM_WORKING_PIXEL_UM, order=1, mode="constant", preserve_range=True,
                     anti_aliasing=False).astype(int)
        p_, pos_ = ads.im2patches_overlap(rs)
        mine_s, theirs_s = ads.unet_forward(sem_weights, sem_config, p_), ads.original_graph_output(p_, ads.SEM_MODEL_DIR)
        print(f"SEM network against its saved graph on the {len(p_)} patches of Rat 1: largest absolute difference "
              f"{float(np.abs(mine_s - theirs_s).max()):.2g}, same class on {float((mine_s.argmax(3) == theirs_s.argmax(3)).mean()):.4f} of pixels")
    stitched, rs_shape, n_patches = ads.segment_stitched(img, px, sem_weights, sem_config, invert=False,
                                                         working_um=ads.SEM_WORKING_PIXEL_UM)
    pred = ads.resize_back(stitched, img.shape)
    sem_conf[name] = ads.confusion(pred, gt)
    variants = {"segment.py": (pred, gt),
                "nearest-neighbour resize back": (ads.resize_back(stitched, img.shape, order=0), gt),
                "contrast inverted": (ads.segment(img, px, sem_weights, sem_config, invert=True,
                                                  working_um=ads.SEM_WORKING_PIXEL_UM)[0], gt)}
    img25, gt25, _, _, _ = ads.load_sem(subj, samp, mask_commit=ads.SEM_COMMIT_2025)
    print(f"{name}: image the same at both commits: {bool(np.array_equal(img25, img))}; 2025 masks differ on "
          f"{float(np.mean(gt25 != gt)):.4f} of pixels")
    if not np.array_equal(gt25, gt):
        variants["2025 masks"] = (pred, gt25)
    for v, (pv, gv) in variants.items():
        sem_rows.append({"sample": name, "variant": v, "resampled": rs_shape, "patches": n_patches, **ads.scores(pv, gv)})
sem = pd.DataFrame(sem_rows)
print(sem.drop(columns=["pred_axon_frac", "gt_axon_frac"]).round(4).to_string())
    subject              sample  pixel_um  height_px  width_px     fov_um                                fixation
0  sub-rat1        sample-data1     0.180        924      1278  230 x 166  4% paraformaldehyde, 2% glutaraldehyde
1  sub-rat2        sample-data5     0.093        954      1280   119 x 89  4% paraformaldehyde, 0% glutaraldehyde
2  sub-rat3       sample-data10     0.100        758       737    74 x 76  3% paraformaldehyde, 3% glutaraldehyde
3  sub-rat3       sample-data11     0.100        839       769    77 x 84  3% paraformaldehyde, 3% glutaraldehyde
4  sub-rat3        sample-data9     0.100        756       764    76 x 76  3% paraformaldehyde, 3% glutaraldehyde
5  sub-rat4       sample-data12     0.100        771       822    82 x 77  3% paraformaldehyde, 3% glutaraldehyde
6  sub-rat5       sample-data14     0.130       1801      1901  247 x 234  3% paraformaldehyde, 3% glutaraldehyde
7  sub-rat6       sample-data15     0.130        744      1154   150 x 97  3% paraformaldehyde, 3% glutaraldehyde
8  sub-rat7  sample-Maxo03img60     0.070       2001      2001  140 x 140                                     NaN
9  sub-rat8         sample-V915     0.070       1096      1541   108 x 77  3% paraformaldehyde, 3% glutaraldehyde
  Table 1 row  images      pixel_um                fov_um2 fixation
0    training       1          0.18              230 x 166      4-2
1    training       3  0.05 to 0.17  132 x 90 to 218 x 162      4-0
2    training       3           0.1     74 x 76 to 77 x 84      3-3
3    training       1          0.13              247 x 234      3-3
4    training       1           0.1                82 x 77      3-3
5  test Rat 1       1          0.13               150 x 97      3-3
6  test Rat 2       1          0.07               108 x 77      3-3
7  test Human       1          0.13              715 x 735      4-2
Rat 1: sub-rat6 sample-data15, 0.13 um, 1154 x 744 px = 150 x 97 um, fixation 3% paraformaldehyde, 3% glutaraldehyde
Rat 2: sub-rat8 sample-V915, 0.07 um, 1541 x 1096 px = 108 x 77 um, fixation 3% paraformaldehyde, 3% glutaraldehyde
SEM model: variables 162 {'depth': 4, 'trainingset_patchsize': 512, 'n_classes': 3, 'convolution_per_layer': [3, 3, 3, 3]}
Rat 1: image (744, 1154, 2) uint8, grey 2 to 252, alpha values [255]; mask values axon [0, 255], myelin [0, 255], axonmyelin [0, 127, 255]; axonmyelin agrees with axon and myelin masks: True; class fractions bg, myelin, axon [0.314, 0.397, 0.289]
INFO:tensorflow:Restoring parameters from /tmp/tmp9pmf37cf/model.ckpt
SEM network against its saved graph on the 8 patches of Rat 1: largest absolute difference 2.1e-05, same class on 1.0000 of pixels
Rat 1: image the same at both commits: True; 2025 masks differ on 0.0031 of pixels
Rat 2: image (1096, 1541) uint8, grey 2 to 252; mask values axon [0, 255], myelin [0, 255], axonmyelin [0, 127, 255]; axonmyelin agrees with axon and myelin masks: True; class fractions bg, myelin, axon [0.34, 0.349, 0.311]
Rat 2: image the same at both commits: True; 2025 masks differ on 0.0000 of pixels
  sample                        variant    resampled  patches  axon_dice  myelin_dice  accuracy  sensitivity  precision   TP  FP    P  pred_myelin_frac  gt_myelin_frac
0  Rat 1                     segment.py  (967, 1500)        8     0.9282       0.8720    0.8955        0.964      0.887  401  51  416            0.3491          0.3974
1  Rat 1  nearest-neighbour resize back  (967, 1500)        8     0.9171       0.8696    0.8923        0.966      0.884  402  53  416            0.3546          0.3974
2  Rat 1              contrast inverted  (967, 1500)        8     0.0197       0.0076    0.3047        0.070      0.509   29  28  416            0.0365          0.3974
3  Rat 1                     2025 masks  (967, 1500)        8     0.9283       0.8694    0.8940        0.964      0.887  401  51  416            0.3491          0.3943
4  Rat 2                     segment.py  (767, 1079)        6     0.9186       0.8309    0.8757        0.979      0.801  238  59  243            0.3438          0.3490
5  Rat 2  nearest-neighbour resize back  (767, 1079)        6     0.9319       0.8597    0.8937        0.984      0.797  239  61  243            0.3485          0.3490
6  Rat 2              contrast inverted  (767, 1079)        6     0.0065       0.0017    0.3220        0.037      0.360    9  16  243            0.0252          0.3490

table3-sem-rat-accuracy¶

The SEM model trained on rat spinal cord reaches a pixel-wise accuracy between 85% and 88% on the two rat test images (0.8510 and 0.8822 in Table 3).

Expected 0.8510 +/- 0.0851 (Rat 1) and 0.8822 +/- 0.0882 (Rat 2), on the images matched above.

In [18]:
SEM_EXPECTED = {"Rat 1": (0.8510, 0.0851), "Rat 2": (0.8822, 0.0882)}
main = sem[sem.variant == "segment.py"].set_index("sample")
for name, (e, t) in SEM_EXPECTED.items():
    v = main.loc[name, "accuracy"]
    print(f"{name}: accuracy {v:.4f}, expected {e} +/- {t} ({e - t:.4f} to {e + t:.4f}), within: {abs(v - e) <= t}")
for v_ in sem.variant.unique():
    if v_ != "segment.py":
        print(f"variant {v_}: " + ", ".join(f"{r['sample']} {r.accuracy:.4f}" for _, r in sem[sem.variant == v_].iterrows()))
names = ["bg", "myelin", "axon"]
for name, cm in sem_conf.items():
    cm = cm / cm.sum()
    print(f"{name} confusion (fraction of pixels): " + "; ".join(
          f"gt {names[i]} -> " + ", ".join(f"{names[j]} {cm[i, j]:.3f}" for j in range(3)) for i in range(3)))
# Bearing on myelin-dice-below-axon-dice and sensitivity-above-93, whose criteria test the mouse images only.
for name, r in main.iterrows():
    print(f"{name}: myelin Dice {r.myelin_dice:.4f} below axon Dice {r.axon_dice:.4f}: {r.myelin_dice < r.axon_dice}; "
          f"sensitivity {r.sensitivity:.3f} above 0.93: {r.sensitivity > 0.93}")
Rat 1: accuracy 0.8955, expected 0.851 +/- 0.0851 (0.7659 to 0.9361), within: True
Rat 2: accuracy 0.8757, expected 0.8822 +/- 0.0882 (0.7940 to 0.9704), within: True
variant nearest-neighbour resize back: Rat 1 0.8923, Rat 2 0.8937
variant contrast inverted: Rat 1 0.3047, Rat 2 0.3220
variant 2025 masks: Rat 1 0.8940
Rat 1 confusion (fraction of pixels): gt bg -> bg 0.296, myelin 0.012, axon 0.007; gt myelin -> bg 0.050, myelin 0.325, axon 0.022; gt axon -> bg 0.002, myelin 0.012, axon 0.275
Rat 2 confusion (fraction of pixels): gt bg -> bg 0.309, myelin 0.024, axon 0.006; gt myelin -> bg 0.050, myelin 0.288, axon 0.011; gt axon -> bg 0.001, myelin 0.032, axon 0.279
Rat 1: myelin Dice 0.8720 below axon Dice 0.9282: True; sensitivity 0.964 above 0.93: True
Rat 2: myelin Dice 0.8309 below axon Dice 0.9186: True; sensitivity 0.979 above 0.93: True

Result: reproduced, resting on an assumption. The two images of the AxonDeepSeg SEM dataset that have the pixel size, field of view and fixation of Table 1's SEM test rows (rat 6, 0.13 um, 150 x 97 um, for Rat 1; rat 8, 0.07 um, 108 x 77 um, for Rat 2; six of the other eight match Table 1's training rows in all three, and rat 2 and rat 7 have the pixel size of the row of three images at 0.05 to 0.17 um) give a pixel-wise accuracy of 0.8955 (Rat 1) and 0.8757 (Rat 2), within 0.7659 to 0.9361 and 0.7940 to 0.9704. Rat 1's 0.8955 is above the statement's "between 85% and 88%", though inside the criterion's tolerance. The rebuilt SEM network agrees with its saved graph (largest difference below 1e-04, printed above, and the same class on every pixel). With the nearest-neighbour resize back the accuracy is 0.8923 and 0.8937, with the 2025 masks of Rat 1 0.8940, and with the contrast inverted 0.3047 and 0.3220. The data are not the dandiset's and are not named by the paper; they are tied to it by Table 1 only. The outcome assumes that these two images are the paper's Rat 1 and Rat 2 test images, which Table 1's pixel size, field of view and fixation support but do not prove. On both images the myelin Dice is below the axon Dice and the sensitivity is above 0.93 (0.964 and 0.979), which the criteria of myelin-dice-below-axon-dice and sensitivity-above-93 do not count, as they test the mouse images only.

The macaque image (data elsewhere)¶

The macaque TEM image of Table 3 is not in the dandiset. The White Matter Microscopy Database, which the paper's Data availability statement names, holds the macaque corpus callosum TEM images of ref. 7 (folder MontrealNeurologicalInstitute/histology/Macaque of OSF node yp4qg): eight samples of three images each, 2300 x 3040 pixels (20.7 x 27.4 um at the 0.009 um of Table 1, which gives 27 x 21 um2), and one myelin and one axon mask per sample. The paper names neither the sample nor the image it tested. Each mask is matched here to the image of its sample that it fits (myelin is the darkest structure, so the grey-level contrast between the rest of the image and the myelin mask is large for the right image and near 0 for the others), and every matched image is one reading of "the macaque test image".

What the deposit says about the macaque images¶

The deposit's own description, its wiki, and every entry of the macaque folder and its sub-folders, to see whether any of them names the image or the masks the paper used.

In [19]:
desc, pages = ads.osf_node_text()
print("node yp4qg description:", desc.replace("\n", " ")[:600])
for name, text in pages:
    print(f"wiki page {name!r}: {len(text)} characters; mentions macaque: {'macaque' in text.lower()}, "
          f"AxonDeepSeg: {'axondeepseg' in text.lower()}")
for path in [ads.MACAQUE_ROOT.rsplit("/", 2)[0], ads.MACAQUE_ROOT.rsplit("/", 1)[0], ads.MACAQUE_ROOT,
             ads.MACAQUE_ROOT + "/data", ads.MACAQUE_ROOT + "/segmentation"]:
    lst = ads.osf_listing(path)
    print(f"{path}: " + ", ".join(f"{r['name']} ({r.kind})" for _, r in lst.iterrows()))
node yp4qg description: The purpose of this repository is to provide a freely-accessible and curated microscopy data of white matter axons from the central and peripheral nervous system. This repository can be used for: - Training/Testing automatic methods for segmenting white matter microstructure - Documenting white matter microstructure across various species - Validating quantitative MRI methods (e.g., diffusion, magnetization transfer, etc.).  For more information about this project, please see this presentation: https://docs.google.com/presentation/d/1Ww8YaanjQ1tWNyL4AswHtgqDtkkCSVV8TnXkYqkRM5A/edit?usp=sharing
wiki page 'home': 1182 characters; mentions macaque: False, AxonDeepSeg: False
MontrealNeurologicalInstitute: histology (folder)
MontrealNeurologicalInstitute/histology: Macaque (folder)
MontrealNeurologicalInstitute/histology/Macaque: data (folder), segmentation (folder)
MontrealNeurologicalInstitute/histology/Macaque/data: sample1 (folder), sample2 (folder), sample3 (folder), sample4 (folder), sample5 (folder), sample6 (folder), sample7 (folder), sample8 (folder)
MontrealNeurologicalInstitute/histology/Macaque/segmentation: sample5 (folder), sample1 (folder), sample2 (folder), sample3 (folder), sample4 (folder), sample6 (folder), sample7 (folder), sample8 (folder)
In [20]:
mfiles = ads.osf_macaque_files()
print(mfiles.to_string())
mac_rows = []
for s in sorted(mfiles["sample"].unique()):
    seg = mfiles[(mfiles.kind == "segmentation") & (mfiles["sample"] == s)].set_index("name").id
    my = ads.read_osf_nifti(seg["myelin.nii"])
    ax = ads.read_osf_nifti(seg["avf.nii"])
    m = my > 0
    m_shift = np.roll(m, (50, 50), axis=(0, 1))
    cands = []
    for _, r in mfiles[(mfiles.kind == "data") & (mfiles["sample"] == s)].iterrows():
        im = ads.read_osf_nifti(r.id)
        cands.append((im[~m].mean() - im[m].mean(), im[~m_shift].mean() - im[m_shift].mean(), r["name"], im))
    for c, cs, name, im in cands:
        print(f"{s} {name}: shape {im.shape}, grey {im.min():.0f} to {im.max():.0f}, integer valued {bool(np.all(im == np.round(im)))}; "
              f"contrast {c:.1f}, with the mask shifted by 50 px {cs:.1f}")
    print(f"{s} masks: myelin values {np.unique(my).tolist()}, axon values {np.unique(ax).round(5).tolist()}, "
          f"pixels in both {int((m & (ax > 0)).sum())}")
    c, cs, name, im = max(cands, key=lambda t: t[0])
    row = {"sample": s, "image": name, "contrast": c, "contrast_shifted": cs, "matched": c > 20}
    if row["matched"]:
        gt = ads.macaque_ground_truth(my, ax)
        im8 = np.round(im).astype(np.uint8)
        for invert, tag in ((True, "inv"), (False, "noinv")):
            stitched, rs_shape, n_patches = ads.segment_stitched(im8, ads.MACAQUE_PIXEL_UM, weights, config, invert=invert)
            pred = ads.resize_back(stitched, im8.shape)
            row.update({f"{tag}_{k}": v for k, v in ads.scores(pred, gt).items()})
            if invert:
                row["confusion"] = ads.confusion(pred, gt)
                # Variant: nearest-neighbour resize back to the native shape (not the paper's code).
                row.update({f"nn_{k}": v for k, v in ads.scores(ads.resize_back(stitched, im8.shape, order=0), gt).items()})
        row["n_patches"] = n_patches
    mac_rows.append(row)
mac = pd.DataFrame(mac_rows)
print(mac[["sample", "image", "contrast", "contrast_shifted", "matched"]].round(1).to_string())
print("samples whose masks fit one of their images:", int(mac.matched.sum()), "of", len(mac))
            kind   sample        name                        id      size                    modified
0           data  sample1      01.nii  58bde00fb83f6901f1271f45  27968352  2017-03-06T22:17:52.027000
1           data  sample1      03.nii  58bde012b83f6901f3271df6  27968352  2017-03-06T22:17:54.294000
2           data  sample1      07.nii  58bde01a6c613b01f43b3a45  27968352  2017-03-06T22:18:02.512000
3           data  sample2      01.nii  58bde0229ad5a101fe00eb3c  27968352  2017-03-06T22:18:10.076000
4           data  sample2      03.nii  58bde0266c613b01f53b3b12  27968352  2017-03-06T22:18:14.278000
5           data  sample2      05.nii  58bde0236c613b01ef3b3a59  27968352  2017-03-06T22:18:11.128000
6           data  sample3      01.nii  58bde0339ad5a1020100e95a  27968352  2017-03-06T22:18:27.875000
7           data  sample3      03.nii  58bde037b83f6901ef271c56  27968352  2017-03-06T22:18:31.312000
8           data  sample3      05.nii  58bde037594d9001f3b598a3  27968352  2017-03-06T22:18:31.884000
9           data  sample4      01.nii  58bde03b9ad5a101ff00ec1e  27968352  2017-03-06T22:18:35.875000
10          data  sample4      05.nii  58bde039b83f6901f3271e02  27968352  2017-03-06T22:18:33.303000
11          data  sample4      07.nii  58bde0469ad5a101ff00ec20  27968352  2017-03-06T22:18:46.736000
12          data  sample5      01.nii  58bde055b83f6901ee271d05  27968352  2017-03-06T22:19:01.640000
13          data  sample5      03.nii  58bde04c6c613b01f43b3a47  27968352  2017-03-06T22:18:52.561000
14          data  sample5      05.nii  58bde0526c613b01f03b3b20  27968352  2017-03-06T22:18:58.470000
15          data  sample6      01.nii  58bde04a9ad5a101fa00eb57  27968352  2017-03-06T22:18:50.642000
16          data  sample6      03.nii  58bde0539ad5a101ff00ec22  27968352  2017-03-06T22:19:00.014000
17          data  sample6      05.nii  58bde056594d9001f2b59acc  27968352  2017-03-06T22:19:02.709000
18          data  sample7      01.nii  58bde066594d9001f4b599b4  27968352  2017-03-06T22:19:18.260000
19          data  sample7      03.nii  58bde0639ad5a101fb00ea60  27968352  2017-03-06T22:19:15.206000
20          data  sample7      05.nii  58bde0739ad5a101fb00ea63  27968352  2017-03-06T22:19:31.354000
21          data  sample8      01.nii  58bde0666c613b01f33b3bc0  27968352  2017-03-06T22:19:18.425000
22          data  sample8      03.nii  58bde065b83f6901f2271d76  27968352  2017-03-06T22:19:17.721000
23          data  sample8      05.nii  58bde070594d9001f4b599b8  27968352  2017-03-06T22:19:28.087000
24  segmentation  sample1     avf.nii  58bde10a9ad5a101fe00eb42  27968352  2017-03-06T22:22:02.658000
25  segmentation  sample1  myelin.nii  58bde10ab83f6901f3271e0b  27968352  2017-03-06T22:22:02.650000
26  segmentation  sample2     avf.nii  58bde111594d9001f2b59ade  27968352  2017-03-06T22:22:09.085000
27  segmentation  sample2  myelin.nii  58bde1246c613b01f23b3972  27968352  2017-03-06T22:22:28.912000
28  segmentation  sample3     avf.nii  58bde127594d9001f5b59935  27968352  2017-03-06T22:22:31.847000
29  segmentation  sample3  myelin.nii  58bde11f6c613b01f03b3b38  27968352  2017-03-06T22:22:23.663000
30  segmentation  sample4     avf.nii  58bde1246c613b01f13b3ae0  27968352  2017-03-06T22:22:28.947000
31  segmentation  sample4  myelin.nii  58bde12bb83f6901f2271d89  27968352  2017-03-06T22:22:35.508000
32  segmentation  sample5     avf.nii  58bde1309ad5a101fc00e9a4  27968352  2017-03-06T22:22:40.186000
33  segmentation  sample5  myelin.nii  58bde138b83f6901f4271dbe  27968352  2017-03-06T22:22:48.750000
34  segmentation  sample6     avf.nii  58bde1506c613b01f03b3b3a  27968352  2017-03-06T22:23:12.293000
35  segmentation  sample6  myelin.nii  58bde14c594d9001f3b598b0  27968352  2017-03-06T22:23:08.581000
36  segmentation  sample7     avf.nii  58bde153594d9001f1b59c5c  27968352  2017-03-06T22:23:15.040000
37  segmentation  sample7  myelin.nii  58bde153b83f6901ee271d08  27968352  2017-03-06T22:23:15.532000
38  segmentation  sample8     avf.nii  58bde15bb83f6901ee271d0a  27968352  2017-03-06T22:23:23.323000
39  segmentation  sample8  myelin.nii  58bde161b83f6901f3271e0e  27968352  2017-03-06T22:23:29.769000
sample1 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 61.7, with the mask shifted by 50 px 2.3
sample1 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 1.9, with the mask shifted by 50 px 1.9
sample1 07.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 3.2, with the mask shifted by 50 px 2.1
sample1 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample2 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 2.3, with the mask shifted by 50 px 2.2
sample2 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 80.6, with the mask shifted by 50 px 6.6
sample2 05.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 5.7, with the mask shifted by 50 px 2.8
sample2 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample3 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 3.4, with the mask shifted by 50 px 3.7
sample3 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 4.8, with the mask shifted by 50 px 3.7
sample3 05.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 57.9, with the mask shifted by 50 px 2.5
sample3 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample4 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 1.9, with the mask shifted by 50 px 3.2
sample4 05.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast -0.3, with the mask shifted by 50 px 0.6
sample4 07.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast -0.9, with the mask shifted by 50 px -0.9
sample4 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample5 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 1.4, with the mask shifted by 50 px 0.1
sample5 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast -0.3, with the mask shifted by 50 px 0.2
sample5 05.nii: shape (2300, 3040), grey 0 to 251, integer valued True; contrast 74.3, with the mask shifted by 50 px 6.4
sample5 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample6 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast -0.8, with the mask shifted by 50 px 0.5
sample6 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 72.7, with the mask shifted by 50 px 9.9
sample6 05.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 2.8, with the mask shifted by 50 px -0.6
sample6 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample7 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 95.5, with the mask shifted by 50 px 15.2
sample7 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast -1.0, with the mask shifted by 50 px -1.1
sample7 05.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 2.4, with the mask shifted by 50 px 2.6
sample7 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
sample8 01.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast -0.1, with the mask shifted by 50 px 0.5
sample8 03.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 108.0, with the mask shifted by 50 px 15.1
sample8 05.nii: shape (2300, 3040), grey 0 to 255, integer valued True; contrast 1.2, with the mask shifted by 50 px 0.6
sample8 masks: myelin values [0.0, 1.0], axon values [0.0, 0.00392], pixels in both 0
    sample   image    contrast  contrast_shifted  matched
0  sample1  01.nii   61.700001               2.3     True
1  sample2  03.nii   80.599998               6.6     True
2  sample3  05.nii   57.900002               2.5     True
3  sample4  01.nii    1.900000               3.2    False
4  sample5  05.nii   74.300003               6.4     True
5  sample6  03.nii   72.699997               9.9     True
6  sample7  01.nii   95.500000              15.2     True
7  sample8  03.nii  108.000000              15.1     True
samples whose masks fit one of their images: 7 of 8

table3-tem-macaque-accuracy¶

On the macaque corpus callosum TEM test image the mouse-trained TEM model reaches a pixel-wise accuracy of 84% (0.8438).

Expected 0.8438, tolerance 0.0844 (0.7594 to 0.9282). One reading per matched image.

In [21]:
mm = mac[mac.matched].set_index("sample")
lo_m, hi_m = 0.8438 - 0.0844, 0.8438 + 0.0844
cols = ["image", "inv_accuracy", "inv_axon_dice", "inv_myelin_dice", "inv_sensitivity", "inv_precision", "noinv_accuracy"]
print(mm[cols].round(4).to_string())
within = (mm.inv_accuracy >= lo_m) & (mm.inv_accuracy <= hi_m)
print(f"readings within {lo_m:.4f} to {hi_m:.4f}: {int(within.sum())} of {len(mm)} ({', '.join(mm.index[within])})")
print("accuracy over the readings: %.4f to %.4f, mean %.4f" % (mm.inv_accuracy.min(), mm.inv_accuracy.max(), mm.inv_accuracy.mean()))
print("Table 3, macaque row, for the other measures: axon Dice 0.9069, myelin Dice 0.7519, sensitivity 0.9429, precision 0.8129")
for m in ["axon_dice", "myelin_dice", "sensitivity", "precision"]:
    print(f"  {m}: {mm['inv_' + m].min():.4f} to {mm['inv_' + m].max():.4f}")
print("ground-truth axon objects per image:", mm.inv_P.astype(int).to_dict(), "| patches per image:", mm.n_patches.astype(int).to_dict())
print("Variant, nearest-neighbour resize back: accuracy %.4f to %.4f, axon Dice %.4f to %.4f, myelin Dice %.4f to %.4f" % (
      mm.nn_accuracy.min(), mm.nn_accuracy.max(), mm.nn_axon_dice.min(), mm.nn_axon_dice.max(),
      mm.nn_myelin_dice.min(), mm.nn_myelin_dice.max()))
print("Confusion matrices, fraction of the image's pixels (rows ground truth, columns prediction; bg, myelin, axon):")
names = ["bg", "myelin", "axon"]
for s_, r in mm.iterrows():
    cm = r.confusion / r.confusion.sum()
    print(f"{s_} {r.image}: " + "; ".join(f"gt {names[i]} -> " + ", ".join(f"{names[j]} {cm[i, j]:.3f}" for j in range(3)) for i in range(3)))
tot = sum(mm.confusion.values)
tot = tot / tot.sum()
print("all 7 images pooled: ground-truth myelin predicted as background %.3f, as axon %.3f, as myelin %.3f of all pixels; "
      "ground-truth axon predicted as background %.3f, as myelin %.3f; ground-truth background predicted as axon %.3f, as myelin %.3f" % (
      tot[1, 0], tot[1, 2], tot[1, 1], tot[2, 0], tot[2, 1], tot[0, 2], tot[0, 1]))
print("errors that are ground-truth myelin: %.3f of all misclassified pixels" % ((tot[1, 0] + tot[1, 2]) / (1 - np.trace(tot))))
          image  inv_accuracy  inv_axon_dice  inv_myelin_dice  inv_sensitivity  inv_precision  noinv_accuracy
sample                                                                                                       
sample1  01.nii        0.6809         0.7848           0.6095            0.606          0.691          0.1810
sample2  03.nii        0.7070         0.7777           0.6481            0.373          0.630          0.2236
sample3  05.nii        0.7634         0.7914           0.6321            0.316          0.525          0.3540
sample5  05.nii        0.7094         0.8070           0.6341            0.521          0.510          0.2130
sample6  03.nii        0.5729         0.6862           0.5119            0.289          0.428          0.1992
sample7  01.nii        0.6135         0.6268           0.5032            0.311          0.349          0.2823
sample8  03.nii        0.6591         0.6895           0.5761            0.515          0.458          0.2817
readings within 0.7594 to 0.9282: 1 of 7 (sample3)
accuracy over the readings: 0.5729 to 0.7634, mean 0.6723
Table 3, macaque row, for the other measures: axon Dice 0.9069, myelin Dice 0.7519, sensitivity 0.9429, precision 0.8129
  axon_dice: 0.6268 to 0.8070
  myelin_dice: 0.5032 to 0.6481
  sensitivity: 0.2890 to 0.6060
  precision: 0.3490 to 0.6910
ground-truth axon objects per image: {'sample1': 756, 'sample2': 960, 'sample3': 852, 'sample5': 480, 'sample6': 646, 'sample7': 631, 'sample8': 373} | patches per image: {'sample1': 30, 'sample2': 30, 'sample3': 30, 'sample5': 30, 'sample6': 30, 'sample7': 30, 'sample8': 30}
Variant, nearest-neighbour resize back: accuracy 0.5797 to 0.7678, axon Dice 0.6218 to 0.8033, myelin Dice 0.5071 to 0.6573
Confusion matrices, fraction of the image's pixels (rows ground truth, columns prediction; bg, myelin, axon):
sample1 01.nii: gt bg -> bg 0.164, myelin 0.002, axon 0.015; gt myelin -> bg 0.153, myelin 0.217, axon 0.119; gt axon -> bg 0.027, myelin 0.004, axon 0.300
sample2 03.nii: gt bg -> bg 0.206, myelin 0.003, axon 0.019; gt myelin -> bg 0.116, myelin 0.196, axon 0.088; gt axon -> bg 0.061, myelin 0.006, axon 0.305
sample3 05.nii: gt bg -> bg 0.343, myelin 0.005, axon 0.027; gt myelin -> bg 0.090, myelin 0.151, axon 0.075; gt axon -> bg 0.034, myelin 0.006, axon 0.269
sample5 05.nii: gt bg -> bg 0.201, myelin 0.002, axon 0.013; gt myelin -> bg 0.139, myelin 0.195, axon 0.079; gt axon -> bg 0.052, myelin 0.006, axon 0.314
sample6 03.nii: gt bg -> bg 0.191, myelin 0.001, axon 0.012; gt myelin -> bg 0.221, myelin 0.158, axon 0.074; gt axon -> bg 0.113, myelin 0.006, axon 0.224
sample7 01.nii: gt bg -> bg 0.281, myelin 0.001, axon 0.020; gt myelin -> bg 0.176, myelin 0.157, axon 0.128; gt axon -> bg 0.056, myelin 0.004, axon 0.175
sample8 03.nii: gt bg -> bg 0.285, myelin 0.001, axon 0.015; gt myelin -> bg 0.123, myelin 0.134, axon 0.066; gt axon -> bg 0.128, myelin 0.006, axon 0.240
all 7 images pooled: ground-truth myelin predicted as background 0.146, as axon 0.090, as myelin 0.173 of all pixels; ground-truth axon predicted as background 0.067, as myelin 0.005; ground-truth background predicted as axon 0.017, as myelin 0.002
errors that are ground-truth myelin: 0.719 of all misclassified pixels

Result: blocked (methods underspecified). The masks of 7 of the 8 macaque samples fit one of their images; those of sample 4 fit none of its three images. On the 7 matched images the pixel-wise accuracy ranges from 0.5729 to 0.7634: one reading (sample 3) is inside 0.7594 to 0.9282 and six are below it, so the readings disagree, and neither the paper nor the deposit says which image was tested (the deposit's description, wiki and folders, printed above, hold no description of the macaque images). The other measures are below Table 3's macaque row on every image (axon Dice 0.6268 to 0.8070 against 0.9069, myelin Dice 0.5032 to 0.6481 against 0.7519, sensitivity 0.289 to 0.606 against 0.9429). The errors are mostly ground-truth myelin: pooled over the 7 images, 0.146 of all pixels are ground-truth myelin predicted as background and 0.090 ground-truth myelin predicted as axon, 0.719 of all misclassified pixels, so the masks mark much more myelin than the model finds on both of its borders; 0.067 of the pixels are ground-truth axon predicted as background. With a nearest-neighbour resize back the accuracy is 0.5797 to 0.7678, so the resize step of the code does not explain the gap. The same TEM code, with the same contrast inversion and resize, reproduces the mouse rows of Table 3 (table3-tem-mice-accuracy and table3-tem-mice-dice-detection), so these masks, or these images, may not be the ones the paper scored; this is not shown, so the claim is not marked as not reproduced. Without the inversion the accuracy is 0.1810 to 0.3540.

macaque-myelin-underestimated¶

The TEM model slightly underestimates the myelin sheaths of the macaque sample compared with its ground truth.

The criterion's reading: the predicted myelin area is below the ground-truth myelin area.

In [22]:
ratio = mm.inv_pred_myelin_frac / mm.inv_gt_myelin_frac
print(pd.DataFrame({"pred_myelin_frac": mm.inv_pred_myelin_frac, "gt_myelin_frac": mm.inv_gt_myelin_frac,
                    "ratio": ratio, "pred_axon_frac": mm.inv_pred_axon_frac, "gt_axon_frac": mm.inv_gt_axon_frac}).round(3).to_string())
print("readings with predicted myelin area below the ground truth:", int((ratio < 1).sum()), "of", len(mm),
      "| ratio %.3f to %.3f" % (ratio.min(), ratio.max()))
mouse_ratio = res.inv_pred_myelin_frac / res.inv_gt_myelin_frac
print("for comparison, mouse images: ratio %.3f to %.3f, median %.3f" % (mouse_ratio.min(), mouse_ratio.max(), mouse_ratio.median()))
         pred_myelin_frac  gt_myelin_frac  ratio  pred_axon_frac  gt_axon_frac
sample                                                                        
sample1             0.223           0.489  0.455           0.434         0.330
sample2             0.205           0.401  0.512           0.412         0.372
sample3             0.162           0.316  0.512           0.371         0.309
sample5             0.203           0.413  0.491           0.405         0.372
sample6             0.165           0.454  0.364           0.310         0.343
sample7             0.162           0.461  0.352           0.324         0.236
sample8             0.142           0.324  0.438           0.321         0.374
readings with predicted myelin area below the ground truth: 7 of 7 | ratio 0.352 to 0.512
for comparison, mouse images: ratio 0.788 to 1.266, median 0.974

Result: reproduced, resting on an assumption. On all 7 matched macaque images the predicted myelin area is below the ground truth's. The underestimate is large: the predicted myelin fraction is 0.352 to 0.512 of the ground truth's, against 0.788 to 1.266 (median 0.974) on the mouse images, so the paper's "slightly" does not hold on these images. The criterion tests the direction only; whether it should also test the size is asked of a reader (questions/zaimi-2018.yaml). The direction comes from the same images and masks whose other measures are far from Table 3 (table3-tem-macaque-accuracy), so it carries little weight. The outcome assumes that the masks of ref. 7 in the White Matter Microscopy Database are the paper's macaque ground truth: the paper's macaque sample and its labels come from ref. 7 ("More details can be found about the generation of labels for the macaque 7", Methods, Ground truth labelling) and its Data availability statement names this database, but it does not say which masks it scored against, and the gap in the other measures leaves open that they differ. The direction holds on every one of the 7 images, so it does not depend on which image was tested.

table3-other-samples-dice-detection¶

For the SEM test images and the macaque TEM image the axon Dice, myelin Dice, sensitivity and precision are rat 1 0.9089, 0.8193, 0.9699, 0.8468; rat 2 0.9244, 0.8389, 0.9876, 0.7987; human 0.8089, 0.7629, 0.9300, 0.7306; macaque 0.9069, 0.7519, 0.9429, 0.8129.

Tolerance 10% of each value. The rat values are those of the matched SEM test images, the macaque values one reading per matched macaque image; the human image is not public.

In [23]:
TABLE3_OTHER = {"Rat 1": (0.9089, 0.8193, 0.9699, 0.8468), "Rat 2": (0.9244, 0.8389, 0.9876, 0.7987),
                "Human": (0.8089, 0.7629, 0.9300, 0.7306), "Macaque": (0.9069, 0.7519, 0.9429, 0.8129)}
q = ["axon_dice", "myelin_dice", "sensitivity", "precision"]
n_in = n_tested = 0
for name in ["Rat 1", "Rat 2"]:
    r = main.loc[name]
    for m, e in zip(q, TABLE3_OTHER[name]):
        ok = abs(r[m] - e) <= 0.1 * e
        n_in += ok; n_tested += 1
        print(f"{name} {m:12s} {r[m]:.4f}  expected {e} +/- {0.1 * e:.4f}  within: {ok}")
for m, e in zip(q, TABLE3_OTHER["Macaque"]):
    ok = (abs(mm["inv_" + m] - e) <= 0.1 * e)
    print(f"Macaque {m:12s} {mm['inv_' + m].min():.4f} to {mm['inv_' + m].max():.4f} over the 7 readings  expected {e} +/- {0.1 * e:.4f}  "
          f"readings within: {int(ok.sum())} of {len(mm)}")
print(f"rat values within tolerance: {n_in} of {n_tested}; human values: not tested (image not public)")
Rat 1 axon_dice    0.9282  expected 0.9089 +/- 0.0909  within: True
Rat 1 myelin_dice  0.8720  expected 0.8193 +/- 0.0819  within: True
Rat 1 sensitivity  0.9640  expected 0.9699 +/- 0.0970  within: True
Rat 1 precision    0.8870  expected 0.8468 +/- 0.0847  within: True
Rat 2 axon_dice    0.9186  expected 0.9244 +/- 0.0924  within: True
Rat 2 myelin_dice  0.8309  expected 0.8389 +/- 0.0839  within: True
Rat 2 sensitivity  0.9790  expected 0.9876 +/- 0.0988  within: True
Rat 2 precision    0.8010  expected 0.7987 +/- 0.0799  within: True
Macaque axon_dice    0.6268 to 0.8070 over the 7 readings  expected 0.9069 +/- 0.0907  readings within: 0 of 7
Macaque myelin_dice  0.5032 to 0.6481 over the 7 readings  expected 0.7519 +/- 0.0752  readings within: 0 of 7
Macaque sensitivity  0.2890 to 0.6060 over the 7 readings  expected 0.9429 +/- 0.0943  readings within: 0 of 7
Macaque precision    0.3490 to 0.6910 over the 7 readings  expected 0.8129 +/- 0.0813  readings within: 0 of 7
rat values within tolerance: 8 of 8; human values: not tested (image not public)

Result: blocked (data missing). The human SEM test image is not public, so 4 of the 16 values cannot be tested. The 8 rat values are all within tolerance on the matched SEM images (axon Dice 0.9282 and 0.9186, myelin Dice 0.8720 and 0.8309, sensitivity 0.964 and 0.979, precision 0.887 and 0.801). The 4 macaque values are outside tolerance on every one of the 7 macaque readings, which rest on images and masks that may not be the paper's (table3-tem-macaque-accuracy).

Claims not tested¶

The dandiset holds only the mouse TEM images and their masks. The human SEM test image (Table 3, row Human; 0.13 um, 715 x 735 um2 in Table 1) and the full rat cervical spinal cord slice of Figures 6 and 7 are not in it. The White Matter Microscopy Database (OSF node yp4qg), which the paper names, holds human spinal cord images (PolytechniqueMontreal/Human, one zip file) whose description, printed below, gives a pixel size of 230 nm, not the 0.13 um of the test image, and the AxonDeepSeg SEM dataset holds rat images only. The database holds two SEM panoramas of an adult rat cervical spinal cord, listed below: PolytechniqueMontreal/RatSpinalCordNov2016 (0.095 um, dated 2016-11-17) and PolytechniqueMontreal/RatSpinalCord2017 (0.13 um, dated 2017-04-27, next to a map of axon equivalent diameter). Either could be the slice of Figures 6 and 7, but the paper gives no pixel size, date or deposit for that slice, so neither can be shown to be it, and the Figure 7 claims also leave the tract boundaries and the white matter mask open. They are not run here, and these claims are not tested.

In [24]:
# The human spinal cord images and the two SEM panoramas of a rat cervical spinal cord in the
# White Matter Microscopy Database.
for path in ["PolytechniqueMontreal/Human", "PolytechniqueMontreal/RatSpinalCordNov2016/histology", "PolytechniqueMontreal/RatSpinalCord2017/Histology"]:
    lst = ads.osf_listing(path)
    print(f"----- {path}")
    print(lst[["name", "size", "modified"]].to_string())
    d = lst[lst.name == "description_histology.json"]
    if len(d):
        print(ads.osf_text(d.id.iloc[0]))
----- PolytechniqueMontreal/Human
                         name      size                    modified
0                PAMhisto.zip  92937660  2017-12-08T06:42:53.417033
1  description_histology.json       358  2018-10-16T21:18:20.640538
{
  "Center": "PolytechniqueMontreal",
  "To Cite": "Duval et al. Axon morphometry in the human spinal cord. Neuroimage 2018",
  "Project": "Human",
  "URL": "https://osf.io/8k7jr/",
  "Modality": "Electron microscopy",
  "Pathology": "healthy subject",
  "PixelSize": "230nm",
  "Staining": "Osmium",
  "Structure": "Spinal cord",
  "Region": ["Cervical"]
}
----- PolytechniqueMontreal/RatSpinalCordNov2016/histology
                              name       size                    modified
0  Panorama_rat_20161102_uint8.png  156615458  2016-11-17T17:41:05.938000
1         parameters_histology.txt        173  2016-11-17T17:41:27.406000
2       description_histology.json        272  2018-06-20T14:08:11.826008
{
  "Center": "PolytechniqueMontreal",
  "Project": "RatNov2016",
  "URL": "https://osf.io/pzveq/",
  "Modality": "SEM",
  "Pathology": "HC",
  "PixelSize": "0.095um",
  "Staining": "Osmium",
  "Structure": "Spinal cord",
  "Region": [
    "Cervical",
    "Panorama"
  ]
}
----- PolytechniqueMontreal/RatSpinalCord2017/Histology
                                   name      size                    modified
0  axonEquivDiameter_(myelin)_0_9µm.jpg  48285034  2017-04-25T19:05:58.236513
1            description_histology.json       271  2018-06-20T14:08:49.073566
2                               img.jpg  27247725  2017-04-27T02:32:41.391916
{
  "Center": "PolytechniqueMontreal",
  "Project": "RatJan2017",
  "URL": "https://osf.io/tgc62/",
  "Modality": "SEM",
  "Pathology": "HC",
  "PixelSize": "0.13um",
  "Staining": "Osmium",
  "Structure": "Spinal cord",
  "Region": [
    "Cervical",
    "Panorama"
  ]
}
In [25]:
print("species in participants.tsv:", sorted(set(pd.read_csv(pd.io.common.BytesIO(
      ads.read_bytes(assets.set_index('path').asset_id['participants.tsv'])), sep='\t').species)))
print("modalities in the file names:", sorted(set(assets.path.str.extract(r'_(TEM|SEM|BF|[A-Z]+)\.png$')[0].dropna())))
print("body part in the sidecars:", sorted({d['BodyPart'] + '/' + d['BodyPartDetails'] for d in sidecars.values()}))
species in participants.tsv: ['mus musculus']
modalities in the file names: ['TEM']
body part in the sidecars: ['BRAIN/splenium']

Summary¶

Claim Outcome
osf-group-labels-link (registry check) reproduced
table3-tem-mice-accuracy reproduced
table3-tem-mice-dice-detection reproduced
myelin-dice-below-axon-dice reproduced on the mouse images
sensitivity-above-93 reproduced on the mouse images
table3-tem-macaque-accuracy blocked, methods underspecified (which image)
macaque-myelin-underestimated reproduced, assumed (the masks of ref. 7 are the paper's ground truth; direction only, the size is not slight)
table3-sem-rat-accuracy reproduced, assumed (the two images of the AxonDeepSeg SEM dataset matched by Table 1 are the paper's test images)
table3-sem-human-accuracy blocked, data missing
table3-other-samples-dice-detection blocked, data missing (human image); rat values within tolerance, macaque values outside
full-slice-processing-time, fig7-corticospinal-tract, fig7-larger-axons-periphery, fig7-tract-diameters, fig7-gratio-range blocked, data missing

How the analysis differs from the paper's. The paper's network runs in TensorFlow 1, which cannot be installed with Python 3.13; it is rebuilt here from the released checkpoint, and its output matches the model's own saved graph to below 1e-04 on the four patches of the first mouse image, with the same class on every pixel, and the SEM network matches its saved graph to below 1e-04 on the patches of Rat 1 (the largest differences are printed in the model check and in the SEM section). The difference changes slightly from run to run, at the level of floating-point round-off. Resampling uses the settings of scikit-image 0.13; the original lines of the code are printed, but the original pipeline could not be run end to end. The paper's test set (3 held-out mice) is not named, so the mouse claims are tested on all mice and on the control mice, both of which include training mice, with every set of 3 mice shown. The dandiset's masks are those of 2025 (fibres separated by a 2-pixel line), not the masks the paper scored against; filling those lines changes the mouse accuracy by less than 0.002. The SEM rat test images come from the AxonDeepSeg SEM dataset, matched to Table 1 by pixel size, field of view and fixation. The macaque images and masks come from the White Matter Microscopy Database, and which of them the paper tested is not known.

What was found about the dataset. The dandiset holds 158 TEM images of 20 mice (8 per mouse, 6 for mouse 25) with three masks each, and the masks fit their images (myelin contrast median 84.4 grey levels in place against 11.8 when shifted). No image is deposited twice. The pixel size is 0.00236 um, not the 0.002 um of the paper (the README says so; at 0.002 um the images would be too small for the model's 512-pixel patches). The files do not say which mice are controls; the White Matter Microscopy Database does, by mouse number. The archive's summary counts 11 samples where there are 158 images (sample ids repeat across mice). 21 axonmyelin masks are grey plus alpha pngs, the rest grey. The test split of the paper is not recorded.