ossify 0.2.8__tar.gz → 0.3.1__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.8 → ossify-0.3.1}/PKG-INFO +1 -1
  2. {ossify-0.2.8 → ossify-0.3.1}/pyproject.toml +2 -2
  3. ossify-0.3.1/scripts/build_example_cell.py +102 -0
  4. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/__init__.py +1 -1
  5. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/base.py +13 -1
  6. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/base.py +66 -13
  7. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/data_layers.py +319 -37
  8. {ossify-0.2.8 → ossify-0.3.1}/.github/workflows/mkdocs_publish.yml +0 -0
  9. {ossify-0.2.8 → ossify-0.3.1}/.github/workflows/python-package.yml +0 -0
  10. {ossify-0.2.8 → ossify-0.3.1}/.gitignore +0 -0
  11. {ossify-0.2.8 → ossify-0.3.1}/.pre-commit-config.yaml +0 -0
  12. {ossify-0.2.8 → ossify-0.3.1}/LICENSE +0 -0
  13. {ossify-0.2.8 → ossify-0.3.1}/README.md +0 -0
  14. {ossify-0.2.8 → ossify-0.3.1}/mkdocs.yml +0 -0
  15. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/__init__.py +0 -0
  16. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/graph.py +0 -0
  17. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/mapping.py +0 -0
  18. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/mesh.py +0 -0
  19. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/morph.py +0 -0
  20. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/points.py +0 -0
  21. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/_sync/table.py +0 -0
  22. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/algorithms.py +0 -0
  23. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/compartment_models/minnie65_ds15_us0_bd0.json +0 -0
  24. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/compartment_models/v1dd_ds15_us0_bd0.json +0 -0
  25. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/compartment_models/xgb/minnie65_ds15_us0_bd0.ubj +0 -0
  26. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/compartment_models/xgb/v1dd_ds15_us0_bd0.ubj +0 -0
  27. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/compartments.py +0 -0
  28. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/file_io.py +0 -0
  29. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/graph_functions.py +0 -0
  30. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/plot.py +0 -0
  31. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/plot3d.py +0 -0
  32. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/plot_utils.py +0 -0
  33. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/structured_prediction.py +0 -0
  34. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/sync_classes.py +0 -0
  35. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/translate.py +0 -0
  36. {ossify-0.2.8 → ossify-0.3.1}/src/ossify/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ossify
3
- Version: 0.2.8
3
+ Version: 0.3.1
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.8"
9
+ version = "0.3.1"
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.8"
98
+ current_version = "0.3.1"
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.8"
8
+ __version__ = "0.3.1"
9
9
 
10
10
 
11
11
  def __getattr__(name):
