Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 70 additions & 19 deletions src/trk_to_annotation/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,41 @@
License: Apache-2.0
"""

import argparse
import json
import logging
import os
import time
from trk_to_annotation.preprocessing import load_from_file, split_along_grid_batched
from trk_to_annotation.segmentation import make_segmentation_layer
from trk_to_annotation.tract_sharding import write_tract_shard
from trk_to_annotation.id_sharding import write_id_shard
from trk_to_annotation.utils import save_lta, write_spatial_and_info

Check failure on line 16 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (I001)

src/trk_to_annotation/__main__.py:8:1: I001 Import block is un-sorted or un-formatted help: Organize imports


def load_label_map(trk_file: str, label_json: str = None) -> dict:

Check failure on line 19 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (RUF013)

src/trk_to_annotation/__main__.py:19:47: RUF013 PEP 484 prohibits implicit `Optional` help: Convert to `Optional[T]`
"""
Load a {bundle_name: label_id} sidecar JSON for the .trk file.

If label_json is not given, looks for a same-basename .json next to the
.trk file (BIDS-sidecar convention). Returns None if neither is found.
"""
if label_json is None:
candidate = os.path.splitext(trk_file)[0] + ".json"
if os.path.exists(candidate):
label_json = candidate
if label_json is None:
return None
with open(label_json) as f:
return json.load(f)


logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)


def main(trk_file: str, output_dir: str, segmentation_output_dir: str, grid_densities: list[int]):
def main(trk_file: str, output_dir: str, segmentation_output_dir: str, grid_densities: list[int], label_json: str = None, skip_segmentation: bool = False, skip_relationships: bool = False, skip_labels: bool = False):

Check failure on line 42 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (RUF013)

src/trk_to_annotation/__main__.py:42:111: RUF013 PEP 484 prohibits implicit `Optional` help: Convert to `Optional[T]`

Check failure on line 42 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (FA102)

src/trk_to_annotation/__main__.py:42:88: FA102 Missing `from __future__ import annotations`, but uses PEP 585 collection help: Add `from __future__ import annotations`
"""
Parameters
----------
Expand All @@ -34,42 +51,58 @@
path to the precomputed segmentations directory
grid_densities: list[int]
stores how many splits the grids have on each axis. Each number represents a spatial layer, should be increasing, and each should be a power of two
label_json: string, optional
path to a {bundle_name: label_id} sidecar JSON. If omitted, a
same-basename .json next to trk_file is used if present. Used to
attach bundle names (via enum_values/enum_labels) to the label_name
property when the .trk carries a "label_id" scalar/property.
skip_relationships: bool, optional
Skip writing the sharded by_id/by_tract relationship index (no
by-streamline-ID lookup). Just the spatial pyramid is written, with
"relationships": [] and "by_id": {"key": ""} in info.
"""

os.makedirs(output_dir, exist_ok=True)
id_dir = os.path.join(output_dir, 'by_id')
os.makedirs(id_dir, exist_ok=True)
tract_dir = os.path.join(output_dir, 'by_tract')
os.makedirs(tract_dir, exist_ok=True)

start_time = time.time()

pre_segments, bbox, offsets, affine = load_from_file(trk_file)
name_to_id = None if skip_labels else load_label_map(trk_file, label_json)

pre_segments, bbox, offsets, affine, voxel_sizes_mm = load_from_file(trk_file, use_labels=not skip_labels)
split_segments, offsets = split_along_grid_batched(
pre_segments, bbox, [grid_densities[-1]]*3, offsets)

logging.info("Writing ID shards...")
id_file = os.path.join(id_dir, "0.shard")
with open(id_file, 'wb') as f:
write_id_shard(split_segments, f)
if not skip_relationships:
id_dir = os.path.join(output_dir, 'by_id')
os.makedirs(id_dir, exist_ok=True)
tract_dir = os.path.join(output_dir, 'by_tract')
os.makedirs(tract_dir, exist_ok=True)

logging.info("Writing ID shards...")

Check failure on line 81 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (LOG015)

src/trk_to_annotation/__main__.py:81:9: LOG015 `info()` call on root logger help: Use own logger instead
id_file = os.path.join(id_dir, "0.shard")
with open(id_file, 'wb') as f:
write_id_shard(split_segments, f)

logging.info("Writing tract shards...")
tract_file = os.path.join(tract_dir, "0.shard")
with open(tract_file, 'wb') as f:
write_tract_shard(offsets, split_segments, f)
logging.info("Writing tract shards...")

Check failure on line 86 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (LOG015)

src/trk_to_annotation/__main__.py:86:9: LOG015 `info()` call on root logger help: Use own logger instead
tract_file = os.path.join(tract_dir, "0.shard")
with open(tract_file, 'wb') as f:
write_tract_shard(offsets, split_segments, f)

logging.info("Writing spatial layers and info file...")

Check failure on line 91 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (LOG015)

src/trk_to_annotation/__main__.py:91:5: LOG015 `info()` call on root logger help: Use own logger instead
write_spatial_and_info(split_segments, bbox,
grid_densities, offsets, output_dir)
grid_densities, offsets, output_dir, label_map=name_to_id,
sharding=not skip_relationships, voxel_sizes_mm=voxel_sizes_mm)

logging.info("Writing transformation to file...")

Check failure on line 96 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (LOG015)

src/trk_to_annotation/__main__.py:96:5: LOG015 `info()` call on root logger help: Use own logger instead
save_lta(affine, os.path.join(output_dir, "transform.lta"))

logging.info("Creating segmentation layer...")
make_segmentation_layer(split_segments, 1, bbox, segmentation_output_dir)
if not skip_segmentation:
from trk_to_annotation.segmentation import make_segmentation_layer
logging.info("Creating segmentation layer...")

Check failure on line 101 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (LOG015)

src/trk_to_annotation/__main__.py:101:9: LOG015 `info()` call on root logger help: Use own logger instead
make_segmentation_layer(split_segments, 1, bbox, segmentation_output_dir)

end_time = time.time()
logging.info("Script completed in %.2f seconds.", end_time - start_time)

Check failure on line 105 in src/trk_to_annotation/__main__.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (LOG015)

src/trk_to_annotation/__main__.py:105:5: LOG015 `info()` call on root logger help: Use own logger instead


if __name__ == "__main__":
Expand Down Expand Up @@ -100,7 +133,25 @@
default=[1, 2, 4, 8, 16, 32],
help="Grid densities (powers of two in ascending order)",
)
parser.add_argument(
"--label_json",
type=str,
default=None,
help="Path to a {bundle_name: label_id} sidecar JSON. Defaults to a "
"same-basename .json next to trk_file if present.",
)
parser.add_argument(
"--skip_segmentation",
action="store_true",
help="Skip building the streamline-id segmentation layer (avoids the cloud-volume dependency).",
)
parser.add_argument(
"--skip_relationships",
action="store_true",
help="Skip the sharded by_id/by_tract relationship index; write only the spatial pyramid.",
)

args = parser.parse_args()
main(args.trk_file, args.annotation_output_dir,
args.segmentation_output_dir, args.grid_densities)
args.segmentation_output_dir, args.grid_densities, args.label_json,
args.skip_segmentation, args.skip_relationships)
19 changes: 19 additions & 0 deletions src/trk_to_annotation/datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,22 @@
('orientation', 'f4', 3),
('id', 'i8')
)

# Optional per-segment bundle-label fields, appended to SEGMENT_DTYPE when the
# source .trk carries a "label_id" scalar/property (e.g. bundle group id).
# label_name duplicates label_id's raw value under a separate property id so
# Neuroglancer can attach enum_values/enum_labels (bundle names) to it while
# label_id stays a plain numeric property.
LABEL_EXTRA_DTYPE = (
('label_id', '<u2'),
('label_name', '<u2'),
('label_color', '<u1', 3),
)
LABEL_EXTRA_BYTES = 8 # 2 (label_id) + 2 (label_name) + 3 (label_color) + 1 (extra
# alignment byte: Neuroglancer requires each record's
# byte size to be a multiple of 4; the plain 7 extra
# label bytes would break that, so an extra anonymous
# 1-byte padding field (LABEL_ALIGN_PAD_FIELD) is
# added alongside the normal "padding" field when
# labels are present.
LABEL_ALIGN_PAD_FIELD = ("label_align_pad", "u1") # only when has_label
46 changes: 35 additions & 11 deletions src/trk_to_annotation/id_sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,41 @@

import numpy as np

from trk_to_annotation.datatypes import LABEL_EXTRA_BYTES, LABEL_ALIGN_PAD_FIELD


def _extra_bytes(segments: np.ndarray, scalar_names: list) -> int:
"""Extra per-record bytes beyond the 56 fixed id-record fields: 4 per
generic float32 scalar, plus LABEL_EXTRA_BYTES if bundle-label fields
are present."""
has_label = "label_id" in segments.dtype.names
return 4 * len(scalar_names) + (LABEL_EXTRA_BYTES if has_label else 0)


# ----------------------------
# Utility Functions
# ----------------------------
def length_of_id_chunk(scalar_size: int) -> int:
def length_of_id_chunk(extra_bytes: int) -> int:
"""
Compute the byte length of a single ID chunk.

