ossify 0.2.7__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {ossify-0.2.7 → ossify-0.3.0}/PKG-INFO +1 -1
  2. {ossify-0.2.7 → ossify-0.3.0}/pyproject.toml +2 -2
  3. ossify-0.3.0/scripts/build_example_cell.py +102 -0
  4. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/__init__.py +1 -1
  5. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/base.py +120 -20
  6. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/data_layers.py +353 -87
  7. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/plot.py +25 -1
  8. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/translate.py +5 -8
  9. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/utils.py +4 -1
  10. {ossify-0.2.7 → ossify-0.3.0}/.github/workflows/mkdocs_publish.yml +0 -0
  11. {ossify-0.2.7 → ossify-0.3.0}/.github/workflows/python-package.yml +0 -0
  12. {ossify-0.2.7 → ossify-0.3.0}/.gitignore +0 -0
  13. {ossify-0.2.7 → ossify-0.3.0}/.pre-commit-config.yaml +0 -0
  14. {ossify-0.2.7 → ossify-0.3.0}/LICENSE +0 -0
  15. {ossify-0.2.7 → ossify-0.3.0}/README.md +0 -0
  16. {ossify-0.2.7 → ossify-0.3.0}/mkdocs.yml +0 -0
  17. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/__init__.py +0 -0
  18. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/base.py +0 -0
  19. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/graph.py +0 -0
  20. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/mapping.py +0 -0
  21. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/mesh.py +0 -0
  22. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/morph.py +0 -0
  23. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/points.py +0 -0
  24. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/_sync/table.py +0 -0
  25. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/algorithms.py +0 -0
  26. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/compartment_models/minnie65_ds15_us0_bd0.json +0 -0
  27. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/compartment_models/v1dd_ds15_us0_bd0.json +0 -0
  28. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/compartment_models/xgb/minnie65_ds15_us0_bd0.ubj +0 -0
  29. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/compartment_models/xgb/v1dd_ds15_us0_bd0.ubj +0 -0
  30. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/compartments.py +0 -0
  31. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/file_io.py +0 -0
  32. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/graph_functions.py +0 -0
  33. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/plot3d.py +0 -0
  34. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/plot_utils.py +0 -0
  35. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/structured_prediction.py +0 -0
  36. {ossify-0.2.7 → ossify-0.3.0}/src/ossify/sync_classes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ossify
3
- Version: 0.2.7
3
+ Version: 0.3.0
4
4
  Summary: Mesh and skeleton analysis
5
5
  Author-email: Casey Schneider-Mizell <caseysm@gmail.com>
6
6
  License-File: LICENSE
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  allow-direct-references = true
7
7
  [project]
8
8
  name = "ossify"
9
- version = "0.2.7"
9
+ version = "0.3.0"
10
10
  description = "Mesh and skeleton analysis"
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.11"
@@ -95,7 +95,7 @@ default-groups = ["dev", "docs", "lint", "profile", "viz"]
95
95
 
96
96
 
97
97
  [tool.bumpversion]
98
- current_version = "0.2.7"
98
+ current_version = "0.3.0"
99
99
  parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
100
100
  serialize = ["{major}.{minor}.{patch}"]
101
101
  regex = false
@@ -0,0 +1,102 @@
1
+ """Build the distributable four-layer example cell.
2
+
3
+ The source mesh is 2.6M vertices. Quadric decimation (fast-simplification via
4
+ trimesh) does most of the work and preserves surface area well, but it floors
5
+ around 634k faces because the reconstruction is in 970 disconnected bodies --
6
+ 65 of which are over 1000 vertices, so they are real morphology, not dust.
7
+ Vertex clustering takes it the rest of the way.
8
+
9
+ Note trimesh's `percent` is the fraction to REMOVE, not to keep.
10
+ """
11
+
12
+ import sys
13
+ import numpy as np, pandas as pd, trimesh, ossify
14
+ from scipy.spatial import cKDTree
15
+ from ossify import Cell, Link
16
+
17
+ GRID = float(sys.argv[1]) if len(sys.argv) > 1 else 700.0
18
+ OUT = sys.argv[2] if len(sys.argv) > 2 else "864691135336055529_full.osy"
19
+ SRC = "tests/data/test_cell_with_mesh.osy"
20
+
21
+ src = ossify.load_cell(SRC)
22
+ V0, F0 = src.mesh.vertices, src.mesh.faces_positional
23
+ src_area = src.mesh.surface_area()
24
+
25
+ dec = trimesh.Trimesh(vertices=V0, faces=F0, process=False).simplify_quadric_decimation(
26
+ percent=0.99
27
+ )
28
+ V, F = np.asarray(dec.vertices), np.asarray(dec.faces)
29
+
30
+ keys = np.floor(V / GRID).astype(np.int64)
31
+ _, inverse, counts = np.unique(keys, axis=0, return_inverse=True, return_counts=True)
32
+ n_cells = len(counts)
33
+ reps = np.zeros((n_cells, 3))
34
+ for axis in range(3):
35
+ reps[:, axis] = np.bincount(inverse, weights=V[:, axis], minlength=n_cells)
36
+ reps /= counts[:, None]
37
+
38
+ nf = inverse[F]
39
+ keep = (nf[:, 0] != nf[:, 1]) & (nf[:, 1] != nf[:, 2]) & (nf[:, 0] != nf[:, 2])
40
+ nf = np.unique(np.sort(nf[keep], axis=1), axis=0)
41
+ used = np.unique(nf)
42
+ remap = np.full(n_cells, -1, dtype=np.int64)
43
+ remap[used] = np.arange(len(used))
44
+ mesh_verts, mesh_faces = reps[used], remap[nf]
45
+
46
+ # Link each new vertex to the graph, via the nearest ORIGINAL vertex that
47
+ # actually has a link -- 502 source vertices carry the unmapped sentinel 0,
48
+ # and inheriting one of those would put a non-existent graph id in the link.
49
+ m2g = np.asarray(src.mesh.map_index_to_layer("graph"))
50
+ valid = np.isin(m2g, src.graph.vertex_index)
51
+ _, nearest_valid = cKDTree(V0[valid]).query(mesh_verts)
52
+ new_m2g = m2g[valid][nearest_valid]
53
+ assert np.isin(new_m2g, src.graph.vertex_index).all()
54
+
55
+ out = Cell(name=src.name, meta=dict(src.meta or {}))
56
+ out.add_skeleton(
57
+ vertices=src.skeleton.nodes[src.skeleton.spatial_columns],
58
+ edges=src.skeleton.edges,
59
+ spatial_columns=src.skeleton.spatial_columns,
60
+ root=src.skeleton.root,
61
+ features=src.skeleton.features,
62
+ edges_as_positional=False,
63
+ )
64
+ out.add_graph(
65
+ vertices=src.graph.nodes[src.graph.spatial_columns],
66
+ edges=src.graph.edges,
67
+ spatial_columns=src.graph.spatial_columns,
68
+ features=src.graph.features,
69
+ edges_as_positional=False,
70
+ linkage=Link(
71
+ mapping=np.asarray(src.graph.map_index_to_layer("skeleton")),
72
+ target="skeleton",
73
+ map_value_is_index=True,
74
+ ),
75
+ )
76
+ out.add_mesh(
77
+ vertices=pd.DataFrame(mesh_verts, columns=src.mesh.spatial_columns),
78
+ faces=mesh_faces,
79
+ spatial_columns=src.mesh.spatial_columns,
80
+ faces_as_positional=True,
81
+ linkage=Link(mapping=new_m2g, target="graph", map_value_is_index=True),
82
+ )
83
+ for anno in ("pre_syn", "post_syn"):
84
+ a = src.annotations[anno]
85
+ out.add_point_annotations(
86
+ name=anno,
87
+ vertices=a.nodes,
88
+ spatial_columns=a.spatial_columns,
89
+ linkage=Link(
90
+ mapping=np.asarray(a.map_index_to_layer("graph")),
91
+ target="graph",
92
+ map_value_is_index=True,
93
+ ),
94
+ )
95
+ ossify.save_cell(out, OUT, allow_overwrite=True)
96
+ import os
97
+
98
+ print(
99
+ f"grid={GRID:.0f}nm mesh {out.mesh.n_vertices:,} v / {len(out.mesh.faces):,} f "
100
+ f"area {100 * out.mesh.surface_area() / src_area:.0f}% "
101
+ f"file {os.path.getsize(OUT) / 1e6:.1f}MB"
102
+ )
@@ -5,7 +5,7 @@ from .base import *
5
5
  from .file_io import *