@@ -272,7 +272,19 @@ def mask_and_remap(
272
272
  """
273
273
  if np.array(mask).dtype == bool:
274
274
  mask = np.where(mask)[0]
275
- return _mask_and_remap(np.array(arr, dtype=int), mask)
275
+ arr = np.array(arr, dtype=int)
276
+ mask = np.asarray(mask)
277
+ n = len(mask)
278
+ # Fast path: when the node index is already 0..n-1, index space and
279
+ # positional space coincide, so the remap is the identity and the only
280
+ # thing it can do is drop rows pointing outside the range -- and there are
281
+ # none. Worth special-casing because the general path below builds a Python
282
+ # dict and a Python list with one entry per node, which dominates
283
+ # everything else on a mesh with millions of vertices.
284
+ if n and (arr.size == 0 or (arr.min() >= 0 and arr.max() < n)):
285
+ if mask[0] == 0 and mask[-1] == n - 1 and np.array_equal(mask, np.arange(n)):
286
+ return arr
287
+ return _mask_and_remap(arr, mask)
276
288
 
277
289
 
278
290
  def _mask_and_remap(
@@ -470,6 +470,7 @@ class Cell:
470
470
  *,
471
471
  vertex_index: Optional[Union[str, np.ndarray]] = None,
472
472
  edges_as_positional: Optional[bool] = None,
473
+ root_as_positional: bool = False,
473
474
  linkage: Optional[Link] = None,
474
475
  spatial_columns: Optional[list] = None,
475
476
  inherited_properties: Optional[dict] = None,
@@ -494,6 +495,11 @@ class Cell:
494
495
  opposite convention to ``edges``, which are positional when
495
496
  ``vertex_index`` is given. Required if the edges are not already
496
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.
497
503
  vertex_index : Optional[Union[str, np.ndarray]]
498
504
  Vertex indices to label the skeleton's vertices by: either the name of
499
505
  a column in ``vertices``, or an array with one value per vertex.
@@ -530,6 +536,7 @@ class Cell:
530
536
  edges_as_positional=edges_as_positional,
531
537
  features=features,
532
538
  root=root,
539
+ root_as_positional=root_as_positional,
533
540
  morphsync=self._morphsync,
534
541
  spatial_columns=spatial_columns,
535
542
  linkage=linkage,
@@ -1025,7 +1032,39 @@ class Cell:
1025
1032
 
1026
1033
  return self
1027
1034
 
1028
- 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:
1029
1068
  """Generate a hierarchical summary description of the cell and its layers.
1030
1069
 
1031
1070
  Provides a tree-like overview including:
@@ -1038,6 +1077,12 @@ class Cell:
1038
1077
  html : bool, optional
1039
1078
  If True, create expandable HTML widgets in Jupyter.
1040
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.
1041
1086
 
1042
1087
  Returns
1043
1088
  -------
@@ -1048,13 +1093,14 @@ class Cell:
1048
1093
  --------
1049
1094
  >>> cell.describe() # Prints formatted string
1050
1095
  >>> cell.describe(html=True) # Shows HTML widgets in Jupyter
1096
+ >>> cell.describe(coverage=False) # Skip the mapping-coverage walk
1051
1097
  """
1052
1098
  if html:
1053
1099
  self._describe_html()
1054
1100
  else:
1055
- print(self._describe_text())
1101
+ print(self._describe_text(coverage=coverage))
1056
1102
 
1057
- def _describe_text(self) -> str:
1103
+ def _describe_text(self, coverage: bool = True) -> str:
1058
1104
  """Generate text-based hierarchical description."""
1059
1105
  lines = []
1060
1106
 
@@ -1102,9 +1148,11 @@ class Cell:
1102
1148
  vertex_count = len(layer_obj.vertices)
1103
1149
 
1104
1150
  if hasattr(layer_obj, "faces"): # Mesh layers
1105
- face_count = (
1106
- len(layer_obj.faces) if len(layer_obj.faces.shape) > 1 else 0
1107
- )
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
1108
1156
  lines.append(
1109
1157
  f"│ {prefix} {layer_name}: {vertex_count} vertices, {face_count} faces"
1110
1158
  )
@@ -1162,12 +1210,16 @@ class Cell:
1162
1210
  # Check if bidirectional link exists
1163
1211
  if reverse_key in self._morphsync.links:
1164
1212
  # Bidirectional link
1165
- link_display_items.append(f"{source} <-> {target}")
1213
+ link_display_items.append(
1214
+ f"{source} <-> {target}{self._coverage_note(source, target, coverage)}"
1215
+ )
1166
1216
  processed_pairs.add(link_key)
1167
1217
  processed_pairs.add(reverse_key)
1168
1218
  else:
1169
1219
  # Unidirectional link
1170
- link_display_items.append(f"{source} → {target}")
1220
+ link_display_items.append(
1221
+ f"{source} → {target}{self._coverage_note(source, target, coverage)}"
1222
+ )
1171
1223
  processed_pairs.add(link_key)
1172
1224
 
1173
1225
  # Show the actual number of connection pairs being displayed
@@ -1414,9 +1466,8 @@ class Cell:
1414
1466
  vertex_count = len(layer_obj.vertices)
1415
1467
 
1416
1468
  if hasattr(layer_obj, "faces"):
1417
- face_count = (
1418
- len(layer_obj.faces) if len(layer_obj.faces.shape) > 1 else 0
1419
- )
1469
+ faces = layer_obj.faces # remaps on access; bind once
1470
+ face_count = len(faces) if faces.ndim > 1 else 0
1420
1471
  details = f"vertices: {vertex_count:,} | faces: {face_count:,}"
1421
1472
  elif hasattr(layer_obj, "edges"):
1422
1473
  edge_count = (
@@ -1457,10 +1508,12 @@ class Cell:
1457
1508
  vertex_count = len(layer.vertices)
1458
1509
 
1459
1510
  if hasattr(layer, "faces"):
1460
- 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
1461
1513
  details = f"vertices: {vertex_count:,} | faces: {face_count:,}"
1462
1514
  elif hasattr(layer, "edges"):
1463
- 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
1464
1517
  details = f"vertices: {vertex_count:,} | edges: {edge_count:,}"
1465
1518
  else:
1466
1519
  details = f"vertices: {vertex_count:,}"
@@ -301,7 +301,7 @@ class FaceMixin(ABC):
301
301
  def surface_area(
302
302
  self,
303
303
  vertices: Optional[np.ndarray] = None,
304
- as_positional: bool = True,
304
+ as_positional: bool = False,
305
305
  inclusive: bool = False,
306
306
  ) -> float:
307
307
  """Calculate the surface area of the mesh, or a subset of vertices.
@@ -311,7 +311,8 @@ class FaceMixin(ABC):
311
311
  vertices : Optional[np.ndarray], optional
312
312
  Vertex indices to calculate surface area for. If None, uses entire mesh.
313
313
  as_positional : bool, optional
314
- 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.
315
316
  inclusive : bool, optional
316
317
  Whether to include faces that are covered by any vertex (True) or only those fully covered (False). Default False.
317
318
 
@@ -726,7 +727,11 @@ class PointMixin(ABC):
726
727
  return mapping.values
727
728
 
728
729
  def _map_index_one_to_one(
729
- 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",
730
735
  ) -> np.ndarray:
731
736
  """Map source indices to single target indices in a one-to-one manner.
732
737
 
@@ -741,6 +746,10 @@ class PointMixin(ABC):
741
746
  Source indices to map from.
742
747
  validate : bool, optional
743
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.
744
753
 
745
754
  Returns
746
755
  -------
@@ -758,7 +767,36 @@ class PointMixin(ABC):
758
767
  raise ValueError(
759
768
  f"Ambiguous index mapping from {self.layer_name} to {layer}."
760
769
  )
761
- 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
762
800
 
763
801
  def _map_index_to_list_of_lists(self, layer: str, source_index: np.ndarray) -> dict:
764
802
  """Map source indices to lists of all corresponding target indices.
@@ -850,6 +888,7 @@ class PointMixin(ABC):
850
888
  as_positional: bool,
851
889
  how: str,
852
890
  validate: bool = False,
891
+ missing: Union[str, int, float] = "raise",
853
892
  ) -> Union[np.ndarray, dict]:
854
893
  """Master function for mapping indices from source to target layer with various strategies.
855
894
 
@@ -885,7 +924,10 @@ class PointMixin(ABC):
885
924
  match how:
886
925
  case "one_to_one":
887
926
  mapping = self._map_index_one_to_one(
888
- layer=layer, source_index=source_index, validate=validate
927
+ layer=layer,
928
+ source_index=source_index,
929
+ validate=validate,
930
+ missing=missing,
889
931
  )
890
932
  case "range_to_range":
891
933
  mapping = self._map_range_to_range(
@@ -921,6 +963,7 @@ class PointMixin(ABC):
921
963
  source_index: Optional[np.ndarray] = None,
922
964
  as_positional: bool = False,
923
965
  validate: bool = False,
966
+ missing: Union[str, int, float] = "raise",
924
967
  ) -> np.ndarray:
925
968
  """Map each vertex index from the current layer to a single index in the specified layer.
926
969
 
@@ -934,6 +977,18 @@ class PointMixin(ABC):
934
977
  Whether to treat source_index and mapped index as positional (i_th element of the array) or as a dataframe index.
935
978
  validate : bool
936
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.
937
992
 
938
993
  Returns
939
994
  -------
@@ -949,6 +1004,7 @@ class PointMixin(ABC):
949
1004
  as_positional=as_positional,