Parameters
----------
scalar_size : int
Number of scalar fields per segment.
extra_bytes : int
Extra bytes per segment beyond the fixed record fields (start, end,
streamline, orientation, orientation_color, padding, number_tracts,
tract_id = 56 bytes), i.e. 4 bytes per generic float32 scalar plus
LABEL_EXTRA_BYTES (7) when bundle-label fields are present.

Returns
-------
int
Byte length of the ID chunk.
"""
return 52 + 4 * scalar_size
return 56 + extra_bytes


def length_of_id_minishard(id_start: int, id_end: int, scalar_size: int) -> int:
def length_of_id_minishard(id_start: int, id_end: int, extra_bytes: int) -> int:
"""
Compute the byte length of a minishard containing multiple IDs.

Expand All @@ -43,16 +56,17 @@ def length_of_id_minishard(id_start: int, id_end: int, scalar_size: int) -> int:
Starting ID index.
id_end : int
Ending ID index (exclusive).
scalar_size : int
Number of scalar fields per segment.
extra_bytes : int
Extra bytes per segment beyond the fixed record fields (see
length_of_id_chunk).

Returns
-------
int
Byte length of the minishard.
"""
chunk_indices = 24 * (id_end - id_start)
chunks = (52 + 4 * scalar_size) * (id_end - id_start)
chunks = (56 + extra_bytes) * (id_end - id_start)
return chunk_indices + chunks


Expand Down Expand Up @@ -97,6 +111,8 @@ def write_id_minishard(
"""
scalar_names = [
name for name in segments.dtype.names if name.startswith("scalar_")]
has_label = "label_id" in segments.dtype.names
extra_bytes = _extra_bytes(segments, scalar_names)