6
6
  from .translate import *
7
7
 
8
- __version__ = "0.2.7"
8
+ __version__ = "0.3.0"
9
9
 
10
10
 
11
11
  def __getattr__(name):
@@ -398,6 +398,7 @@ class Cell:
398
398
  features: Optional[Union[dict, pd.DataFrame]] = None,
399
399
  *,
400
400
  vertex_index: Optional[Union[str, np.ndarray]] = None,
401
+ faces_as_positional: Optional[bool] = None,
401
402
  linkage: Optional[Link] = None,
402
403
  spatial_columns: Optional[list] = None,
403
404
  ) -> Self:
@@ -408,11 +409,25 @@ class Cell:
408
409
  vertices : Union[np.ndarray, pd.DataFrame, MeshLayer]
409
410
  The vertices of the mesh, or a MeshLayer object.
410
411
  faces : Union[np.ndarray, pd.DataFrame]
411
- The faces of the mesh. If faces are provided as a dataframe, faces should be in dataframe indices.
412
+ The triangular faces of the mesh. **If ``vertex_index`` is given
413
+ these are positional indices into ``vertices``** and are remapped
414
+ onto the vertex index for you; otherwise they are vertex indices
415
+ already -- the index of ``vertices`` when it is a DataFrame, or
416
+ positional when it is a plain array. Mesh formats such as OBJ and
417
+ PLY give positional faces, so ``vertex_index`` is usually what you
418
+ want when labelling mesh vertices with ids.
412
419
  features : Optional[Union[dict, pd.DataFrame]]
413
420
  Additional features for the mesh. If passed as dictionary, the key is the feature name and the values are an array of feature values.
414
421
  vertex_index : Optional[Union[str, np.ndarray]]
415
- The column to use as a vertex index for the mesh, if vertices are a dataframe.
422
+ Vertex indices to label the mesh's vertices by: either the name of
423
+ a column in ``vertices``, or an array with one value per vertex.
424
+ Supplying this changes how ``faces`` are read -- see above.
425
+ faces_as_positional : Optional[bool]
426
+ Whether ``faces`` are positional indices into ``vertices``. The
427
+ default, None, infers it as described above: positional exactly
428
+ when ``vertex_index`` is supplied. Pass it explicitly when the two
429
+ spaces overlap -- a ``vertex_index`` whose values are also valid
430
+ positions cannot be told apart any other way.
416
431
  linkage : Optional[Link]
417
432
  The linkage information for the mesh.
418
433
  spatial_columns: Optional[list] = None
@@ -435,6 +450,7 @@ class Cell:
435
450
  name=self.MESH_LN,
436
451
  vertices=vertices,
437
452
  faces=faces,
453
+ faces_as_positional=faces_as_positional,
438
454
  features=features,
439
455
  morphsync=self._morphsync,
440
456
  spatial_columns=spatial_columns,
@@ -453,6 +469,8 @@ class Cell:
453
469
  root: Optional[int] = None,
454
470
  *,
455
471
  vertex_index: Optional[Union[str, np.ndarray]] = None,
472
+ edges_as_positional: Optional[bool] = None,
473
+ root_as_positional: bool = False,
456
474
  linkage: Optional[Link] = None,
457
475
  spatial_columns: Optional[list] = None,
458
476
  inherited_properties: Optional[dict] = None,
@@ -465,13 +483,33 @@ class Cell:
465
483
  vertices : Union[np.ndarray, pd.DataFrame, SkeletonLayer]
466
484
  The vertices of the skeleton, or a SkeletonLayer object.
467
485
  edges : Union[np.ndarray, pd.DataFrame]
468
- The edges of the skeleton.
486
+ The edges of the skeleton, as pairs of vertices. **If ``vertex_index``
487
+ is given these are positional indices into ``vertices``** and are
488
+ remapped onto the vertex index for you; otherwise they are vertex
489
+ indices already -- the index of ``vertices`` when it is a DataFrame,
490
+ or positional when it is a plain array.
469
491
  features : Optional[Union[dict, pd.DataFrame]]
470
492
  The features for the skeleton.
471
493
  root : Optional[int]
472
- The root vertex for the skeleton, required of the edges are not already consistent with a single root.
494
+ The root of the skeleton, as a **vertex index** -- note this is the
495
+ opposite convention to ``edges``, which are positional when
496
+ ``vertex_index`` is given. Required if the edges are not already
497
+ consistent with a single root.
498
+ root_as_positional : bool
499
+ Whether ``root`` is a positional index into ``vertices`` rather
500
+ than a vertex index. Default False. This is the escape hatch for
501
+ the asymmetry noted above: ``edges`` and ``root`` keep different
502
+ defaults, but either can be stated explicitly.
473
503
  vertex_index : Optional[Union[str, np.ndarray]]
474
- The vertex index for the skeleton.
504
+ Vertex indices to label the skeleton's vertices by: either the name of
505
+ a column in ``vertices``, or an array with one value per vertex.
506
+ Supplying this changes how ``edges`` are read -- see above.
507
+ edges_as_positional : Optional[bool]
508
+ Whether ``edges`` are positional indices into ``vertices``. The
509
+ default, None, infers it as described above: positional exactly
510
+ when ``vertex_index`` is supplied. Pass it explicitly when the two
511
+ spaces overlap -- a ``vertex_index`` whose values are also valid
512
+ positions cannot be told apart any other way.
475
513
  linkage : Optional[Link]
476
514
  The linkage information for the skeleton. Typically, you will define the source vertices for the skeleton if using a graph-to-skeleton mapping.
477
515
  spatial_columns: Optional[list] = None
@@ -495,8 +533,10 @@ class Cell:
495
533
  name=self.SKEL_LN,
496
534
  vertices=vertices,
497
535
  edges=edges,
536
+ edges_as_positional=edges_as_positional,
498
537
  features=features,
499
538
  root=root,
539
+ root_as_positional=root_as_positional,
500
540
  morphsync=self._morphsync,
501
541
  spatial_columns=spatial_columns,
502
542
  linkage=linkage,
@@ -514,6 +554,7 @@ class Cell:
514
554
  features: Optional[Union[dict, pd.DataFrame]] = None,
515
555
  *,
516
556
  vertex_index: Optional[Union[str, np.ndarray]] = None,
557
+ edges_as_positional: Optional[bool] = None,
517
558
  spatial_columns: Optional[list] = None,
518
559
  linkage: Optional[Link] = None,
519
560
  ) -> Self:
@@ -526,11 +567,23 @@ class Cell:
526
567
  vertices : Union[np.ndarray, pd.DataFrame, SkeletonLayer]
527
568
  The vertices of the graph.
528
569
  edges : Union[np.ndarray, pd.DataFrame]