950
1005
  how="one_to_one",
951
1006
  validate=validate,
1007
+ missing=missing,
952
1008
  )
953
1009
  )
954
1010
 
@@ -1120,35 +1176,65 @@ class PointMixin(ABC):
1120
1176
  self,
1121
1177
  mask: np.ndarray,
1122
1178
  as_positional: bool = False,
1179
+ return_cell: Optional[bool] = None,
1123
1180
  self_only: bool = False,
1124
1181
  ) -> Union[Self, "Cell"]:
1125
- """Apply a mask on the current layer. Returns a new object with the masked morphsync.
1126
- If the object is associated with a CellSync, a new CellSync will be created, otherwise
1127
- 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.
1128
1187
 
1129
- Properties
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.
1194
+
1195
+ Parameters
1130
1196
  ----------
1131
1197
  mask: np.ndarray
1132
1198
  The mask to apply, either in boolean, vertex index, or positional index form.
1133
1199
  as_positional: bool
1134
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.
1135
1205
  self_only: bool
1136
- 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.
1137
1210
 
1138
1211
  Returns
1139
1212
  -------
1140
- masked_object Union[Self, "CellSync"]
1141
- 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.
1142
1216
  """
1143
1217
  new_morphsync = self._mask_morphsync(mask=mask, as_positional=as_positional)
1144
1218
  if self._cell is None or self_only:
1145
1219
  return self.__class__._from_existing(
1146
1220
  new_morphsync=new_morphsync, old_obj=self
1147
1221
  )
1148
- else:
1149
- return self._cell.__class__._from_existing(
1150
- 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,
1151
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]
1152
1238
 
1153
1239
  def copy(self) -> Self:
1154
1240
  """Create a deep copy of the current object.
@@ -1203,25 +1289,32 @@ class PointMixin(ABC):
1203
1289
  reset()
1204
1290
 
1205
1291
  @contextlib.contextmanager
1206
- 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]:
1207
1295
  """Context manager to temporarily apply a mask via the current layer.
1208
1296
 
1209
1297
  Parameters
1210
1298
  ----------
1211
1299
  mask: np.ndarray
1212
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.
1213
1306
 
1214
1307
  Yields
1215
1308
  ------
1216
1309
  Self
1217
- A new object of the same class with the mask applied.
1310
+ The masked object, per ``return_cell``.
1218
1311
 
1219
1312
  Example
1220
1313
  -------
1221
- >>> with cell.skeleton.mask_context(mask) as masked_cell:
1222
- >>> 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()
1223
1316
  """
1224
- new_self = self.apply_mask(mask=mask)
1317
+ new_self = self.apply_mask(mask=mask, return_cell=return_cell)
1225
1318
  try:
1226
1319
  yield new_self
1227
1320
  finally:
@@ -1277,10 +1370,14 @@ class PointMixin(ABC):
1277
1370
  all_unmapped_indices = []
1278
1371
 
1279
1372
  for target_layer in target_layers:
1280
- # 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.
1281
1378
  mapping = self._morphsync.get_mapping(
1282
- source=target_layer,
1283
- target=self.layer_name,
1379
+ source=self.layer_name,
1380
+ target=target_layer,
1284
1381
  dropna=False,
1285
1382
  )
1286
1383
 
@@ -1299,9 +1396,83 @@ class PointMixin(ABC):
1299
1396
 
1300
1397
  return unique_unmapped
1301
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
+
1302
1472
  def mask_out_unmapped(
1303
1473
  self,
1304
1474
  target_layers: Optional[Union[str, List[str]]] = None,
1475
+ return_cell: Optional[bool] = None,
1305
1476
  self_only: bool = False,
1306
1477
  ) -> Union[Self, "Cell"]:
1307
1478
  """Create a new object with unmapped vertices removed.