dtype = np.dtype(
[
Expand All @@ -105,8 +121,11 @@ def write_id_minishard(
("streamline", "<u4"),
("orientation", "<f4", 3),
*[(name, "<f4") for name in scalar_names],
*([("label_id", "<u2"), ("label_name", "<u2"),
("label_color", "<u1", 3)] if has_label else []),
("orientation_color", "<u1", 3),
("padding", "u1"),
*([LABEL_ALIGN_PAD_FIELD] if has_label else []),
("number_tracts", "<u4"),
("tract_id", "<u8"),
]
Expand All @@ -121,6 +140,10 @@ def write_id_minishard(
data["streamline"] = masked_segments["streamline"]
for name in scalar_names:
data[name] = masked_segments[name]
if has_label:
data["label_id"] = masked_segments["label_id"]
data["label_name"] = masked_segments["label_name"]
data["label_color"] = masked_segments["label_color"]
data["orientation_color"] = np.abs(masked_segments["orientation"] * 255)
data["padding"] = np.zeros(data.shape[0], dtype="u1")
data["number_tracts"] = 0
Expand All @@ -132,11 +155,11 @@ def write_id_minishard(
np.asarray([id_start], dtype="<u8").tofile(f)
np.asarray(np.ones((id_end - id_start - 1)), dtype="<u8").tofile(f)
np.asarray(
[length_of_id_minishard(0, id_start, len(scalar_names))], dtype="<u8"
[length_of_id_minishard(0, id_start, extra_bytes)], dtype="<u8"
).tofile(f)
np.asarray(np.zeros((id_end - id_start - 1)), dtype="<u8").tofile(f)
np.asarray(
[length_of_id_chunk(len(scalar_names))] * (id_end - id_start), dtype="<u8"
[length_of_id_chunk(extra_bytes)] * (id_end - id_start), dtype="<u8"
).tofile(f)


Expand All @@ -157,6 +180,7 @@ def write_id_shard(
"""
scalar_names = [
name for name in segments.dtype.names if name.startswith("scalar_")]
extra_bytes = _extra_bytes(segments, scalar_names)
num_ids = len(segments)
minishard_bits = number_of_minishard_bits_ids(num_ids, preshift_bits)
per_minishard = 2**preshift_bits
Expand All @@ -167,7 +191,7 @@ def write_id_shard(
starts = np.arange(0, num_ids, per_minishard)
ends = np.minimum(starts + per_minishard, num_ids)

sizes = length_of_id_minishard(starts, ends, len(scalar_names))
sizes = length_of_id_minishard(starts, ends, extra_bytes)

last_sizes = np.cumsum(sizes)

Expand Down
62 changes: 57 additions & 5 deletions src/trk_to_annotation/preprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,46 @@
import logging
from typing import List, Tuple
import nibabel
from nibabel.affines import voxel_sizes as _voxel_sizes
import numpy as np

from trk_to_annotation.datatypes import SEGMENT_DTYPE
from trk_to_annotation.datatypes import SEGMENT_DTYPE, LABEL_EXTRA_DTYPE

# ----------------------------
# Configuration
# ----------------------------
BATCH_SIZE = 100_000_000
LABEL_SCALAR_NAME = "label_id"


def label_ids_to_colors(label_ids: np.ndarray) -> np.ndarray:
"""
Deterministically assign a random RGB color to each unique label id.

Each id is seeded independently (seed = the id itself), so the color for
a given label id is stable across batches/runs regardless of which other
ids are present or the order they're encountered in.

Parameters
----------
label_ids : np.ndarray
Integer label ids, one per segment.

Returns
-------
np.ndarray
(N, 3) uint8 array of RGB colors, one row per input label id.
"""
unique_ids = np.unique(label_ids)
lut = np.zeros((int(unique_ids.max()) + 1, 3), dtype=np.uint8)
for uid in unique_ids:
rng = np.random.default_rng(int(uid))
lut[uid] = rng.integers(0, 256, size=3, dtype=np.uint8)
return lut[label_ids]


def load_from_file(
trk_file: str
trk_file: str, use_labels: bool = True
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Load streamlines from a .trk file.
Expand Down Expand Up @@ -72,11 +100,19 @@ def load_from_file(
line_start = points[start_idx, :3]
line_end = points[end_idx, :3]

# Scalar keys
scalar_keys = list(tracts.tractogram.data_per_point.keys())
# Scalar keys (label_id is handled separately below, not as a generic
# float32 scalar)
scalar_keys = [
name for name in tracts.tractogram.data_per_point.keys()
if name != LABEL_SCALAR_NAME
]
has_label = use_labels and LABEL_SCALAR_NAME in tracts.tractogram.data_per_point.keys()

segment_dtype = list(SEGMENT_DTYPE)
for name in scalar_keys:
segment_dtype.append(("scalar_" + name, "f4"))
if has_label:
segment_dtype.extend(LABEL_EXTRA_DTYPE)

# Streamline IDs
line_tract = np.concatenate([np.full(length - 1, i + 1)
Expand All @@ -99,12 +135,28 @@ def load_from_file(
segments["scalar_" + name] = np.reshape((tracts.tractogram.data_per_point[name]._data[start_idx] +
tracts.tractogram.data_per_point[name]._data[end_idx])/2, (-1))

# Bundle label id / name / color (label_id is constant along a
# streamline, so start/end average equals the exact value)
if has_label:
label_scalar = tracts.tractogram.data_per_point[LABEL_SCALAR_NAME]._data
label_ids = np.rint(
(label_scalar[start_idx] + label_scalar[end_idx]) / 2
).reshape(-1).astype(np.uint16)
segments["label_id"] = label_ids
segments["label_name"] = label_ids
segments["label_color"] = label_ids_to_colors(label_ids)

offsets = np.append(streamlines._offsets -
np.arange(len(streamlines._offsets)), len(segments))

logging.info("load_from_file: Done")

return segments, np.array([lb, ub]), offsets, tracts.affine
# Points were transformed into voxel-index space above (not world mm),
# so Neuroglancer needs the per-axis voxel size (mm/index-step) to scale
# these coordinates back to real physical distances.
voxel_sizes_mm = _voxel_sizes(tracts.affine)

return segments, np.array([lb, ub]), offsets, tracts.affine, voxel_sizes_mm


def split_along_grid_batched(
Expand Down
Loading
Loading