529
- The edges of the graph.
570
+ The edges of the graph, as pairs of vertices. **If ``vertex_index``
571
+ is given these are positional indices into ``vertices``** and are
572
+ remapped onto the vertex index for you; otherwise they are vertex
573
+ indices already -- the index of ``vertices`` when it is a DataFrame,
574
+ or positional when it is a plain array.
530
575
  features : Optional[Union[dict, pd.DataFrame]]
531
576
  The features for the graph.
532
577
  vertex_index : Optional[Union[str, np.ndarray]]
533
- The vertex index for the graph.
578
+ Vertex indices to label the graph's vertices by: either the name of
579
+ a column in ``vertices``, or an array with one value per vertex.
580
+ Supplying this changes how ``edges`` are read -- see above.
581
+ edges_as_positional : Optional[bool]
582
+ Whether ``edges`` are positional indices into ``vertices``. The
583
+ default, None, infers it as described above: positional exactly
584
+ when ``vertex_index`` is supplied. Pass it explicitly when the two
585
+ spaces overlap -- a ``vertex_index`` whose values are also valid
586
+ positions cannot be told apart any other way.
534
587
  spatial_columns: Optional[list] = None
535
588
  The spatial columns for the graph, if vertices are a dataframe.
536
589
 
@@ -552,6 +605,7 @@ class Cell:
552
605
  name=self.GRAPH_LN,
553
606
  vertices=vertices,
554
607
  edges=edges,
608
+ edges_as_positional=edges_as_positional,
555
609
  features=features,
556
610
  morphsync=self._morphsync,
557
611
  spatial_columns=spatial_columns,
@@ -978,7 +1032,39 @@ class Cell:
978
1032
 
979
1033
  return self
980
1034
 
981
- def describe(self, html: bool = False) -> None:
1035
+ def _coverage_note(self, source: str, target: str, enabled: bool = True) -> str:
1036
+ """Annotate a link with the directions that are not fully mapped.
1037
+
1038
+ A link existing does not mean it is usable in the direction you want:
1039
+ completeness is directional, so every mesh vertex can reach the graph
1040
+ while some graph vertices are reached by no mesh vertex. Operations
1041
+ that need a total mapping -- ``map_index_to_layer`` chief among them --
1042
+ care about that, in the way a mesh's volume cares about watertightness.
1043
+
1044
+ Partial coverage is not automatically a fault. A sparse annotation is
1045
+ expected to reach few of the skeleton's vertices; only the layers that
1046
+ are meant to cover each other are worth a second look.
1047
+ """
1048
+ if not enabled:
1049
+ return ""
1050
+ notes = []
1051
+ for a, b in ((source, target), (target, source)):
1052
+ layer = self._all_objects.get(a)
1053
+ if layer is None or b not in self._all_objects:
1054
+ continue
1055
+ try:
1056
+ # Cheap check first; only pay for the fraction when there is
1057
+ # something to report. describe() is called casually and can
1058
+ # be run on a cell with millions of mesh vertices.
1059
+ if layer.is_fully_mapped_to(b):
1060
+ continue
1061
+ coverage = layer.mapping_coverage(b)
1062
+ except Exception: # noqa: BLE001 - describe must never fail
1063
+ continue
1064
+ notes.append(f"{a} {coverage:.0%} mapped")
1065
+ return f" ({'; '.join(notes)})" if notes else ""
1066
+
1067
+ def describe(self, html: bool = False, coverage: bool = True) -> None:
982
1068
  """Generate a hierarchical summary description of the cell and its layers.
983
1069
 
984
1070
  Provides a tree-like overview including:
@@ -991,6 +1077,12 @@ class Cell:
991
1077
  html : bool, optional
992
1078
  If True, create expandable HTML widgets in Jupyter.
993
1079
  If False, print formatted string (default).
1080
+ coverage : bool, optional
1081
+ Annotate links whose mapping is incomplete with how much of each
1082
+ side is covered. Default True. This walks the link tables, so it
1083
+ costs O(vertices) per link -- negligible on a normal cell, a couple
1084
+ of seconds on one with millions of mesh vertices. Pass False to
1085
+ skip it.
994
1086
 
995
1087
  Returns
996
1088
  -------
@@ -1001,13 +1093,14 @@ class Cell:
1001
1093
  --------
1002
1094
  >>> cell.describe() # Prints formatted string
1003
1095
  >>> cell.describe(html=True) # Shows HTML widgets in Jupyter
1096
+ >>> cell.describe(coverage=False) # Skip the mapping-coverage walk
1004
1097
  """
1005
1098
  if html:
1006
1099
  self._describe_html()
1007
1100
  else:
1008
- print(self._describe_text())
1101
+ print(self._describe_text(coverage=coverage))
1009
1102
 
1010
- def _describe_text(self) -> str:
1103
+ def _describe_text(self, coverage: bool = True) -> str:
1011
1104
  """Generate text-based hierarchical description."""
1012
1105
  lines = []
1013
1106
 
@@ -1055,9 +1148,11 @@ class Cell:
1055
1148
  vertex_count = len(layer_obj.vertices)
1056
1149
 
1057
1150
  if hasattr(layer_obj, "faces"): # Mesh layers
1058
- face_count = (
1059
- len(layer_obj.faces) if len(layer_obj.faces.shape) > 1 else 0
1060
- )
1151
+ # Bind once: `faces` remaps the whole facet array on every
1152
+ # access, so evaluating it twice here doubled the cost of
1153
+ # describing a large mesh.
1154
+ faces = layer_obj.faces
1155
+ face_count = len(faces) if faces.ndim > 1 else 0
1061
1156
  lines.append(
1062
1157
  f"│ {prefix} {layer_name}: {vertex_count} vertices, {face_count} faces"
1063
1158
  )
@@ -1115,12 +1210,16 @@ class Cell:
1115
1210
  # Check if bidirectional link exists
1116
1211
  if reverse_key in self._morphsync.links:
1117
1212
  # Bidirectional link
1118
- link_display_items.append(f"{source} <-> {target}")
1213
+ link_display_items.append(
1214
+ f"{source} <-> {target}{self._coverage_note(source, target, coverage)}"
1215
+ )
1119
1216
  processed_pairs.add(link_key)
1120
1217
  processed_pairs.add(reverse_key)
1121
1218
  else:
1122
1219
  # Unidirectional link
1123
- link_display_items.append(f"{source} → {target}")
1220
+ link_display_items.append(
1221
+ f"{source} → {target}{self._coverage_note(source, target, coverage)}"
1222
+ )
1124
1223
  processed_pairs.add(link_key)
1125
1224
 
1126
1225
  # Show the actual number of connection pairs being displayed
@@ -1367,9 +1466,8 @@ class Cell:
1367
1466
  vertex_count = len(layer_obj.vertices)
1368
1467
 
1369
1468
  if hasattr(layer_obj, "faces"):
1370
- face_count = (
1371
- len(layer_obj.faces) if len(layer_obj.faces.shape) > 1 else 0
1372
- )
1469
+ faces = layer_obj.faces # remaps on access; bind once
1470
+ face_count = len(faces) if faces.ndim > 1 else 0
1373
1471
  details = f"vertices: {vertex_count:,} | faces: {face_count:,}"
1374
1472
  elif hasattr(layer_obj, "edges"):