@@ -1355,7 +1526,10 @@ class PointMixin(ABC):
1355
1526
 
1356
1527
  # Apply mask using existing functionality
1357
1528
  return self.apply_mask(
1358
- 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,
1359
1533
  )
1360
1534
 
1361
1535
  def describe(self) -> None:
@@ -1592,6 +1766,60 @@ class GraphLayer(PointMixin, EdgeMixin):
1592
1766
  """
1593
1767
  return np.array(self.csgraph_undirected.sum(axis=0)).flatten() / 2
1594
1768
 
1769
+ def _masked_component_labels(self, mask: Optional[np.ndarray]) -> np.ndarray:
1770
+ """Connected-component label per vertex within the subgraph ``mask`` induces.
1771
+
1772
+ Vertices outside ``mask`` get -1. Edges count only when both ends are
1773
+ inside it, so a mask that cuts through the graph splits it.
1774
+ """
1775
+ if mask is None:
1776
+ keep = np.ones(self.n_vertices, dtype=bool)
1777
+ else:
1778
+ keep = np.asarray(mask)
1779
+ if keep.dtype != bool or keep.shape != (self.n_vertices,):
1780
+ raise ValueError(
1781
+ "mask must be a boolean array with one entry per vertex "
1782
+ f"({self.n_vertices}), got dtype {keep.dtype} and shape {keep.shape}"
1783
+ )
1784
+ labels = np.full(self.n_vertices, -1, dtype=int)
1785
+ inside = np.flatnonzero(keep)
1786
+ if inside.size == 0:
1787
+ return labels
1788
+ subgraph = self.csgraph_binary_undirected[inside][:, inside]
1789
+ _, labels[inside] = sparse.csgraph.connected_components(
1790
+ subgraph, directed=False
1791
+ )
1792
+ return labels
1793
+
1794
+ def largest_connected_component(
1795
+ self, mask: Optional[np.ndarray] = None
1796
+ ) -> np.ndarray:
1797
+ """Boolean mask of the largest connected component, by vertex count.
1798
+
1799
+ Parameters
1800
+ ----------
1801
+ mask : np.ndarray, optional
1802
+ Boolean array with one entry per vertex. When given, components are
1803
+ found within the subgraph it induces: vertices outside it are never
1804
+ selected, and edges count only when both ends are inside it.
1805
+ Default None considers the whole layer.
1806
+
1807
+ Returns
1808
+ -------
1809
+ np.ndarray
1810
+ Boolean array with one entry per vertex, True on the largest
1811
+ component. Ties go to the component holding the lowest-positioned
1812
+ vertex. All False when ``mask`` selects nothing.
1813
+ """
1814
+ labels = self._masked_component_labels(mask)
1815
+ inside = labels >= 0
1816
+ if not inside.any():
1817
+ return inside
1818
+ # connected_components numbers components in order of first vertex, and
1819
+ # argmax takes the first maximum, so ties go to the earliest component.
1820
+ largest = int(np.argmax(np.bincount(labels[inside])))
1821
+ return labels == largest
1822
+
1595
1823
  def proximity_mapping(
1596
1824
  self,
1597
1825
  distance_threshold: float,
@@ -1910,6 +2138,7 @@ class SkeletonLayer(GraphLayer):
1910
2138
  *,
1911
2139
  vertex_index: Optional[Union[str, np.ndarray]] = None,
1912
2140
  edges_as_positional: Optional[bool] = None,
2141
+ root_as_positional: bool = False,
1913
2142
  features: Optional[Union[dict, pd.DataFrame]] = None,
1914
2143
  morphsync: MorphSync = None,
1915
2144
  linkage: Optional[dict] = None,
@@ -1937,11 +2166,13 @@ class SkeletonLayer(GraphLayer):
1937
2166
  self._setup_linkage(linkage)
1938
2167
 
1939
2168
  # Establish the root and then build the base properties
1940
- self._root = self._infer_root(root)
2169
+ self._root = self._infer_root(root, as_positional=root_as_positional)
1941
2170
  self._dag_cache = gf.DAGCache(
1942
2171
  root=self.root_positional
1943
2172
  ) # Cache of properties associated with rooted skeletons
1944
- self._dag_cache.parent_node_array = self._apply_root_to_edges(root)
2173
+ # Use the resolved root, not the raw argument: _infer_root may have
2174
+ # converted it out of positional space or inferred it from the edges.
2175
+ self._dag_cache.parent_node_array = self._apply_root_to_edges(self._root)
1945
2176
 
1946
2177
  self._set_base_properties(
1947
2178
  base_properties={
@@ -2025,6 +2256,36 @@ class SkeletonLayer(GraphLayer):
2025
2256
  return None
2026
2257
  return self.vertex_df.loc[self.root, self.spatial_columns].to_numpy(dtype=float)
2027
2258
 
2259
+ def root_component(self, mask: Optional[np.ndarray] = None) -> np.ndarray:
2260
+ """Boolean mask of the connected component that contains the root.
2261
+
2262
+ Parameters
2263
+ ----------
2264
+ mask : np.ndarray, optional
2265
+ Boolean array with one entry per vertex. When given, the component is
2266
+ found within the subgraph it induces, so vertices reachable from the
2267
+ root only through vertices outside the mask are excluded. Default
2268
+ None considers the whole skeleton.
2269
+
2270
+ Returns
2271
+ -------
2272
+ np.ndarray
2273
+ Boolean array with one entry per vertex, True on the root's
2274
+ component. All False when the root lies outside ``mask``.
2275
+
2276
+ Raises
2277
+ ------
2278
+ ValueError
2279
+ If the skeleton has no root.
2280
+ """
2281
+ root = self.root_positional
2282
+ if root is None:
2283
+ raise ValueError("Skeleton has no root, so it has no root component")
2284
+ labels = self._masked_component_labels(mask)
2285
+ if labels[root] < 0:
2286
+ return np.zeros(self.n_vertices, dtype=bool)
2287
+ return labels == labels[root]
2288
+
2028
2289
  @property
2029
2290
  def parent_node_array(self) -> np.ndarray:
2030
2291
  """Get the parent node array for the skeleton, or -1 for a missing parent."""
@@ -2283,16 +2544,20 @@ class SkeletonLayer(GraphLayer):
2283
2544
  if np.array_equal(self.vertex_index, self.base_vertex_index):
2284
2545
  self._base_properties["base_csgraph"] = self.csgraph
2285
2546
 
2286
- def _infer_root(self, root: Optional[int]) -> int:
2547
+ def _infer_root(self, root: Optional[int], as_positional: bool = False) -> int:
2287
2548
  """Infer the root node from the graph structure or validate provided root.