1375
1473
  edge_count = (
@@ -1410,10 +1508,12 @@ class Cell:
1410
1508
  vertex_count = len(layer.vertices)
1411
1509
 
1412
1510
  if hasattr(layer, "faces"):
1413
- face_count = len(layer.faces) if len(layer.faces.shape) > 1 else 0
1511
+ faces = layer.faces # remaps on access; bind once
1512
+ face_count = len(faces) if faces.ndim > 1 else 0
1414
1513
  details = f"vertices: {vertex_count:,} | faces: {face_count:,}"
1415
1514
  elif hasattr(layer, "edges"):
1416
- edge_count = len(layer.edges) if len(layer.edges.shape) > 1 else 0
1515
+ edges = layer.edges # remaps on access; bind once
1516
+ edge_count = len(edges) if edges.ndim > 1 else 0
1417
1517
  details = f"vertices: {vertex_count:,} | edges: {edge_count:,}"
1418
1518
  else:
1419
1519
  details = f"vertices: {vertex_count:,}"
@@ -89,26 +89,6 @@ class EdgeMixin(ABC):
89
89
  return np.empty((0, 2), dtype=int)
90
90
  return self.layer.edges_positional
91
91
 
92
- def _map_edges_to_index(
93
- self, edges: np.ndarray, vertex_indices: np.ndarray
94
- ) -> np.ndarray:
95
- """Remap positional edges to vertex indices.
96
-
97
- Parameters
98
- ----------
99
- edges : np.ndarray
100
- Edge array with positional indices.
101
- vertex_indices : np.ndarray
102
- Array of vertex indices to map to.
103
-
104
- Returns
105
- -------
106
- np.ndarray
107
- Edge array with vertex indices instead of positional indices.
108
- """
109
- index_map = {ii: v for ii, v in enumerate(vertex_indices)}
110
- return fastremap.remap(edges, index_map)
111
-
112
92
  @property
113
93
  def csgraph(self) -> sparse.csr_matrix:
114
94
  """
@@ -318,30 +298,10 @@ class FaceMixin(ABC):
318
298
  self._csgraph = None
319
299
  self._trimesh = None
320
300
 
321
- def _map_faces_to_index(
322
- self, faces: np.ndarray, vertex_indices: np.ndarray
323
- ) -> np.ndarray:
324
- """Remap positional faces to vertex indices.
325
-
326
- Parameters
327
- ----------
328
- faces : np.ndarray
329
- Face array with positional indices.
330
- vertex_indices : np.ndarray
331
- Array of vertex indices to map to.
332
-
333
- Returns
334
- -------
335
- np.ndarray
336
- Face array with vertex indices instead of positional indices.
337
- """
338
- index_map = {ii: v for ii, v in enumerate(vertex_indices)}
339
- return fastremap.remap(faces, index_map)
340
-
341
301
  def surface_area(
342
302
  self,
343
303
  vertices: Optional[np.ndarray] = None,
344
- as_positional: bool = True,
304
+ as_positional: bool = False,
345
305
  inclusive: bool = False,
346
306
  ) -> float:
347
307
  """Calculate the surface area of the mesh, or a subset of vertices.
@@ -351,7 +311,8 @@ class FaceMixin(ABC):
351
311
  vertices : Optional[np.ndarray], optional
352
312
  Vertex indices to calculate surface area for. If None, uses entire mesh.
353
313
  as_positional : bool, optional
354
- Whether the input vertices are positional indices or vertex indices. Default True.
314
+ Whether the input vertices are positional indices or vertex indices.
315
+ Default False, matching every other ``as_positional`` in the API.
355
316
  inclusive : bool, optional
356
317
  Whether to include faces that are covered by any vertex (True) or only those fully covered (False). Default False.
357
318
 
@@ -444,6 +405,75 @@ class PointMixin(ABC):
444
405
  )
445
406
  self._process_linkage(linkage)
446
407
 
408
+ def _index_connectivity(
409
+ self,
410
+ connectivity: np.ndarray,
411
+ vertices: pd.DataFrame,
412
+ as_positional: Optional[bool],
413
+ vertex_index: Optional[Union[str, np.ndarray]],
414
+ what: str = "edges",
415
+ ) -> np.ndarray:
416
+ """Put edges or faces into vertex-index space at construction.
417
+
418
+ Every layer type takes connectivity that may be written either as
419
+ positional indices into ``vertices`` or as vertex indices, so the rule
420
+ lives here once rather than in each constructor.
421
+
422
+ ``as_positional=None`` keeps the historical behaviour -- positional
423
+ exactly when ``vertex_index`` was supplied -- so callers that never
424
+ pass the flag are unaffected. An explicit ``True``/``False`` overrides
425
+ it, and is the only way to disambiguate a vertex index whose values
426
+ are also valid positions.
427
+
428
+ Parameters
429
+ ----------
430
+ connectivity : np.ndarray
431
+ Edge pairs or face triples.
432
+ vertices : pd.DataFrame
433
+ The processed vertex table; its index supplies the vertex indices.
434
+ as_positional : Optional[bool]
435
+ Whether ``connectivity`` holds positional indices. None infers it.
436
+ vertex_index : Optional[Union[str, np.ndarray]]
437
+ The vertex index argument, used only for the inference above.
438
+ what : str
439
+ Name used in error messages -- "edges" or "faces".
440
+
441
+ Returns
442
+ -------
443
+ np.ndarray
444
+ ``connectivity`` in vertex-index space.
445
+ """
446
+ positional = (
447
+ vertex_index is not None if as_positional is None else bool(as_positional)
448
+ )
449
+ if not positional:
450
+ return connectivity
451
+
452
+ arr = np.asarray(connectivity)
453
+ if arr.size:
454
+ # Without this check, values that are actually vertex indices
455
+ # surface as KeyError from inside fastremap, which says nothing
456
+ # about the convention that was violated.
457
+ low, high = int(arr.min()), int(arr.max())
458
+ if low < 0 or high >= len(vertices):
459
+ if as_positional is None:
460
+ hint = (
461
+ f"`{what}` are read as positional indices because "
462
+ f"`vertex_index` was given; pass "
463
+ f"{what}_as_positional=False if they are vertex "
464
+ "indices already."
465
+ )
466
+ else:
467
+ hint = (
468
+ f"`{what}_as_positional=True` was given, so `{what}` "
469
+ "must be positional indices."
470
+ )
471
+ raise ValueError(
472
+ f"{what} contain values outside the valid positional range "
473
+ f"0..{len(vertices) - 1} (found {low}..{high}). {hint}"
474
+ )
475
+ return fastremap.remap(arr, dict(enumerate(vertices.index)))
476
+
447
477
  def _vertices_to_positional(
448
478
  self,
449
479
  vertices: Optional[np.ndarray],
@@ -697,7 +727,11 @@ class PointMixin(ABC):
697
727
  return mapping.values
698
728
 
699
729
  def _map_index_one_to_one(
700
- self, layer: str, source_index: np.ndarray, validate: bool = False
730
+ self,
731
+ layer: str,
732
+ source_index: np.ndarray,
733
+ validate: bool = False,
734
+ missing: Union[str, int, float] = "raise",
701
735
  ) -> np.ndarray:
702
736
  """Map source indices to single target indices in a one-to-one manner.
703
737
 
@@ -712,6 +746,10 @@ class PointMixin(ABC):
712
746
  Source indices to map from.
713
747
  validate : bool, optional
714
748
  Whether to validate for ambiguous mappings, i.e. multiple targets are possible. Default False.
749
+ missing : Union[str, int, float], optional
750
+ What to do with source vertices that have no mapping. ``"raise"``
751
+ (default) raises a KeyError naming them. Any other value is used to
752
+ fill their slots. Default False.
715
753
 
716
754
  Returns
717
755
  -------
@@ -729,7 +767,36 @@ class PointMixin(ABC):
729
767
  raise ValueError(
730
768
  f"Ambiguous index mapping from {self.layer_name} to {layer}."
731
769
  )
732
- return mapping[~mapping.index.duplicated(keep="first")].loc[source_index].values
770
+ mapping = mapping[~mapping.index.duplicated(keep="first")]
771
+ if isinstance(missing, str):
772
+ if missing != "raise":
773
+ raise ValueError(
774
+ f"missing must be 'raise' or a fill value, got {missing!r}."
775
+ )
776
+ # .loc raises a KeyError naming the unmapped vertices.
777
+ return mapping.loc[source_index].values
778
+ # Look the positions up in numpy rather than reindexing: pandas would
779
+ # upcast an integer Series to float64 to hold the NaN, and vertex ids
780
+ # here routinely exceed 2**53, so they would not survive that round
781
+ # trip. Build the output at the mapping's own dtype instead, and let
782
+ # the caller's choice of fill decide if it has to widen.
783
+ source_index = np.atleast_1d(source_index)
784
+ values = mapping.to_numpy()
785
+ positions = mapping.index.get_indexer(source_index)
786
+ found = positions >= 0
787
+ try:
788
+ out = np.empty(len(source_index), dtype=values.dtype)
789
+ out[found] = values[positions[found]]
790
+ out[~found] = missing
791
+ except (ValueError, OverflowError, TypeError):
792
+ # The fill does not fit the mapping's dtype -- np.nan into an
793
+ # integer array, say. Widen rather than silently truncating, and
794
+ # let the caller live with the consequences they asked for.
795
+ out = np.empty(len(source_index), dtype=object)
796
+ out[found] = values[positions[found]]
797
+ out[~found] = missing
798
+ out = np.asarray(out.tolist())
799
+ return out
733
800
 
734
801
  def _map_index_to_list_of_lists(self, layer: str, source_index: np.ndarray) -> dict:
735
802
  """Map source indices to lists of all corresponding target indices.
@@ -798,8 +865,17 @@ class PointMixin(ABC):
798
865
  right_index=True,
799
866
  how="left",
800
867
  )
868
+ # "majority" is ossify's own reducer, not something pandas understands,
869
+ # so it has to be swapped for the callable wherever it appears -- including
870
+ # inside a per-feature dict, which is the documented way to give different
871
+ # features different aggregations.
801
872
  if agg == "majority":
802
873
  agg = utils.majority_agg()
874
+ elif isinstance(agg, dict):
875
+ agg = {
876
+ key: utils.majority_agg() if value == "majority" else value
877
+ for key, value in agg.items()
878
+ }
803
879
  # Group by target layer and aggregate, then reindex to ensure all target vertices are included
804
880
  grouped_result = mapping_merged.groupby(layer).agg(agg)
805
881
  target_layer_index = self._morphsync.layers[layer].nodes.index
@@ -812,6 +888,7 @@ class PointMixin(ABC):
812
888
  as_positional: bool,
813
889
  how: str,
814
890
  validate: bool = False,
891
+ missing: Union[str, int, float] = "raise",
815
892
  ) -> Union[np.ndarray, dict]:
816
893
  """Master function for mapping indices from source to target layer with various strategies.
817
894
 
@@ -847,7 +924,10 @@ class PointMixin(ABC):
847
924
  match how:
848
925
  case "one_to_one":
849
926
  mapping = self._map_index_one_to_one(
850
- layer=layer, source_index=source_index, validate=validate
927
+ layer=layer,
928
+ source_index=source_index,
929
+ validate=validate,
930
+ missing=missing,
851
931
  )
852
932
  case "range_to_range":
853
933
  mapping = self._map_range_to_range(
@@ -883,6 +963,7 @@ class PointMixin(ABC):
883
963
  source_index: Optional[np.ndarray] = None,
884
964
  as_positional: bool = False,
885
965
  validate: bool = False,
966
+ missing: Union[str, int, float] = "raise",
886
967
  ) -> np.ndarray:
887
968
  """Map each vertex index from the current layer to a single index in the specified layer.
888
969
 
@@ -896,6 +977,18 @@ class PointMixin(ABC):
896
977
  Whether to treat source_index and mapped index as positional (i_th element of the array) or as a dataframe index.
897
978
  validate : bool
898
979
  Whether to raise an error is the mapping is ambiguous, i.e. it is not clear which target index to use.
980
+ missing : Union[str, int, float]
981
+ What to do with vertices that have no mapping to ``layer``.
982
+ ``"raise"`` (default) raises a KeyError naming them. Anything else
983
+ is used to fill their slots -- ``missing=-1`` is the usual choice.
984
+
985
+ The fill is yours to pick rather than the library's, because it
986
+ decides the result's dtype. An integer keeps the array integral,
987
+ which matters here: vertex ids are routinely above 2**53, where a
988
+ float64 round trip silently changes them. ``missing=np.nan`` is
989
+ allowed and does exactly that, so only reach for it when the ids
990
+ are small. Use :meth:`get_unmapped_vertices` to find which
991
+ vertices are unmapped in the first place.
899
992
 
900
993
  Returns
901
994
  -------
@@ -911,6 +1004,7 @@ class PointMixin(ABC):
911
1004
  as_positional=as_positional,
912
1005
  how="one_to_one",
913
1006
  validate=validate,
1007
+ missing=missing,
914
1008
  )
915
1009
  )
916
1010
 
@@ -1082,35 +1176,65 @@ class PointMixin(ABC):
1082
1176
  self,
1083
1177
  mask: np.ndarray,
1084
1178
  as_positional: bool = False,
1179
+ return_cell: Optional[bool] = None,
1085
1180
  self_only: bool = False,
1086
1181
  ) -> Union[Self, "Cell"]:
1087
- """Apply a mask on the current layer. Returns a new object with the masked morphsync.
1088
- If the object is associated with a CellSync, a new CellSync will be created, otherwise
1089
- a new object of the same class will be returned.
1182
+ """Apply a mask to this layer.
1183
+
1184
+ When the layer belongs to a :class:`Cell`, the mask propagates to every
1185
+ linked layer -- that is what links are for. What comes back is either
1186
+ that masked cell or this layer's masked counterpart from it.
1187
+
1188
+ .. deprecated:: 0.3
1189
+ The default return is changing. Today, calling this without
1190
+ ``return_cell`` returns the masked :class:`Cell` and warns; from
1191
+ 1.0 it will return a masked layer, since a layer is the thing you
1192
+ asked to mask and can stand on its own. Pass ``return_cell``
1193
+ explicitly to fix the behaviour either way and silence the warning.
1090
1194
 
1091
- Properties
1195
+ Parameters
1092
1196
  ----------
1093
1197
  mask: np.ndarray
1094
1198
  The mask to apply, either in boolean, vertex index, or positional index form.
1095
1199
  as_positional: bool
1096
1200
  If providing indices, specify if they are positional indices (True) or vertex indices (False).
1201
+ return_cell: Optional[bool]
1202
+ True returns the masked :class:`Cell`, False returns this layer's
1203
+ masked counterpart from it. Leaving it unset keeps today's
1204
+ behaviour, True, and warns that the default becomes False at 1.0.
1097
1205
  self_only: bool
1098
- If True, only apply the mask to the current object and not to any associated CellSync.
1206
+ Mask only this layer, leaving any linked layers out of it entirely.
1207
+ The result is a standalone layer, not attached to a cell. Differs
1208
+ from the default, which masks the whole cell and then hands back
1209
+ this layer from it.
1099
1210
 
1100
1211
  Returns
1101
1212
  -------