2288
2549
 
2289
2550
  Parameters
2290
2551
  ----------
2291
2552
  root : Optional[int]
2292
- Proposed root, as a **vertex index** -- the same space as
2553
+ Proposed root. By default a **vertex index** -- the same space as
2293
2554
  ``vertex_index``, not a positional index. Note this differs from
2294
- ``edges``, which are positional when ``vertex_index`` is supplied.
2555
+ ``edges``, which are positional when ``vertex_index`` is supplied;
2556
+ pass ``as_positional=True`` to use that space here instead.
2295
2557
  If None, attempts to infer from graph structure.
2558
+ as_positional : bool
2559
+ Whether ``root`` is a positional index into this layer's vertices.
2560
+ Default False, matching ``as_positional`` everywhere else.
2296
2561
 
2297
2562
  Returns
2298
2563
  -------
@@ -2306,6 +2571,10 @@ class SkeletonLayer(GraphLayer):
2306
2571
  root was specified and multiple potential roots were found.
2307
2572
  """
2308
2573
  if root is not None:
2574
+ if as_positional:
2575
+ # Positional in, vertex index out: `root` is stored and
2576
+ # returned as a vertex index whichever space it arrived in.
2577
+ root = int(self.vertex_index[int(root)])
2309
2578
  root = int(root)
2310
2579
  # Numpy membership rather than building a Python set: a layer can
2311
2580
  # have millions of vertices and this runs on every construction.
@@ -2603,8 +2872,11 @@ class SkeletonLayer(GraphLayer):
2603
2872
  ds_inds = gf.get_subtree_nodes(
2604
2873
  subtree_root=vertex[0], edges=self.edges_positional
2605
2874
  )
2606
- if inclusive:
2607
- ds_inds = np.concatenate(([vertex[0]], ds_inds))
2875
+ # get_subtree_nodes already returns the subtree root, so `inclusive`
2876
+ # had it backwards: False still contained the vertex, and True listed
2877
+ # it twice.
2878
+ if not inclusive:
2879
+ ds_inds = ds_inds[ds_inds != vertex[0]]
2608
2880
  if as_positional:
2609
2881
  return ds_inds
2610
2882
  else:
@@ -2762,10 +3034,14 @@ class SkeletonLayer(GraphLayer):
2762
3034
  List[np.ndarray]
2763
3035
  List of segment arrays including parent nodes in positional indices.
2764
3036
  """
2765
- segs = self.segments_positional
2766
- return [
2767
- np.concatenate((seg, [self.parent_node_array[seg[-1]]])) for seg in segs
2768
- ]
3037
+ # The root's segment has no parent, and -1 is the sentinel for that.
3038
+ # Appending it would put -1 into a list of positional indices, which
3039
+ # then reads as the *last* vertex once mapped through vertex_index.
3040
+ out = []
3041
+ for seg in self.segments_positional:
3042
+ parent = self.parent_node_array[seg[-1]]
3043
+ out.append(np.concatenate((seg, [parent])) if parent != -1 else seg)
3044
+ return out
2769
3045
 
2770
3046
  @property
2771
3047
  def segments_plus(self) -> List[np.ndarray]:
@@ -2776,7 +3052,10 @@ class SkeletonLayer(GraphLayer):
2776
3052
  List[np.ndarray]
2777
3053
  List of segment arrays including parent nodes in dataframe indices.
2778
3054
  """
2779
- return [self.vertices[seg] for seg in self.segments_plus_positional]
3055
+ # ``self.vertices`` is the Nx3 coordinate array, so indexing it here
3056
+ # returned coordinates from a property documented -- and named, next to
3057
+ # ``segments`` -- to return vertex indices.
3058
+ return [self.vertex_index[seg] for seg in self.segments_plus_positional]
2780
3059
 
2781
3060
  @property
2782
3061
  def segment_map(self) -> np.ndarray:
@@ -2813,7 +3092,10 @@ class SkeletonLayer(GraphLayer):
2813
3092
  capped_segs, capped_seg_map = gf.build_capped_segments(
2814
3093
  segments, self.vertices, max_length
2815
3094
  )
2816
- if positional:
3095
+ # ``build_capped_segments`` works in positional space, so it is the
3096
+ # *index* form that needs mapping. This test was inverted, returning
3097
+ # vertex indices for positional=True and positions for positional=False.
3098
+ if not positional:
2817
3099
  capped_segs = [self.vertex_index[seg] for seg in capped_segs]
2818
3100
  return capped_segs, capped_seg_map
2819
3101
 
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
File without changes
File without changes