1102
- masked_object Union[Self, "CellSync"]
1103
- Either a new object of the same class or a new CellSync will be returned.
1213
+ Union[Self, "Cell"]
1214
+ A masked layer of the same class, or the masked Cell when
1215
+ ``return_cell`` is True.
1104
1216
  """
1105
1217
  new_morphsync = self._mask_morphsync(mask=mask, as_positional=as_positional)
1106
1218
  if self._cell is None or self_only:
1107
1219
  return self.__class__._from_existing(
1108
1220
  new_morphsync=new_morphsync, old_obj=self
1109
1221
  )
1110
- else:
1111
- return self._cell.__class__._from_existing(
1112
- new_morphsync=new_morphsync, old_obj=self._cell
1222
+ if return_cell is None:
1223
+ warn(
1224
+ f"{type(self).__name__}.apply_mask currently returns a Cell, but "
1225
+ "from ossify 1.0 it will return a masked layer. Pass "
1226
+ "return_cell=True to keep the current behaviour, or "
1227
+ "return_cell=False to opt into the new one.",
1228
+ FutureWarning,
1229
+ stacklevel=2,
1113
1230
  )
1231
+ return_cell = True
1232
+ new_cell = self._cell.__class__._from_existing(
1233
+ new_morphsync=new_morphsync, old_obj=self._cell
1234
+ )
1235
+ if return_cell:
1236
+ return new_cell
1237
+ return new_cell._all_objects[self.name]
1114
1238
 
1115
1239
  def copy(self) -> Self:
1116
1240
  """Create a deep copy of the current object.
@@ -1165,25 +1289,32 @@ class PointMixin(ABC):
1165
1289
  reset()
1166
1290
 
1167
1291
  @contextlib.contextmanager
1168
- def mask_context(self, mask: np.ndarray) -> Generator[Self, None, None]:
1292
+ def mask_context(
1293
+ self, mask: np.ndarray, return_cell: Optional[bool] = None
1294
+ ) -> Generator[Self, None, None]:
1169
1295
  """Context manager to temporarily apply a mask via the current layer.
1170
1296
 
1171
1297
  Parameters
1172
1298
  ----------
1173
1299
  mask: np.ndarray
1174
1300
  The mask to apply, either in boolean, vertex index, or positional index form.
1301
+ return_cell: Optional[bool]
1302
+ What to yield: the masked :class:`Cell` (True) or this layer's
1303
+ masked counterpart (False). Follows :meth:`apply_mask`, including
1304
+ its deprecation -- unset yields a Cell today and warns that it will
1305
+ yield a layer from 1.0.
1175
1306
 
1176
1307
  Yields
1177
1308
  ------
1178
1309
  Self
1179
- A new object of the same class with the mask applied.
1310
+ The masked object, per ``return_cell``.
1180
1311
 
1181
1312
  Example
1182
1313
  -------
1183
- >>> with cell.skeleton.mask_context(mask) as masked_cell:
1184
- >>> masked_path_length = masked_cell.mesh.surface_area()
1314
+ >>> with cell.skeleton.mask_context(mask, return_cell=True) as masked_cell:
1315
+ >>> masked_area = masked_cell.mesh.surface_area()
1185
1316
  """
1186
- new_self = self.apply_mask(mask=mask)
1317
+ new_self = self.apply_mask(mask=mask, return_cell=return_cell)
1187
1318
  try:
1188
1319
  yield new_self
1189
1320
  finally:
@@ -1239,10 +1370,14 @@ class PointMixin(ABC):
1239
1370
  all_unmapped_indices = []
1240
1371
 
1241
1372
  for target_layer in target_layers:
1242
- # Get mapping with nulls preserved
1373
+ # Get mapping with nulls preserved. Source is *this* layer: the
1374
+ # question is which of its vertices fail to reach the target. With
1375
+ # these swapped the method returned the target layer's vertices
1376
+ # instead, so mask_out_unmapped compared two disjoint index spaces
1377
+ # and removed nothing.
1243
1378
  mapping = self._morphsync.get_mapping(
1244
- source=target_layer,
1245
- target=self.layer_name,
1379
+ source=self.layer_name,
1380
+ target=target_layer,
1246
1381
  dropna=False,
1247
1382
  )
1248
1383
 
@@ -1261,9 +1396,83 @@ class PointMixin(ABC):
1261
1396
 
1262
1397
  return unique_unmapped
1263
1398
 
1399
+ def mapping_coverage(self, layer: str) -> float:
1400
+ """Fraction of this layer's vertices that map to ``layer``.
1401
+
1402
+ Mapping completeness is directional: every mesh vertex may reach the
1403
+ graph while some graph vertices are reached by no mesh vertex, so ask
1404
+ in the direction you intend to use.
1405
+
1406
+ Parameters
1407
+ ----------
1408
+ layer : str
1409
+ The target layer name.
1410
+
1411
+ Returns
1412
+ -------
1413
+ float
1414
+ Between 0.0 and 1.0. Returns 1.0 for a layer with no vertices.
1415
+ """
1416
+ if self.n_vertices == 0:
1417
+ return 1.0
1418
+ mapping = self._morphsync.get_mapping(
1419
+ source=self.layer_name, target=layer, dropna=False
1420
+ )
1421
+ null = mapping.isna()
1422
+ if not null.any():
1423
+ return 1.0
1424
+ # A mapping can be one-to-many -- one skeleton vertex, several synapses
1425
+ # -- so the Series has repeated index entries. Count distinct unmapped
1426
+ # *vertices*, not null rows, or the fraction runs past 1. This is the
1427
+ # expensive half, which is why the complete case returns above.
1428
+ n_unmapped = mapping.index[null].nunique()
1429
+ return float(1.0 - n_unmapped / self.n_vertices)
1430
+
1431
+ def is_fully_mapped_to(self, layer: str) -> bool:
1432
+ """Whether every vertex of this layer maps to ``layer``.
1433
+
1434
+ The cheap precondition check for operations that need a total mapping,
1435
+ in the spirit of a mesh's ``is_watertight``: an incompletely mapped
1436
+ cell is perfectly well defined, but not every operation is meaningful
1437
+ on it. :meth:`map_index_to_layer` raises by default rather than
1438
+ inventing a value for the vertices that have no counterpart.
1439
+
1440
+ Note that partial coverage is not always a defect. A sparse annotation
1441
+ such as synapses is *expected* to reach only a few of the skeleton's
1442
+ vertices; it is a mesh that fails to cover the arbor that is a problem.
1443
+
1444
+ Parameters
1445
+ ----------
1446
+ layer : str
1447
+ The target layer name.
1448
+
1449
+ Returns
1450
+ -------
1451
+ bool
1452
+ True when no vertex of this layer is unmapped.
1453
+
1454
+ See Also
1455
+ --------
1456
+ get_unmapped_vertices : which vertices are unmapped.
1457
+ mapping_coverage : the fraction that are mapped.
1458
+ """
1459
+ if self.n_vertices == 0:
1460
+ return True
1461
+ # Only asks whether any hole exists, so it skips the distinct-vertex
1462
+ # count that mapping_coverage needs. That is the point: this is meant
1463
+ # to be cheap enough to call before an operation, not after.
1464
+ return (
1465
+ not self._morphsync.get_mapping(
1466
+ source=self.layer_name, target=layer, dropna=False
1467
+ )
1468
+ .isna()
1469
+ .any()
1470
+ )
1471
+
1264
1472
  def mask_out_unmapped(
1265
1473
  self,
1266
1474
  target_layers: Optional[Union[str, List[str]]] = None,
1475
+ return_cell: Optional[bool] = None,
1267
1476
  self_only: bool = False,
1268
1477
  ) -> Union[Self, "Cell"]:
1269
1478
  """Create a new object with unmapped vertices removed.
@@ -1317,7 +1526,10 @@ class PointMixin(ABC):
1317
1526
 
1318
1527
  # Apply mask using existing functionality
1319
1528
  return self.apply_mask(
1320
- mask=keep_indices, as_positional=False, self_only=self_only
1529
+ mask=keep_indices,
1530
+ as_positional=False,
1531
+ return_cell=return_cell,
1532
+ self_only=self_only,
1321
1533
  )
1322
1534
 
1323
1535
  def describe(self) -> None:
@@ -1498,6 +1710,7 @@ class GraphLayer(PointMixin, EdgeMixin):
1498
1710
  spatial_columns: Optional[list] = None,
1499
1711
  *,
1500
1712
  vertex_index: Optional[Union[str, np.ndarray]] = None,
1713
+ edges_as_positional: Optional[bool] = None,
1501
1714
  features: Optional[Union[dict, pd.DataFrame]] = None,
1502
1715
  morphsync: MorphSync = None,
1503
1716
  linkage: Optional[Link] = None,
@@ -1515,8 +1728,9 @@ class GraphLayer(PointMixin, EdgeMixin):
1515
1728
  self._cell = None
1516
1729
 
1517
1730
  if not existing:
1518
- if vertex_index:
1519
- edges = self._map_edges_to_index(edges, vertices.index)
1731
+ edges = self._index_connectivity(
1732
+ edges, vertices, edges_as_positional, vertex_index, "edges"
1733
+ )
1520
1734
  self._morphsync.add_graph(
1521
1735
  graph=(vertices, edges),
1522
1736
  name=self.layer_name,
@@ -1869,6 +2083,8 @@ class SkeletonLayer(GraphLayer):
1869
2083
  root: Optional[int] = None,
1870
2084
  *,
1871
2085
  vertex_index: Optional[Union[str, np.ndarray]] = None,
2086
+ edges_as_positional: Optional[bool] = None,
2087
+ root_as_positional: bool = False,
1872
2088
  features: Optional[Union[dict, pd.DataFrame]] = None,
1873
2089
  morphsync: MorphSync = None,
1874
2090
  linkage: Optional[dict] = None,
@@ -1885,8 +2101,9 @@ class SkeletonLayer(GraphLayer):
1885
2101
 
1886
2102
  if inherited_properties is None:
1887
2103
  # Add as a morphsync layer
1888
- if vertex_index:
1889
- edges = self._map_edges_to_index(edges, vertices.index)
2104
+ edges = self._index_connectivity(
2105
+ edges, vertices, edges_as_positional, vertex_index, "edges"
2106
+ )
1890
2107
  self._morphsync.add_graph(
1891
2108
  graph=(vertices, edges),
1892
2109
  name=self.layer_name,
@@ -1895,11 +2112,13 @@ class SkeletonLayer(GraphLayer):
1895
2112
  self._setup_linkage(linkage)
1896
2113
 
1897
2114
  # Establish the root and then build the base properties
1898
- self._root = self._infer_root(root)
2115
+ self._root = self._infer_root(root, as_positional=root_as_positional)
1899
2116
  self._dag_cache = gf.DAGCache(
1900
2117
  root=self.root_positional
1901
2118
  ) # Cache of properties associated with rooted skeletons
1902
- self._dag_cache.parent_node_array = self._apply_root_to_edges(root)
2119
+ # Use the resolved root, not the raw argument: _infer_root may have
2120
+ # converted it out of positional space or inferred it from the edges.
2121
+ self._dag_cache.parent_node_array = self._apply_root_to_edges(self._root)
1903
2122
 
1904
2123
  self._set_base_properties(
1905
2124
  base_properties={
@@ -2241,30 +2460,52 @@ class SkeletonLayer(GraphLayer):
2241
2460
  if np.array_equal(self.vertex_index, self.base_vertex_index):
2242
2461
  self._base_properties["base_csgraph"] = self.csgraph
2243
2462
 
2244
- def _infer_root(self, root: Optional[int]) -> int:
2463
+ def _infer_root(self, root: Optional[int], as_positional: bool = False) -> int:
2245
2464
  """Infer the root node from the graph structure or validate provided root.
2246
2465
 
2247
2466
  Parameters
2248
2467
  ----------
2249
2468
  root : Optional[int]
2250
- Proposed root node index. If None, attempts to infer from graph structure.
2469
+ Proposed root. By default a **vertex index** -- the same space as
2470
+ ``vertex_index``, not a positional index. Note this differs from
2471
+ ``edges``, which are positional when ``vertex_index`` is supplied;
2472
+ pass ``as_positional=True`` to use that space here instead.
2473
+ If None, attempts to infer from graph structure.
2474
+ as_positional : bool
2475
+ Whether ``root`` is a positional index into this layer's vertices.
2476
+ Default False, matching ``as_positional`` everywhere else.
2251
2477
 
2252
2478
  Returns
2253
2479
  -------
2254
2480
  int
2255
- The root node index.
2481
+ The root vertex index.
2256
2482
 
2257
2483
  Raises
2258
2484
  ------
2259
2485
  ValueError
2260
- If no root specified and multiple potential roots found.
2486
+ If the given root is not one of this layer's vertices, or if no
2487
+ root was specified and multiple potential roots were found.
2261
2488
  """
2262
2489
  if root is not None:
2263
- return int(root)
2490
+ if as_positional:
2491
+ # Positional in, vertex index out: `root` is stored and
2492
+ # returned as a vertex index whichever space it arrived in.
2493
+ root = int(self.vertex_index[int(root)])
2494
+ root = int(root)
2495
+ # Numpy membership rather than building a Python set: a layer can
2496
+ # have millions of vertices and this runs on every construction.
2497
+ if not np.any(self.vertex_index == root):
2498
+ raise ValueError(
2499
+ f"root {root} is not a vertex of this layer. `root` is a "
2500
+ "vertex index, not a positional index -- note that `edges` "
2501
+ "use the opposite convention when `vertex_index` is given."
2502
+ )
2503
+ return root
2264
2504
  else:
2265
2505
  potential_roots = np.flatnonzero(self.csgraph_binary.sum(axis=1) == 0)
2266
2506
  if len(potential_roots) == 1:
2267
- return int(potential_roots[0])
2507
+ # ``potential_roots`` is positional; the root is a vertex index.
2508
+ return int(self.vertex_index[potential_roots[0]])
2268
2509
  else:
2269
2510
  raise ValueError(
2270
2511
  "No root specified and edges are not consistent with a single root. Please set a valid root."
@@ -2336,6 +2577,16 @@ class SkeletonLayer(GraphLayer):
2336
2577
  edges_positional_new[:, ii]
2337
2578
  ]
2338
2579
 
2580
+ # The edges just changed direction, but ``csgraph``/``csgraph_binary``
2581
+ # were built (by the connected_components call above) from the *old*
2582
+ # orientation. Everything read off the directed graph -- branch points,
2583
+ # end points, segments, cover paths -- would otherwise be computed from
2584
+ # a stale graph that disagrees with ``edges_positional``. Drop only the
2585
+ # edge-derived caches: the DAG cache holds root/parent state that the
2586
+ # callers set around this method.
2587
+ self._csgraph = None
2588
+ self._csgraph_binary = None
2589
+
2339
2590
  def reroot(self, new_root: int, as_positional=False) -> Self:
2340
2591
  """Reroot to a new index. Important: that this will reset any inherited properties from an unmasked skeleton!
2341
2592
 
@@ -2537,8 +2788,11 @@ class SkeletonLayer(GraphLayer):
2537
2788
  ds_inds = gf.get_subtree_nodes(
2538
2789
  subtree_root=vertex[0], edges=self.edges_positional
2539
2790
  )
2540
- if inclusive:
2541
- ds_inds = np.concatenate(([vertex[0]], ds_inds))
2791
+ # get_subtree_nodes already returns the subtree root, so `inclusive`
2792
+ # had it backwards: False still contained the vertex, and True listed
2793
+ # it twice.
2794
+ if not inclusive:
2795
+ ds_inds = ds_inds[ds_inds != vertex[0]]
2542
2796
  if as_positional:
2543
2797
  return ds_inds
2544
2798
  else:
@@ -2641,7 +2895,7 @@ class SkeletonLayer(GraphLayer):
2641
2895
  A list of cover paths, each path is a list of vertex indices, ordered as the typical `cover_paths` method.
2642
2896
  """
2643
2897
  sources, as_positional = self._vertices_to_positional(sources, as_positional)
2644
- cps = gf.compute_cover_paths(
2898
+ cps = gf.build_cover_paths(
2645
2899
  sources,
2646
2900
  self.parent_node_array,
2647
2901
  self.distance_to_root(as_positional=True),
@@ -2696,10 +2950,14 @@ class SkeletonLayer(GraphLayer):
2696
2950
  List[np.ndarray]
2697
2951
  List of segment arrays including parent nodes in positional indices.
2698
2952
  """
2699
- segs = self.segments_positional
2700
- return [
2701
- np.concatenate((seg, [self.parent_node_array[seg[-1]]])) for seg in segs
2702
- ]
2953
+ # The root's segment has no parent, and -1 is the sentinel for that.
2954
+ # Appending it would put -1 into a list of positional indices, which
2955
+ # then reads as the *last* vertex once mapped through vertex_index.
2956
+ out = []
2957
+ for seg in self.segments_positional:
2958
+ parent = self.parent_node_array[seg[-1]]
2959
+ out.append(np.concatenate((seg, [parent])) if parent != -1 else seg)
2960
+ return out
2703
2961
 
2704
2962
  @property
2705
2963
  def segments_plus(self) -> List[np.ndarray]:
@@ -2710,7 +2968,10 @@ class SkeletonLayer(GraphLayer):
2710
2968
  List[np.ndarray]
2711
2969
  List of segment arrays including parent nodes in dataframe indices.
2712
2970
  """
2713
- return [self.vertices[seg] for seg in self.segments_plus_positional]
2971
+ # ``self.vertices`` is the Nx3 coordinate array, so indexing it here
2972
+ # returned coordinates from a property documented -- and named, next to
2973
+ # ``segments`` -- to return vertex indices.
2974
+ return [self.vertex_index[seg] for seg in self.segments_plus_positional]
2714
2975
 
2715
2976
  @property
2716
2977
  def segment_map(self) -> np.ndarray:
@@ -2747,7 +3008,10 @@ class SkeletonLayer(GraphLayer):
2747
3008
  capped_segs, capped_seg_map = gf.build_capped_segments(
2748
3009
  segments, self.vertices, max_length
2749
3010
  )
2750
- if positional:
3011
+ # ``build_capped_segments`` works in positional space, so it is the
3012
+ # *index* form that needs mapping. This test was inverted, returning
3013
+ # vertex indices for positional=True and positions for positional=False.
3014
+ if not positional:
2751
3015
  capped_segs = [self.vertex_index[seg] for seg in capped_segs]
2752
3016
  return capped_segs, capped_seg_map
2753
3017
 
@@ -3479,6 +3743,7 @@ class MeshLayer(FaceMixin, PointMixin):
3479
3743
  spatial_columns: Optional[list] = None,
3480
3744
  *,
3481
3745
  vertex_index: Optional[Union[str, np.ndarray]] = None,
3746
+ faces_as_positional: Optional[bool] = None,
3482
3747
  features: Optional[Union[dict, pd.DataFrame]] = None,
3483
3748
  morphsync: MorphSync = None,
3484
3749
  linkage: Optional[Link] = None,
@@ -3496,8 +3761,9 @@ class MeshLayer(FaceMixin, PointMixin):
3496
3761
  self._cell = None
3497
3762
 
3498
3763
  if not existing:
3499
- if vertex_index:
3500
- faces = self._map_faces_to_index(faces, vertices.index)
3764
+ faces = self._index_connectivity(
3765
+ faces, vertices, faces_as_positional, vertex_index, "faces"
3766
+ )
3501
3767
  self._morphsync.add_mesh(
3502
3768
  mesh=(vertices, faces),
3503
3769
  name=self.layer_name,
@@ -981,7 +981,31 @@ def plot_points(
981
981
  # Single color string
982
982
  scatter_kws["color"] = colors
983
983
  else:
984
- scatter_kws["c"] = colors
984
+ colors_arr = np.asarray(colors)
985
+ single_rgba = (
986
+ colors_arr.ndim == 1
987
+ and colors_arr.shape[0] in (3, 4)
988
+ and np.issubdtype(colors_arr.dtype, np.number)
989
+ and colors_arr.shape[0] != len(points_proj)
990
+ )
991
+ if single_rgba:
992
+ # One bare RGB/RGBA tuple means "this exact color", but as `c`
993
+ # it is ambiguous with one scalar value per point, and
994
+ # matplotlib warns. A 2-D single row is its documented way to
995
+ # say the former. Reached via root_marker, whose color is read
996
+ # off the root vertex as a single RGBA.
997
+ colors_arr = colors_arr.reshape(1, -1)
998
+ if (
999
+ colors_arr.ndim == 2
1000
+ and colors_arr.shape[1] in (3, 4)
1001
+ and np.issubdtype(colors_arr.dtype, np.number)
1002
+ ):
1003
+ # Explicit RGB/RGBA values are not colormapped, so a cmap set
1004
+ # from a string palette above would be silently ignored --
1005
+ # matplotlib says so out loud. Drop it and its norm.
1006
+ for key in ("cmap", "vmin", "vmax"):
1007
+ scatter_kws.pop(key, None)
1008
+ scatter_kws["c"] = colors_arr
985
1009
 
986
1010
  ax.scatter(
987
1011
  x=points_proj[:, 0],
@@ -1,7 +1,6 @@
1
1
  from enum import IntEnum
2
2
  from typing import TYPE_CHECKING, Literal, Optional, Tuple, Union
3
3
 
4
- import fastremap
5
4
  import numpy as np
6
5
  import pandas as pd
7
6
 
@@ -310,13 +309,10 @@ def load_cell_from_client(
310
309
  l2_df = l2_df.reset_index()
311
310
 
312
311
  if restore_graph:
313
- l2_graph = client.chunkedgraph.level2_chunk_graph(root_id)
314
- l2_map = {v: k for k, v in l2_df["l2_id"].to_dict().items()}
315
-
316
- edges = fastremap.remap(
317
- l2_graph,
318
- l2_map,
319
- )
312
+ # The chunkedgraph gives edges as l2_id pairs, which is what the graph
313
+ # is indexed by, so hand them over as-is rather than round-tripping
314
+ # them through positional indices and straight back again.
315
+ edges = client.chunkedgraph.level2_chunk_graph(root_id)
320
316
  else:
321
317
  edges = []
322
318
 
@@ -335,6 +331,7 @@ def load_cell_from_client(
335
331
  spatial_columns=l2_spatial_columns,
336
332
  edges=edges,
337
333
  vertex_index="l2_id",
334
+ edges_as_positional=False,
338
335
  )
339
336
  .add_skeleton(
340
337
  vertices=np.array(sk["vertices"]),
@@ -79,7 +79,10 @@ def process_vertices(
79
79
  )
80
80
  spatial_columns = vertices.columns
81
81
  else:
82
- if vertex_index:
82
+ # Only a string names a column to hold out of the implicit features; an
83
+ # array-like vertex_index supplies the ids directly. Plain truthiness
84
+ # raises on an array of more than one element.
85
+ if isinstance(vertex_index, str):
83
86
  implicit_feature_columns = list(
84
87
  vertices.columns[
85
88
  ~vertices.columns.isin(spatial_columns + [vertex_index])
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes