diff --git a/docs/source/api.md b/docs/source/api.md index d329fa4..169360a 100644 --- a/docs/source/api.md +++ b/docs/source/api.md @@ -58,4 +58,12 @@ The graph databases are importable from `funlib.persistence.graphs`. .. autoclass:: funlib.persistence.graphs.pgsql_graph_database.PgSQLGraphDatabase :members: :show-inheritance: + +.. autoclass:: funlib.persistence.graphs.csr_graph_database.CSRGraphDataBase + :members: + :show-inheritance: + +.. autoexception:: funlib.persistence.graphs.csr_graph_database.UnfinalizedWrites + +.. autoexception:: funlib.persistence.graphs.csr_graph_database.GraphIsReadOnly ``` diff --git a/docs/source/graphs.md b/docs/source/graphs.md index 77b5828..8fe087c 100644 --- a/docs/source/graphs.md +++ b/docs/source/graphs.md @@ -41,3 +41,205 @@ the nodes inside the ROI and the edges whose `u` is inside it, which is how a block sees the edges that leave it; `fetch_on_v=True` adds the edges whose `v` is inside as well. A ROI that is unbounded on every axis, or no ROI, reads the whole graph. + +## A graph in memory-mapped arrays + +`CSRGraphDataBase` keeps a graph as plain `.npy` arrays under a directory, +sorted so that the nodes of a region are a few runs of consecutive rows. It +is read by memory mapping and suits graphs that are written once and then +read block by block. Attributes are numbers or vectors of numbers. + +A whole graph held in arrays is written in one call, and read back as +arrays: + +```python +import numpy as np +from funlib.geometry import Roi +from funlib.persistence.graphs import CSRGraphDataBase + +db = CSRGraphDataBase.from_arrays( + "fragments.csr", + ids, # (N,) node ids + {"position": positions, "size": sizes}, # (N, 3) and (N,) + u, v, # (M,) endpoint ids + {"merge_score": scores}, # (M,) + cell_size=3000.0, +) +nodes, edges = db.read_arrays(Roi((0, 0, 0), (100, 100, 100)), num_steps=1) +``` + +`read_arrays` returns the nodes in the ROI, every node within `num_steps` +edges of them, and the edges among the nodes read. `step_edges` names the +float edge attributes that make an edge a step: an edge is followed when +one of them is set on it. + +By default an edge is returned when both of its ends are among the nodes +read, so the arrays are a graph on their own. That is not the rule of +`read_graph`, which also returns the edges that leave the ROI. +`edge_ends` selects the rule: + +| `edge_ends` | an edge is returned when | same edges as | +|---|---|---| +| `"both"` (default) | both ends are among the nodes read | | +| `"u"` | its smaller-id end is among the nodes read | `read_graph(roi)`, `read_edges(roi)` on every backend | +| `"either"` | at least one end is among the nodes read | `read_graph(roi, fetch_on_v=True)` | + +With `"u"` or `"either"` an edge can name a node whose attributes were not +read. Code that reads one backend as arrays and another through +`read_graph` asks for `edge_ends="u"` to get the same edges from both. + +`read_block` is the read of a computation that writes one value per node of +a block: the nodes of the ROI, marked `own`, with the nodes within a +distance `context` of it and within `num_steps` edges of those. + +```python +nodes, edges = db.read_block(roi, context=500, num_steps=2) +values = compute(nodes, edges)[nodes["own"]] +``` + +`CSRGraphDataBase.is_database(path)` tells such a directory from any other. + +## Values on the nodes of a graph: extra fields + +Values computed on a finished graph, such as an embedding per node, do not +have to go into the graph's directory. The graph is opened with +`extra_fields`, the directory that holds them, and the extra attributes are +written and read through the database like stored ones: + +```python +from funlib.persistence.graphs import CSRGraphDataBase + +g = CSRGraphDataBase("fragments.csr", mode="r+", extra_fields="pred/model_a") +with g.bulk_write_mode(): + for roi in blocks: + nodes, edges = g.read_block(roi, num_steps=2, node_attrs=["position"]) + own = nodes["own"] + e, l = model(nodes, edges) # float32 (N, 64) and int32 (N,) + g.write_node_arrays(nodes["id"][own], embedding=e[own], label=l[own]) + +g = CSRGraphDataBase("fragments.csr", extra_fields="pred/model_a") +nodes, edges = g.read_arrays(roi, node_attrs=["position", "embedding"]) +``` + +The path is enough. No attribute is named and no type is given: `meta.json` +in the directory records what it holds, and opening the graph with it +exposes every attribute there with its recorded type. `g.node_attrs` lists +the extra attributes after the stored ones, and `read_arrays`, `read_block`, +`read_nodes` and `read_graph` return them by name, for the same regions and +steps. `CSRGraphDataBase.stored_extra_fields(path)` tells what a directory +holds without opening a graph. + +`extra_fields` also takes several directories, +`extra_fields=["pred/model_a", "pred/model_b"]`, and exposes the attributes +of all of them. An attribute that two of them hold, or that the graph itself +stores, is refused when the graph is opened. A directory that is empty or +does not exist yet is created by the first write in mode `"r+"`; in mode +`"r"` it is an error. An extra directory is never inside the graph's +directory, nor the other way round: both are refused. + +**A new attribute is created by the first write that names it**, with the +type of the values written: `embedding=e` with `e` a float32 array of shape +`(N, 64)` declares a float32 vector of 64. The declaration is recorded in the +directory's `meta.json` under the directory's lock, so worker processes that +create the same attribute at the same moment agree on it. From then on an +array written to the attribute has that dtype and vector size, or the write +raises `ValueError`; nothing is cast. The writes that take nodes as +dictionaries (`write_nodes`, `bulk_write_nodes`, `write_attrs`) create an +attribute named in `attributes` from the values the nodes carry, when those +are numbers of one kind (bool, int or float, stored as bool, int64 or +float64) and one length; otherwise they raise and ask for a type. When no +node carries a value (an empty block) nothing is written and nothing is +created. A value for an attribute that exists is stored in the recorded type +or refused, never changed: a float for an integer or a bool, an integer for +a bool, and a sequence of another length than the vector raise. A Python +float takes the recorded float width and an integer the recorded integer +width, or becomes a float. + +A write that is refused records nothing: none of the attributes it names is +created. The name of an extra attribute is made of letters, digits, `_`, +`.` and `-`, does not start with `.` or `-`, and has at most 233 +characters, because it is part of the +name of a file. `id`, `step` and `own` are not names of attributes, because +the reads return arrays of those names. Node ids are integers that are not +negative, and a value +has to be in the range of the recorded type. + +`node_attrs` is never needed for an extra attribute. It may name one with a +type, `node_attrs={"score": "float32"}`, to create it up front in mode +`"r+"`, for example float32 where Python numbers would give float64, or to +have the recorded type checked. + +**A new attribute goes into the one directory that is open.** With several +directories open, a write that names an attribute none of them holds raises: +open the graph with the directory it is to go into. Attributes that exist +are written into the directory that holds them. + +**The graph is read-only through such a handle.** Nothing in the graph's +directory is created, changed or locked. Writing edges, writing nodes with +stored attributes, and `drop_edges` raise `GraphIsReadOnly`. The node +writes (`write_node_arrays`, `write_attrs`, `write_nodes`, +`bulk_write_nodes`) take extra attributes only, for nodes that exist, and +need no position, unless a `roi` is given: then a node with a value to write +carries its position (read the graph with it), and one without raises. A +node that carries neither a value nor a position is left out. `read_graph(roi)` +adds such a node for every edge that leaves the region, so +`g.write_attrs(g.read_graph(roi), roi=roi, node_attrs=[...])` writes the +nodes inside the region. + +Writing is the database's: each handle appends to a segment file of its own +in the extra directory, and `finalize()`, or leaving `bulk_write_mode` in +the main process, merges the segments into the arrays. In a blockwise task +each worker opens the graph with the same `extra_fields` and writes inside +`bulk_write_mode(worker=True)`; the main process finalizes at the end. The +finalize rebuilds the arrays of the attributes that were written and reads +the graph's node ids, nothing else of the graph. A later finalize adds to +the values that are there, so a run can be taken up again; a node written +twice keeps its last value. + +The values are stored in the graph's row order, one array per attribute, so +a region read has the graph's locality and there is no lookup by id. This +ties a directory to one graph. It records the graph's node count, the name +of the graph's arrays, and a checksum of its node ids in row order, and +opening it with a graph of another node count, other ids or another row +order raises `ValueError`. Adding edges to the graph, or building it again +from the same nodes, keeps the extra fields valid; adding nodes does not. + +``` +pred/model_a/meta.json version, extends, node_attrs, arrays +pred/model_a/node_embedding-.npy (N, 64), in the graph's row order +pred/model_a/node_label-.npy (N,) +pred/model_a/segments/ writes not yet in the arrays +pred/model_a/finalize.lock +``` + +What to know: + +- A node that was never written reads as NaN, and as 0 for an integer or a + bool, which cannot be told from a written 0. Use a float, or a value + other than 0, where the difference matters. A written NaN counts as not + written. +- A value for an id that is not a node of the graph is found at the + finalize, which raises `ValueError` and changes nothing. The segments + stay; remove the one named in the error to go on. +- Finalize when the writers are done: a record appended to a segment while + it is being merged is lost. Several finalizes at once run one after the + other. A record cut short by a killed writer is ignored with a warning, + and its block has to be written again. +- Which of two processes wrote a node "last" is decided by the names of + their segment files, not by time. Within one process it is the order of + the writes. +- A read that returns an extra attribute raises `UnfinalizedWrites` while + its directory has segments. A read that names other attributes does not, + so a worker reads the graph (`node_attrs=[...]` without the attribute it + is writing) while the run is under way. +- With several directories open, `finalize()` merges every one. A directory + that fails does not keep the others from being merged; one error is raised + as it is, several as an `ExceptionGroup`. A directory with nothing to + merge, or that does not exist yet, is left alone. +- A finalize removes `node_-*.npy` files in the directory that its + `meta.json` does not name, which a finalize that was killed can leave. +- An error raised inside `bulk_write_mode` is the one that reaches the + caller; what was written before it is still merged. +- Finalize holds the node ids and the attributes it rebuilds in memory. +- A handle sees the arrays of the finalize it last loaded; open the graph + again to see what another process finalized since. diff --git a/src/funlib/persistence/__init__.py b/src/funlib/persistence/__init__.py index 591af6d..fc84ff8 100644 --- a/src/funlib/persistence/__init__.py +++ b/src/funlib/persistence/__init__.py @@ -1,4 +1,4 @@ from .arrays import Array, open_ds, prepare_ds, open_ome_ds, prepare_ome_ds # noqa -__version__ = "0.9.1" +__version__ = "0.9.2" __version_info__ = tuple(int(i) for i in __version__.split(".")) diff --git a/src/funlib/persistence/graphs/_files.py b/src/funlib/persistence/graphs/_files.py new file mode 100644 index 0000000..92c89f8 --- /dev/null +++ b/src/funlib/persistence/graphs/_files.py @@ -0,0 +1,40 @@ +"""File system steps shared by the stores that are directories of arrays.""" + +from __future__ import annotations + +import errno +import os +import shutil +import uuid +from pathlib import Path + + +def scratch_beside(path: Path, what: str) -> Path: + """A directory name beside ``path`` that no other writer uses.""" + return path.with_name(f"{path.name}.{what}-{uuid.uuid4().hex}") + + +def replace_directory(new: Path, path: Path) -> None: + """Put the directory ``new`` at ``path``, removing what is there. + + What was at ``path`` is moved aside before ``new`` is moved in, so + ``path`` never holds a mix of the two; for the instant between the two + moves it does not exist. Several processes may replace one path at + once: each of them succeeds in turn and the last one stays. + """ + while True: + try: + os.rename(new, path) # succeeds onto nothing or an empty directory + return + except OSError as error: + if error.errno not in (errno.ENOTEMPTY, errno.EEXIST, errno.ENOTDIR): + raise + old = scratch_beside(path, "old") + try: + os.rename(path, old) + except FileNotFoundError: + continue # another process moved it aside first + if old.is_dir() and not old.is_symlink(): + shutil.rmtree(old, ignore_errors=True) + else: + old.unlink() diff --git a/src/funlib/persistence/graphs/csr_graph_database.py b/src/funlib/persistence/graphs/csr_graph_database.py index c810dcf..2b36f82 100644 --- a/src/funlib/persistence/graphs/csr_graph_database.py +++ b/src/funlib/persistence/graphs/csr_graph_database.py @@ -18,6 +18,12 @@ :meth:`CSRGraphDataBase.finalize` merges the segments into a new set of arrays; leaving :meth:`CSRGraphDataBase.bulk_write_mode` in the main process does that. Reads see the arrays of the last finalize. + +Node attributes that are computed on a finished graph (an embedding, a +label per node) can be kept outside the graph's directory, as *extra +fields*: see ``extra_fields`` of :class:`CSRGraphDataBase`. They are +written and finalized the same way, into a directory of their own, and the +graph's directory is not touched. """ from __future__ import annotations @@ -26,23 +32,35 @@ import json import logging import os +import re import shutil import uuid -from collections.abc import Iterable +import zlib +from collections.abc import Generator, Iterable, Mapping, Sequence from contextlib import contextmanager from pathlib import Path from typing import Any import numpy as np -from funlib.geometry import Roi +from funlib.geometry import Coordinate, Roi from networkx import Graph from ..types import Vec +from ._files import replace_directory, scratch_beside from .graph_database import AttributeType, GraphDataBase logger = logging.getLogger(__name__) FORMAT_VERSION = 1 +EXTRA_FORMAT_VERSION = 1 +RESERVED_NODE_NAMES = ("id", "step", "own") +"""Names the reads give to arrays of their own (the node id, the step that +reached a node, the block's own nodes): not names of extra attributes.""" +_EXTRA_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.\-]{0,232}") +"""The name of an extra attribute: letters, digits, ``_``, ``.`` and ``-``, +not starting with ``.`` or ``-``, at most 233 characters. It is part of the +name of a file, ``node_-<12 characters>.npy``, which a file system +commonly limits to 255 bytes.""" ID_DTYPE = np.dtype(" Generator[None]: + """Hold the lock of a directory of arrays: one finalize, or one change + of its ``meta.json``, at a time. A second process waits.""" + with open(folder / "finalize.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + yield + + def _spec(attr_type: AttributeType) -> dict[str, Any]: """An attribute type as JSON: a numpy dtype name and a vector size.""" size = 0 @@ -172,6 +204,69 @@ def read(path: Path) -> list[np.ndarray]: return records +def _ids_crc32(ids: np.ndarray) -> int: + """The crc32 of node ids in row order, a few million at a time.""" + checksum = 0 + for start in range(0, len(ids), 1 << 22): + chunk = np.asarray(ids[start : start + (1 << 22)], dtype=ID_DTYPE) + checksum = zlib.crc32(chunk.tobytes(), checksum) + return checksum + + +class _ExtraFields: + """A directory of extra node attributes of one graph:: + + meta.json version, extends, node_attrs, arrays + node_-.npy one array per attribute, in the graph's row order + segments/ writes that are not in the arrays yet + finalize.lock + + ``extends`` says which graph the rows are those of: its node count, + the name of the set of arrays it was last built into, and a checksum + of its node ids in row order. ``arrays`` names the file of each + attribute, or nothing for one that was declared and never finalized. + """ + + def __init__(self, path: Path): + self.path = path + self.meta: dict[str, Any] | None = None + self.reload() + + def reload(self) -> None: + file = self.path / "meta.json" + if not file.exists(): + self.meta = None + return + meta = json.loads(file.read_text()) + if not isinstance(meta, dict) or "extends" not in meta: + raise ValueError(f"{self.path} is not a directory of extra node attributes") + if meta["version"] != EXTRA_FORMAT_VERSION: + raise RuntimeError( + f"{self.path} is extra-fields format version {meta['version']}, " + f"this library reads version {EXTRA_FORMAT_VERSION}" + ) + self.meta = meta + + @property + def stored(self) -> dict[str, Any]: + if self.meta is None: + raise RuntimeError(f"{self.path} holds no extra node attributes") + return self.meta + + def write(self) -> None: + tmp = self.path / f"meta.json.{uuid.uuid4().hex}" + tmp.write_text(json.dumps(self.meta, indent=2) + "\n") + os.replace(tmp, self.path / "meta.json") + + def pending(self) -> list[Path]: + folder = self.path / "segments" + return sorted(folder.glob("*.npys")) if folder.exists() else [] + + def record_dtype(self, attrs: Iterable[str]) -> np.dtype: + specs = self.stored["node_attrs"] + return np.dtype([("id", ID_DTYPE)] + [(a, *_field(specs[a])) for a in attrs]) + + class CSRGraphDataBase(GraphDataBase): """A graph in memory-mapped CSR arrays under a directory. @@ -202,6 +297,117 @@ class CSRGraphDataBase(GraphDataBase): Edge length of a grid cell, in the units of the positions: one number or one per dimension. Pick it a few times smaller than the regions that will be read. + + extra_fields: + + One directory, or several, that hold node attributes of this + graph outside the graph's own directory. The graph is opened as + it is (mode ``"r"`` or ``"r+"``); every attribute the + directories hold is read with it, with the type its directory + records, and written through it:: + + g = CSRGraphDataBase(path, mode="r+", extra_fields="pred/modelA") + g.write_node_arrays(ids, embedding=e, label=l) # in bulk_write_mode + g.read_arrays(roi, node_attrs=["position", "embedding"]) + + The path is enough: no attribute is named and no type is given. + ``meta.json`` in each directory says what it holds. Extra + attributes are read like stored ones (same regions, steps, + filters) and listed by :attr:`node_attrs`. An attribute that + two of the directories hold, or that the graph itself stores, + is refused when the graph is opened. A directory that is empty + or does not exist is created by the first write in mode + ``"r+"`` and is an error in mode ``"r"``. A directory inside + the graph's directory, or one that holds it, is refused. + + **A new attribute is created by the first write that names + it**, with the type of the values written: + ``write_node_arrays(ids, embedding=e)`` with ``e`` a float32 + array of shape ``(N, 64)`` declares a float32 vector of 64. The + declaration is recorded in the directory's ``meta.json`` under + its lock, so processes that create one attribute at once agree + on it. From then on an array written to it has that dtype and + vector size, or the write raises; nothing is cast. The writes + that take nodes as dictionaries (``write_nodes``, + ``bulk_write_nodes``, ``write_attrs``) create an attribute that + ``attributes`` names from the values the nodes carry: numbers + of one kind (bool, int or float, stored as bool, int64 or + float64) and one length; anything else raises, and when no node + carries a value nothing is written and nothing is created. A + value for an attribute that exists is stored in the recorded + type or refused, never changed: a float for an integer or a + bool, an integer for a bool, and a sequence of another length + than the vector raise; a Python float takes the recorded float + width, an integer the recorded integer width (or becomes a + float). A call that is refused records nothing: no attribute + of it is created. The name of an extra attribute is made of + letters, digits, ``_``, ``.`` and ``-``, does not start with + ``.`` or ``-`` and has at most 233 characters: it is part of + the name of a file. ``id``, + ``step`` and ``own`` are not names of attributes; the reads use + them. Node ids are integers, not negative. A value has to be in the range of + the recorded type. ``node_attrs`` is + never needed for an extra attribute. It may name one with a + type, to create it up front in mode ``"r+"`` (float32 rather + than the float64 Python numbers give), or to have the type that + is recorded checked. + + **A new attribute goes into the one directory that is open.** + With several directories open, a write that names an attribute + none of them holds raises: open the graph with the directory it + is to go into. + + **The graph is read-only through such a handle.** Writes of + edges, of nodes with stored attributes, and ``drop_edges`` + raise :class:`GraphIsReadOnly`; nothing in the graph's + directory is created, changed or locked. The node writes + (``write_node_arrays``, ``write_attrs``, ``write_nodes``, + ``bulk_write_nodes``) take extra attributes only and need no + position, unless a ``roi`` is given: then a node with a value + to write carries its position, and one that does not raises. A + node that carries neither is left out: ``read_graph(roi)`` adds + such a node for an edge that leaves the region, so a block that + is read with its region can be written back with it. + + Writing works as for the graph: each handle appends to a + segment file of its own in the extra directory, from any + number of processes, and :meth:`finalize` (or leaving + :meth:`bulk_write_mode` in the main process) merges the + segments into the arrays of the attributes that were written. + It reads the graph's node ids and nothing else of the graph. A + later finalize adds to the values that are there; a node + written twice keeps its last value. With several directories + open every one is finalized; a directory that fails does not + keep the others from being merged, and the errors of several + are raised together as an ``ExceptionGroup``. A directory with + nothing to merge, or that does not exist yet, is left alone. A + finalize also removes arrays in the directory that its + ``meta.json`` does not name, which a killed finalize can leave. + + Values are stored in the graph's row order, so they belong to + one graph. The directory records that graph's node count, the + name of its arrays and a checksum of its node ids in row order; + opening it with a graph of another node count, or of other ids + or another row order, raises ``ValueError``. Adding edges to + the graph, or rebuilding it from the same nodes, keeps its + extra fields valid. + + Limits. A node that was never written reads as NaN (0 for an + integer or a bool, which cannot be told from a written 0). A + written NaN counts as not written. Writing an id that is not a + node of the graph is found at finalize, which then raises + ``ValueError`` and changes nothing; the segments stay until + they are removed. Finalize holds the node ids and every + attribute it rebuilds in memory. As for the graph: finalize + when the writers are done (a record appended to a segment while + it is merged is lost), a record cut short by a killed writer is + ignored with a warning, and which of two processes wrote "last" + is decided by the names of their segment files, not by time. A + read that returns an extra attribute raises + :class:`UnfinalizedWrites` while its directory has segments; + reads of other attributes do not. A handle sees the arrays of + the finalize it last loaded: open the graph again to see what + another process finalized since. """ read_modes = ("r", "r+") @@ -217,14 +423,30 @@ def __init__( node_attrs: dict[str, AttributeType] | None = None, edge_attrs: dict[str, AttributeType] | None = None, cell_size: float | Iterable[float] | None = None, + extra_fields: Path | str | Sequence[Path | str] | None = None, ): if directed: raise NotImplementedError("the CSR backend stores undirected graphs") self.path = Path(path) self.mode = mode self.directed = False + if isinstance(extra_fields, Mapping): + raise TypeError( + "extra_fields is a directory or a sequence of directories; the " + "attributes and their types are read from each directory" + ) + if isinstance(extra_fields, str | Path): + extra_fields = [extra_fields] + self.extra_fields = [Path(folder) for folder in extra_fields or ()] + self._extra_dirs: list[_ExtraFields] = [] + self._extra: dict[str, _ExtraFields] = {} + if self.extra_fields and mode not in self.read_modes: + raise ValueError( + f"mode {mode!r} creates the graph; extra_fields belong to a " + "graph that exists and are opened with mode 'r' or 'r+'" + ) self._arrays: dict[str, np.ndarray] | None = None - self._segments: dict[str, _Segment] = {} + self._segments: dict[Any, _Segment] = {} self._bulk_depth = 0 self.meta: dict[str, Any] = {} if mode in self.create_modes: @@ -238,6 +460,9 @@ def __init__( if cell_size is None: raise ValueError("cell_size is required to create a CSR database") sizes = np.broadcast_to(np.asarray(cell_size, dtype=float), (ndims,)) + # every argument is checked before what is at the path is removed + node_specs = {k: _spec(v) for k, v in node_attrs.items()} + edge_specs = {k: _spec(v) for k, v in (edge_attrs or {}).items()} if self.path.exists(): shutil.rmtree(self.path) self.path.mkdir(parents=True) @@ -245,8 +470,8 @@ def __init__( "version": FORMAT_VERSION, "position_attribute": position_attribute, "ndims": ndims, - "node_attrs": {k: _spec(v) for k, v in node_attrs.items()}, - "edge_attrs": {k: _spec(v) for k, v in (edge_attrs or {}).items()}, + "node_attrs": node_specs, + "edge_attrs": edge_specs, "cell_size": sizes.tolist(), "total_roi": None if total_roi is None @@ -272,6 +497,8 @@ def __init__( (edge_attrs, self.meta["edge_attrs"], "edge"), ): for name, attr_type in (given or {}).items(): + if what == "node" and self.extra_fields and name not in stored: + continue # an extra attribute: see _open_extra_fields if name not in stored: raise ValueError( f"{what} attribute {name!r} is not in {self.path}; " @@ -289,6 +516,602 @@ def __init__( self.cell_size = np.asarray(self.meta["cell_size"], dtype=float) stored_roi = self.meta.get("total_roi") self.total_roi = None if stored_roi is None else Roi(*stored_roi) + if self.extra_fields: + self._open_extra_fields(node_attrs or {}) + + # -- extra fields ------------------------------------------------------- + + @staticmethod + def stored_extra_fields(path: Path | str) -> dict[str, AttributeType]: + """The node attributes a directory of extra fields holds, with their + types; empty when ``path`` is not such a directory.""" + try: + extra = _ExtraFields(Path(path)) + except (ValueError, NotADirectoryError): + return {} + if extra.meta is None: + return {} + return CSRGraphDataBase._types(extra.meta["node_attrs"]) + + def _extends(self) -> dict[str, Any]: + """What an extra directory records of this graph.""" + ids = np.load(self.path / self.meta["generation"] / "ids.npy", mmap_mode="r") + return { + "num_nodes": self.meta["num_nodes"], + "generation": self.meta["generation"], + "ids_crc32": _ids_crc32(ids), + } + + def _check_extends(self, extra: _ExtraFields) -> None: + of = extra.stored["extends"] + if of["num_nodes"] != self.meta["num_nodes"]: + raise ValueError( + f"{extra.path} holds attributes of a graph of {of['num_nodes']} " + f"nodes; {self.path} has {self.meta['num_nodes']}" + ) + # the same set of arrays is the same rows; another set (edges were + # added, the graph was built again) is compared by its node ids + if of["generation"] != self.meta["generation"]: + if of["ids_crc32"] != self._extends()["ids_crc32"]: + raise ValueError( + f"{extra.path} holds attributes of a graph with other nodes, " + f"or the same nodes in another order, than {self.path}" + ) + + def _open_extra_fields(self, given: Mapping[str, AttributeType]) -> None: + if self.meta["generation"] is None: + raise ValueError( + f"{self.path} was never finalized; extra fields belong to a " + "graph whose nodes are written" + ) + seen: set[Path] = set() + for folder in self.extra_fields: + key, graph = folder.resolve(), self.path.resolve() + if key == graph or key.is_relative_to(graph): + raise ValueError( + f"{folder}: extra fields are kept outside the graph's " + f"directory {self.path}, which they never change" + ) + if graph.is_relative_to(key): + raise ValueError( + f"{folder} holds the graph's directory {self.path}: extra " + "fields are kept in a directory of their own" + ) + if key in seen: + raise ValueError(f"{folder} is given twice in extra_fields") + seen.add(key) + extra = _ExtraFields(folder) + if extra.meta is None and self.mode == "r": + raise ValueError( + f"{folder} holds no extra node attributes. Open the graph " + "with mode 'r+' to write the first" + ) + self._extra_dirs.append(extra) + self._map_extra_fields() + # node_attrs may name extra attributes: to create them up front, or + # to have the recorded type checked + named = { + name: _spec(attr_type) + for name, attr_type in given.items() + if name not in self.meta["node_attrs"] + } + new = {name: spec for name, spec in named.items() if name not in self._extra} + if new and self.mode == "r": + raise ValueError( + f"node attributes {sorted(new)} are neither in {self.path} nor " + f"in its extra fields, which hold {sorted(self._extra)}" + ) + if new: + self._declare_extra(new) + for name, spec in named.items(): + self._same_spec(name, spec) + + def _map_extra_fields(self) -> None: + """Which directory holds each extra attribute, from what the + directories say now. A name held twice is refused.""" + found: dict[str, _ExtraFields] = {} + for extra in self._extra_dirs: + if extra.meta is None: + continue + self._check_extends(extra) + for name in extra.meta["node_attrs"]: + if name in RESERVED_NODE_NAMES: + raise ValueError( + f"{extra.path} holds a node attribute named {name!r}, " + "which the reads use for an array of their own" + ) + if name in self.meta["node_attrs"]: + raise ValueError( + f"node attribute {name!r} of {extra.path} is also stored " + f"in {self.path} itself" + ) + if name in found: + raise ValueError( + f"node attribute {name!r} is held by {found[name].path} " + f"and by {extra.path}" + ) + found[name] = extra + self._extra = found + + def _same_spec(self, name: str, spec: dict[str, Any]) -> None: + extra = self._extra[name] + recorded = extra.stored["node_attrs"][name] + if spec != recorded: + raise ValueError( + f"node attribute {name!r} is {self._types({name: recorded})[name]} " + f"in {extra.path}, not {self._types({name: spec})[name]}" + ) + + def _check_new_extra(self, names: Iterable[str]) -> None: + """Whether attributes of these names may be created by this handle.""" + names = sorted(names, key=str) + if not names: + return + if any(not isinstance(n, str) for n in names): + raise ValueError(f"{names} are not all names: an attribute name is a str") + if self.mode == "r": + raise RuntimeError("Trying to write to read-only DB") + reserved = [n for n in names if n in RESERVED_NODE_NAMES] + if reserved: + raise ValueError( + f"{reserved} are not names of node attributes: the reads use " + f"{list(RESERVED_NODE_NAMES)} for arrays of their own" + ) + unfit = [n for n in names if not _EXTRA_NAME.fullmatch(n)] + if unfit: + raise ValueError( + f"{unfit} are not names of extra node attributes: a name is " + "made of letters, digits, '_', '.' and '-', does not start " + "with '.' or '-' and has at most 233 characters (it is part of " + "the name of a file)" + ) + if len(self._extra_dirs) != 1: + raise ValueError( + f"{names} are new node attributes and " + f"{len(self._extra_dirs)} extra directories are open: open the " + "graph with the one directory they are to go into" + ) + + def _declare_extra(self, specs: Mapping[str, dict[str, Any]]) -> None: + """Record new extra attributes in the one directory that is open. + Another process may declare the same ones at the same time: the + first to hold the lock writes them, the others find them. Either + all of ``specs`` are recorded or, when one disagrees with what is + recorded, none.""" + if not specs: + return + self._check_new_extra(specs) + (extra,) = self._extra_dirs + extra.path.mkdir(parents=True, exist_ok=True) + with _locked(extra.path): + extra.reload() + if extra.meta is None: + extra.meta = { + "version": EXTRA_FORMAT_VERSION, + "extends": self._extends(), + "node_attrs": {}, + "arrays": {}, + } + held = extra.meta["node_attrs"] + for name, spec in specs.items(): + if name in held and held[name] != spec: + extra.reload() + self._map_extra_fields() + self._same_spec(name, spec) + new = {name: spec for name, spec in specs.items() if name not in held} + if new: + held.update(new) + extra.write() + self._map_extra_fields() + self._arrays = None + + def _extra_folders(self) -> list[_ExtraFields]: + return self._extra_dirs + + def _node_specs(self) -> dict[str, dict[str, Any]]: + """Every node attribute this handle reads: stored, then extra.""" + specs = dict(self.meta["node_attrs"]) + for name, extra in self._extra.items(): + specs[name] = extra.stored["node_attrs"][name] + return specs + + def _refuse(self, what: str) -> None: + if self._extra_dirs: + raise GraphIsReadOnly( + f"{what}: {self.path} is read-only through a handle opened with " + "extra_fields; only extra node attributes are written, into " + f"{[str(e.path) for e in self._extra_dirs]}. Open the graph " + "without extra_fields to change it" + ) + + def _split_extra( + self, attrs: Iterable[str] + ) -> list[tuple[_ExtraFields, list[str]]]: + """Extra attribute names by the directory that holds them.""" + attrs = list(attrs) + return [ + (extra, [a for a in attrs if self._extra[a] is extra]) + for extra in self._extra_dirs + if any(self._extra[a] is extra for a in attrs) + ] + + def _new_extra_names(self, attrs: Iterable[str]) -> list[str]: + """Refuse stored attributes and give the names that no directory + holds yet. Nothing is recorded.""" + attrs = list(attrs) + stored = [a for a in attrs if a in self.meta["node_attrs"]] + if stored: + self._refuse(f"cannot write the node attributes {stored}") + if any(a not in self._extra for a in attrs): + for extra in self._extra_dirs: + extra.reload() # another process may have created them + self._map_extra_fields() + # the arrays this handle loaded do not hold what was found + self._arrays = None + new = [a for a in attrs if a not in self._extra] + self._check_new_extra(new) + return new + + @staticmethod + def _spec_of_values(name: str, values: np.ndarray) -> dict[str, Any]: + """The type an array of values, one entry per node, declares.""" + if values.dtype.kind not in "fiub": + raise NotImplementedError( + f"node attribute {name!r}: attributes of type {values.dtype} are " + "not supported by the CSR backend" + ) + if values.ndim not in (1, 2) or (values.ndim == 2 and values.shape[1] < 1): + raise ValueError( + f"node attribute {name!r} has shape {values.shape}; expected " + "(N,) for a scalar or (N, k) for a vector" + ) + size = values.shape[1] if values.ndim == 2 else 0 + return {"dtype": values.dtype.newbyteorder("<").str, "size": size} + + def _write_extra_arrays(self, ids: np.ndarray, attrs: Mapping[str, Any]) -> None: + ids = np.asarray(ids) + if ids.ndim != 1 or (len(ids) and ids.dtype.kind not in "iu"): + raise ValueError( + f"ids are {ids.dtype} of shape {ids.shape}; node ids are " + "integers, one per node" + ) + if ids.dtype.kind == "i" and len(ids) and int(ids.min()) < 0: + raise ValueError( + f"{int(ids.min())} is not a node id: an id is not negative" + ) + arrays = {name: np.asarray(values) for name, values in attrs.items()} + # every check of the call comes before anything is recorded: a write + # that is refused declares no attribute + new = self._new_extra_names(arrays) + for name, values in arrays.items(): + if values.ndim == 0 or len(values) != len(ids): + raise ValueError( + f"node attribute {name!r} has shape {values.shape}; " + f"expected one entry for each of the {len(ids)} ids" + ) + given = { + name: self._spec_of_values(name, values) for name, values in arrays.items() + } + for name, spec in given.items(): + if name not in new: + self._same_spec(name, spec) + self._declare_extra({name: given[name] for name in new}) + for extra, names in self._split_extra(arrays): + records = np.empty(len(ids), dtype=extra.record_dtype(names)) + records["id"] = ids + for name in names: + records[name] = arrays[name] + self._segment("nodes", extra.path).append(records) + + @staticmethod + def _fits(name: str, value: Any, spec: dict[str, Any]) -> None: + """Refuse a value of a node given as a dictionary that the recorded + type would have to change: a float for an integer or a bool, an + integer for a bool, anything that is not a number, and a sequence + of another length than the vector. A Python number has no width, so + a float is stored in the recorded float type and an integer in the + recorded integer type, when it is in the range of that type.""" + given = np.asarray(value) + dtype = np.dtype(spec["dtype"]) + allowed = {"f": "fiub", "i": "iub", "u": "iub", "b": "b"}[dtype.kind] + shape = (spec["size"],) if spec["size"] else () + fits = given.dtype.kind in allowed and given.shape == shape + if fits and dtype.kind in "iu": + # exact Python integers: a value past int64 has dtype object + # and was refused above + bounds = np.iinfo(dtype.name) + fits = all(bounds.min <= int(x) <= bounds.max for x in given.flat) + elif fits and dtype.kind == "f": + with np.errstate(over="ignore"): + stored = given.astype(dtype) + fits = bool((np.isfinite(stored) | ~np.isfinite(given)).all()) + if not fits: + wanted = f"a vector of {spec['size']}" if spec["size"] else "one value" + raise ValueError( + f"node attribute {name!r} is {dtype.name}, {wanted}; " + f"{value!r} is not stored as that without changing it" + ) + + def _write_extra_rows(self, nodes, roi: Roi | None, attributes) -> None: + # left out, the extra attributes that exist are written; a new one + # is named + names = list(self._extra) if attributes is None else list(attributes) + kept = [] + for node_id, data in nodes.items(): + if ( + isinstance(node_id, bool) + or not isinstance(node_id, int | np.integer) + or node_id < 0 + ): + raise ValueError( + f"{node_id!r} is not a node id: an id is an integer, not negative" + ) + if roi is not None: + position = self._position(data) + if position is None: + # a node that read_graph(roi) added for an edge leaving + # the roi carries nothing; one with a value to write and + # no position cannot be placed and is not left out + if all(data.get(a) is None for a in names): + continue + raise ValueError( + f"node {node_id} carries values and no " + f"{self.position_attribute!r}: with a roi, the nodes " + "carry their position (read them with it, or write " + "without a roi)" + ) + if not roi.contains(tuple(position)): + continue + kept.append((node_id, data)) + + # every check of the call comes before anything is recorded + new = self._new_extra_names(names) + specs: dict[str, dict[str, Any]] = {} + for name in new: + values = [np.asarray(d[name]) for _, d in kept if d.get(name) is not None] + if not values: + # no node carries it (an empty block): nothing to write, and + # nothing to tell a type from + continue + kinds = {v.dtype.kind for v in values} + shapes = {v.shape for v in values} + if ( + len(kinds) != 1 + or len(shapes) != 1 + or not kinds <= set("fiub") + or len(next(iter(shapes))) > 1 + ): + raise ValueError( + f"node attribute {name!r} is new and its type cannot be " + f"told from the values of the nodes ({len(values)} " + f"values, kinds {sorted(kinds)}, shapes {sorted(shapes)}): " + "give its type in node_attrs when the graph is opened" + ) + specs[name] = self._spec_of_values(name, np.stack(values)) + names = [a for a in names if a in self._extra or a in specs] + for name in names: + spec = specs.get(name) or self._extra[name].stored["node_attrs"][name] + for _, data in kept: + if data.get(name) is not None: + self._fits(name, data[name], spec) + self._declare_extra(specs) + for extra, own in self._split_extra(names): + groups: dict[tuple[str, ...], list[tuple]] = {} + for node_id, data in kept: + present = tuple(a for a in own if data.get(a) is not None) + if not present: + continue + values = [ + tuple(data[a]) if np.ndim(data[a]) else data[a] for a in present + ] + groups.setdefault(present, []).append((node_id, *values)) + for present, rows in groups.items(): + self._segment("nodes", extra.path).append( + np.array(rows, dtype=extra.record_dtype(present)) + ) + + def _finalize_extra(self, extra: _ExtraFields) -> None: + paths = extra.pending() + if not paths: + return + extra.reload() + self._reload_meta() + self._check_extends(extra) + # the node ids are all that is read of the graph + ids = np.load(self.path / self.meta["generation"] / "ids.npy") + n = len(ids) + by_id = np.argsort(ids, kind="stable") + sorted_ids = ids[by_id] + specs = extra.stored["node_attrs"] + files = extra.stored["arrays"] + values: dict[str, np.ndarray] = {} + for path in paths: + for batch in _Segment.read(path): + at = np.searchsorted(sorted_ids, batch["id"]) + at[at == n] = 0 + known = ( + sorted_ids[at] == batch["id"] + if n + else np.zeros(len(batch), dtype=bool) + ) + if not known.all(): + some = np.unique(batch["id"][~known])[:5].tolist() + raise ValueError( + f"{path} holds values for {int((~known).sum())} ids that " + f"are not nodes of {self.path} (for example {some}); " + f"nothing was finalized in {extra.path}" + ) + rows = by_id[at] + for name in (batch.dtype.names or ())[1:]: + if name not in specs: + raise ValueError( + f"{path} holds {name!r}, unknown to {extra.path}" + ) + if name not in values: + values[name] = self._extra_array(extra, name, n, copy=True) + written = self._present(batch[name]) + values[name][rows[written]] = batch[name][written] + for name, array in values.items(): + file = f"node_{name}-{uuid.uuid4().hex[:12]}.npy" + np.save(extra.path / file, array) + files[name] = file + extra.stored["extends"] = { + "num_nodes": n, + "generation": self.meta["generation"], + "ids_crc32": _ids_crc32(ids), + } + extra.write() + # the arrays that were replaced, and any that a finalize which was + # killed before it recorded them left behind + named = set(files.values()) + for file in extra.path.glob("node_*-*.npy"): + if file.name not in named: + file.unlink(missing_ok=True) + for path in paths: + path.unlink(missing_ok=True) + + @staticmethod + def _extra_array(extra: _ExtraFields, name: str, n: int, copy: bool = False): + """One extra attribute of every node, in row order. One that was + never finalized is all missing values.""" + file = extra.stored["arrays"].get(name) + if file is not None: + return np.load(extra.path / file, mmap_mode=None if copy else "r") + dtype, *shape = _field(extra.stored["node_attrs"][name]) + full = (n, *(shape[0] if shape else ())) + if copy: + return np.full(full, _missing(dtype), dtype=dtype) + return np.broadcast_to(np.asarray(_missing(dtype), dtype=dtype), full) + + @staticmethod + def is_database(path: Path | str) -> bool: + """Whether ``path`` is the directory of a CSR graph database.""" + meta = Path(path) / "meta.json" + if not meta.is_file(): + return False + try: + stored = json.loads(meta.read_text()) + except ValueError: + return False + return isinstance(stored, dict) and "generation" in stored + + @classmethod + def from_arrays( + cls, + path: Path | str, + ids: np.ndarray, + node_attrs: Mapping[str, np.ndarray], + u: np.ndarray | None = None, + v: np.ndarray | None = None, + edge_attrs: Mapping[str, np.ndarray] | None = None, + *, + cell_size: float | Iterable[float], + position_attribute: str = "position", + node_types: Mapping[str, AttributeType] | None = None, + edge_types: Mapping[str, AttributeType] | None = None, + total_roi: Roi | None = None, + ) -> CSRGraphDataBase: + """Create a database at ``path`` from a whole graph held in arrays, + replacing what is there, and return it open for reading and writing. + + ``ids`` are the node ids, ``node_attrs`` one array per node attribute + (the position among them), ``u`` and ``v`` the endpoint ids of the + edges and ``edge_attrs`` one array per edge attribute. Every array + has one entry per node, or per edge: an array of another length is + refused, a single value is not spread over the graph. + + An attribute is stored in the dtype of its array, a 2-D array as a + vector, unless ``node_types`` or ``edge_types`` names another type + for it; the array is cast to that type. + + The database is built in a directory beside ``path`` and moved to + ``path`` when it is complete. A call that fails, for whatever + reason, leaves what was at ``path`` as it was. + """ + path = Path(path) + ids = np.asarray(ids) + if ids.ndim != 1: + raise ValueError(f"ids has shape {ids.shape}; expected one id per node") + if (u is None) != (v is None): + raise ValueError("edges need both u and v") + if u is None and edge_attrs: + raise ValueError("edge attributes were given without edges") + num_edges = 0 + if u is not None and v is not None: + u, v = np.asarray(u), np.asarray(v) + if u.ndim != 1 or u.shape != v.shape: + raise ValueError( + f"u and v have shapes {u.shape} and {v.shape}; expected one " + "entry per edge in each" + ) + num_edges = len(u) + + def columns(what, given, count, named) -> tuple[dict, dict]: + arrays = {name: np.asarray(a) for name, a in (given or {}).items()} + unknown = sorted(set(named or {}) - set(arrays)) + if unknown: + raise ValueError(f"types were given for {unknown}, which have no array") + types: dict[str, AttributeType] = {} + for name, array in arrays.items(): + if array.ndim not in (1, 2) or len(array) != count: + raise ValueError( + f"{what} attribute {name!r} has shape {array.shape}; " + f"expected one entry for each of the {count} {what}s" + ) + if named and name in named: + types[name] = named[name] + elif array.dtype.kind not in "fiub": + raise NotImplementedError( + f"{what} attribute {name!r}: attributes of type " + f"{array.dtype} are not supported by the CSR backend" + ) + elif array.ndim == 1: + types[name] = array.dtype.name + else: + types[name] = Vec(array.dtype.name, array.shape[1]) + size = _spec(types[name])["size"] + if (array.shape[1] if array.ndim == 2 else 0) != size: + raise ValueError( + f"{what} attribute {name!r} has shape {array.shape}, which " + f"does not fit its type {types[name]}" + ) + return arrays, types + + node_arrays, node_kinds = columns("node", node_attrs, len(ids), node_types) + edge_arrays, edge_kinds = columns("edge", edge_attrs, num_edges, edge_types) + + scratch = scratch_beside(path, "writing") + try: + db = cls( + scratch, + position_attribute=position_attribute, + mode="w", + total_roi=total_roi, + node_attrs=node_kinds, + edge_attrs=edge_kinds, + cell_size=cell_size, + ) + with db.bulk_write_mode(): + db.write_node_arrays(ids, **node_arrays) + if u is not None and v is not None: + db.write_edge_arrays(u, v, **edge_arrays) + if db.meta["generation"] is None: + # no node: nothing was appended, so nothing was merged. The + # arrays of an empty graph are built all the same, so that + # it is a finalized graph like any other + empty = db._empty() + db._build( + empty["ids"], + {k: empty[f"node_{k}"] for k in db.meta["node_attrs"]}, + None, + sort_nodes=True, + ) + db.close() + except BaseException: + shutil.rmtree(scratch, ignore_errors=True) + raise + replace_directory(scratch, path) + return cls(path, mode="r+") # -- metadata ----------------------------------------------------------- @@ -300,7 +1123,8 @@ def _write_meta(self) -> None: def _reload_meta(self) -> None: self.meta = json.loads((self.path / "meta.json").read_text()) - def _types(self, specs: dict[str, dict]) -> dict[str, AttributeType]: + @staticmethod + def _types(specs: dict[str, dict]) -> dict[str, AttributeType]: out: dict[str, AttributeType] = {} for name, spec in specs.items(): dtype = np.dtype(spec["dtype"]).name @@ -309,7 +1133,9 @@ def _types(self, specs: dict[str, dict]) -> dict[str, AttributeType]: @property def node_attrs(self) -> dict[str, AttributeType]: - return self._types(self.meta["node_attrs"]) + """The node attributes and their types: those stored in the graph, + then the extra fields this handle was opened with.""" + return self._types(self._node_specs()) @property def edge_attrs(self) -> dict[str, AttributeType]: @@ -350,10 +1176,16 @@ def _open_arrays(self) -> dict[str, np.ndarray] | None: if self.meta["generation"] is None: return None folder = self.path / self.meta["generation"] - self._arrays = { + arrays = { name: np.load(folder / f"{name}.npy", mmap_mode="r") for name in self._array_names() } + for extra in self._extra_dirs: + extra.reload() + self._map_extra_fields() + for name, extra in self._extra.items(): + arrays[f"node_{name}"] = self._extra_array(extra, name, len(arrays["ids"])) + self._arrays = arrays return self._arrays def _readable(self) -> dict[str, np.ndarray] | None: @@ -366,13 +1198,18 @@ def _readable(self) -> dict[str, np.ndarray] | None: # -- writing ------------------------------------------------------------ - def _segment(self, kind: str) -> _Segment: + def _segment(self, kind: str, folder: Path | None = None) -> _Segment: + """This handle's segment of ``kind`` in the graph's directory, or in + ``folder``, a directory of extra fields.""" if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") - if kind not in self._segments: + if folder is None: + self._refuse(f"cannot write {kind}") + key = (kind, folder) + if key not in self._segments: name = f"{kind}-{os.getpid()}-{uuid.uuid4().hex}.npys" - self._segments[kind] = _Segment(self.path / "segments" / name) - return self._segments[kind] + self._segments[key] = _Segment((folder or self.path) / "segments" / name) + return self._segments[key] def _record_dtype(self, kind: str, attrs: list[str]) -> np.dtype: specs = self.meta[f"{kind}_attrs"] @@ -386,7 +1223,12 @@ def _record_dtype(self, kind: str, attrs: list[str]) -> np.dtype: def write_node_arrays(self, ids: np.ndarray, **attrs: np.ndarray) -> None: """Append nodes given as arrays: ``ids`` and one array per attribute - (the position among them).""" + (the position among them). Through a handle with ``extra_fields``: + values of extra attributes for nodes of the graph, no position.""" + if self._extra_dirs: + self._write_extra_arrays(ids, attrs) + self._after_write() + return if self.position_attribute not in attrs: raise ValueError(f"nodes need their {self.position_attribute!r}") records = np.empty(len(ids), dtype=self._record_dtype("node", list(attrs))) @@ -401,6 +1243,7 @@ def write_edge_arrays( ) -> None: """Append edges given as arrays: endpoint ids and one array per attribute. The order of an edge's endpoints does not matter.""" + self._refuse("cannot write edges") records = np.empty(len(u), dtype=self._record_dtype("edge", list(attrs))) u, v = np.asarray(u, dtype=ID_DTYPE), np.asarray(v, dtype=ID_DTYPE) records["u"], records["v"] = np.minimum(u, v), np.maximum(u, v) @@ -436,6 +1279,10 @@ def _append_rows( ) def bulk_write_nodes(self, nodes, roi: Roi | None = None, attributes=None) -> None: + if self._extra_dirs: + self._write_extra_rows(nodes, roi, attributes) + self._after_write() + return attrs = ( list(attributes) if attributes is not None @@ -457,6 +1304,7 @@ def bulk_write_nodes(self, nodes, roi: Roi | None = None, attributes=None) -> No def bulk_write_edges( self, nodes, edges, roi: Roi | None = None, attributes=None ) -> None: + self._refuse("cannot write edges") attrs = ( list(attributes) if attributes is not None @@ -482,6 +1330,8 @@ def bulk_write_graph( node_attrs: list[str] | None = None, edge_attrs: list[str] | None = None, ) -> None: + if write_edges: + self._refuse("cannot write edges (pass write_edges=False)") with self.bulk_write_mode(worker=self._bulk_depth > 0): if write_nodes: self.bulk_write_nodes(graph.nodes, roi=roi, attributes=node_attrs) @@ -545,6 +1395,8 @@ def write_attrs( ) -> None: """Write attribute values of nodes and edges that exist. Values are merged at finalize: an attribute keeps its last written value.""" + if edge_attrs: + self._refuse("cannot write edge attributes") with self.bulk_write_mode(worker=self._bulk_depth > 0): if node_attrs: self.bulk_write_nodes(graph.nodes, roi=roi, attributes=node_attrs) @@ -561,7 +1413,22 @@ def bulk_write_mode(self, worker=False, node_writes=True, edge_writes=True): self._bulk_depth += 1 try: yield - finally: + except BaseException: + # what was written is merged; the error of the block is the one + # that is raised, whatever the finalize has to say + self._bulk_depth -= 1 + for segment in self._segments.values(): + segment.close() + if not worker and self._bulk_depth == 0: + try: + self.finalize() + except Exception: + logger.exception( + "finalize of %s failed after an error in bulk_write_mode", + self.path, + ) + raise + else: self._bulk_depth -= 1 for segment in self._segments.values(): segment.close() @@ -572,6 +1439,7 @@ def drop_edges(self) -> None: """Remove every edge, keeping the nodes.""" if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") + self._refuse("cannot drop edges") for path in self._pending(): if path.name.startswith("edges-"): path.unlink() @@ -635,7 +1503,7 @@ def _present(values: np.ndarray) -> np.ndarray: if values.dtype.kind != "f": return np.ones(len(values), dtype=bool) missing = np.isnan(values) - return ~(missing.all(axis=1) if values.ndim > 1 else missing) + return np.asarray(~(missing.all(axis=1) if values.ndim > 1 else missing)) def _edge_list(self, arrays: dict[str, np.ndarray]): """Every edge of the arrays once, as ids, from its smaller end.""" @@ -654,7 +1522,11 @@ def finalize(self) -> None: A node or edge written more than once keeps, per attribute, its last written value. An edge with an endpoint that is not a node is - dropped. Holds the whole graph in memory.""" + dropped. Holds the whole graph in memory. + + Through a handle with ``extra_fields`` it merges the segments of + the extra directories instead, into the arrays of the attributes + that were written, and leaves the graph alone.""" if self.mode == "r": raise RuntimeError("Trying to write to read-only DB") for segment in self._segments.values(): @@ -662,8 +1534,27 @@ def finalize(self) -> None: self._segments = {} # one finalize at a time: a second process waits, then finds the # segments the first one merged gone - with open(self.path / "finalize.lock", "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + if self._extra_dirs: + # every directory is finalized; one that fails does not keep + # the others from being merged + errors: list[Exception] = [] + for extra in self._extra_dirs: + if not extra.pending(): + continue # nothing to merge; the directory may not exist + try: + with _locked(extra.path): + self._finalize_extra(extra) + except Exception as error: + errors.append(error) + self._arrays = None + if len(errors) == 1: + raise errors[0] + if errors: + raise ExceptionGroup( + f"finalize failed in {len(errors)} extra directories", errors + ) + return + with _locked(self.path): self._finalize() def _finalize(self) -> None: @@ -702,7 +1593,9 @@ def _finalize(self) -> None: path.unlink(missing_ok=True) def _build(self, ids, nodes, edges, sort_nodes: bool) -> None: - position = nodes[self.position_attribute].reshape(len(ids), -1).astype(float) + position = ( + nodes[self.position_attribute].reshape(len(ids), self.ndims).astype(float) + ) if sort_nodes or self.meta.get("origin") is None: lowest = position.min(axis=0) if len(ids) else np.zeros(self.ndims) origin = np.floor(lowest / self.cell_size) * self.cell_size @@ -847,9 +1740,19 @@ def _rows_in(self, arrays: dict[str, np.ndarray], roi: Roi | None) -> np.ndarray def _node_columns(self, arrays, rows, attrs: list[str]) -> dict[str, np.ndarray]: out = {"id": np.asarray(arrays["ids"][rows])} + specs = self._node_specs() for name in attrs: - if name not in self.meta["node_attrs"]: + if name not in specs: raise ValueError(f"unknown node attribute {name!r}") + for extra in { + id(self._extra[a]): self._extra[a] for a in attrs if a in self._extra + }.values(): + if extra.pending(): + raise UnfinalizedWrites( + f"{extra.path} has writes that are not in its arrays yet; " + "call finalize(), or read without its attributes" + ) + for name in attrs: out[name] = np.asarray(arrays[f"node_{name}"][rows]) return out @@ -859,20 +1762,63 @@ def read_arrays( num_steps: int = 0, node_attrs: list[str] | None = None, edge_attrs: list[str] | None = None, + step_edges: Sequence[str] | None = None, + edge_ends: str = "both", ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: """The nodes in ``roi``, every node within ``num_steps`` edges of them, and the edges among those nodes, as arrays. + ``edge_ends`` says which ends of an edge have to be among the nodes + read for the edge to be returned: + + ``"both"`` (the default) + The edges among the nodes read. Every ``u`` and ``v`` is an + ``id`` in ``nodes``, so the result is a graph on its own. An + edge that leaves the nodes read is not returned. + ``"u"`` + The edges whose smaller-id end is among the nodes read: the + rule of :meth:`read_edges` and :meth:`read_graph`, here and in + the SQL backends. With ``num_steps=0`` the edges are those of + ``read_edges(roi)``. A block sees the edges that leave it, and + blocks that tile a graph see every edge once. + ``"either"`` + The edges with at least one end among the nodes read: the + rule of ``read_edges(roi, fetch_on_v=True)``. + + With ``"u"`` and ``"either"`` an edge can name a node that is not in + ``nodes``; its attributes were not read. + + ``step_edges`` names the edge attributes that make an edge a step: + an edge is followed when any of them is set on it (not NaN). They + are float attributes: an integer or bool attribute has no unset + value and is refused. ``None`` follows every edge; an empty + sequence names no attribute, so no edge is followed. Which edges + are returned is the matter of ``edge_ends`` alone, not of which + were followed. + Returns ``(nodes, edges)``. ``nodes`` has ``id``, ``step`` (0 for a node in the region, else the step that first reached it) and the requested attributes; ``edges`` has ``u``, ``v`` (ids, ``u < v``, each edge once) and the requested attributes. All attributes are returned when none are named.""" + if edge_ends not in ("both", "u", "either"): + raise ValueError( + f"edge_ends is {edge_ends!r}; it is one of 'both', 'u', 'either'" + ) arrays = self._readable() - node_attrs = list(self.meta["node_attrs"]) if node_attrs is None else node_attrs + node_attrs = list(self._node_specs()) if node_attrs is None else node_attrs edge_attrs = list(self.meta["edge_attrs"]) if edge_attrs is None else edge_attrs if arrays is None: arrays = self._empty() + for name in step_edges or (): + if name not in self.meta["edge_attrs"]: + raise ValueError(f"unknown edge attribute {name!r}") + dtype = np.dtype(self.meta["edge_attrs"][name]["dtype"]) + if dtype.kind != "f": + raise ValueError( + f"step_edges: edge attribute {name!r} is {dtype.name}; only " + "a float attribute can be unset on an edge" + ) indptr, nbr = arrays["indptr"], arrays["nbr"] selected = self._rows_in(arrays, roi) step = np.zeros(len(selected), dtype=np.int16) @@ -881,6 +1827,11 @@ def read_arrays( if len(frontier) == 0: break at, _ = _gather(indptr, frontier) + if step_edges is not None: + followed = np.zeros(len(at), dtype=bool) + for name in step_edges: + followed |= self._present(np.asarray(arrays[f"edge_{name}"][at])) + at = at[followed] reached = np.unique(np.asarray(nbr[at])) frontier = reached[~np.isin(reached, selected, assume_unique=True)] if len(frontier) == 0: @@ -893,6 +1844,11 @@ def read_arrays( ] nodes = self._node_columns(arrays, selected, node_attrs) nodes["step"] = step + if edge_ends != "both": + # the rule of read_edges, applied to the nodes read + return nodes, self._edge_columns( + arrays, selected, edge_ends == "either", edge_attrs + ) at, owner = _gather(indptr, selected) other = np.asarray(nbr[at]) where = np.searchsorted(selected, other) @@ -906,6 +1862,67 @@ def read_arrays( edges[name] = np.asarray(arrays[f"edge_{name}"][at[once]]) return nodes, edges + def read_block( + self, + roi: Roi, + context: Sequence[float] | float | None = None, + num_steps: int = 0, + node_attrs: list[str] | None = None, + edge_attrs: list[str] | None = None, + step_edges: Sequence[str] | None = None, + edge_ends: str = "both", + ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: + """A block with its surroundings, as arrays: what a computation that + writes one value per node of ``roi`` reads. + + The block's own nodes are those inside ``roi``. The surroundings + are every node within ``context`` of the box (one distance or one + per dimension, rounded up to whole units), and every node within + ``num_steps`` edges of any of those, wherever it lies. + + Returns ``(nodes, edges)`` as :meth:`read_arrays` does, with one more + array in ``nodes``: ``own``, true for the nodes inside ``roi``. + ``step`` is 0 for the block's own nodes and for those the context + reached; the steps are counted from there. ``edge_ends`` is that of + :meth:`read_arrays`: it applies to all the nodes read, the + surroundings included. + """ + if num_steps < 0: + raise ValueError("num_steps must be >= 0") + wanted = list(self._node_specs()) if node_attrs is None else node_attrs + if context is None: + nodes, edges = self.read_arrays( + roi, num_steps, wanted, edge_attrs, step_edges, edge_ends + ) + nodes["own"] = nodes["step"] == 0 + return nodes, edges + distance = np.broadcast_to(np.asarray(context, dtype=float), (self.ndims,)) + if not (distance >= 0).all(): # before rounding: ceil(-0.5) is -0 + raise ValueError("context must be >= 0") + grow = np.ceil(distance) + amount = Coordinate(int(g) for g in grow) + position = self.position_attribute + nodes, edges = self.read_arrays( + roi.grow(amount, amount), + num_steps, + list(dict.fromkeys([*wanted, position])), + edge_attrs, + step_edges, + edge_ends, + ) + # the number of dimensions is given: no node leaves nothing to infer + at = np.asarray(nodes[position], dtype=float).reshape( + len(nodes["id"]), self.ndims + ) + own = nodes["step"] == 0 + bounds = self._bounds(roi) + if bounds is not None: + own &= ((at >= bounds[0]) & (at < bounds[1])).all(axis=1) + nodes["own"] = own + if position not in wanted: + del nodes[position] + return nodes, edges + def _empty(self) -> dict[str, np.ndarray]: out = { "ids": np.zeros(0, dtype=ID_DTYPE), @@ -957,7 +1974,7 @@ def read_nodes( ) -> list[dict[str, Any]]: """The nodes in ``roi`` as dictionaries, as the SQL backends do.""" arrays = self._readable() or self._empty() - read_attrs = list(self.meta["node_attrs"]) if read_attrs is None else read_attrs + read_attrs = list(self._node_specs()) if read_attrs is None else read_attrs needed = list(dict.fromkeys(read_attrs + list(attr_filter or {}))) columns = self._node_columns(arrays, self._rows_in(arrays, roi), needed) mask = self._filter(columns, attr_filter) @@ -997,7 +2014,9 @@ def read_edges( fetch_on_v: bool = False, ) -> list[dict[str, Any]]: """Edges whose smaller endpoint (``u``) is in ``roi`` or in - ``nodes``; with ``fetch_on_v`` also those whose larger one is.""" + ``nodes``; with ``fetch_on_v`` also those whose larger one is. + :meth:`read_arrays` returns the same edges as arrays with + ``edge_ends="u"`` and ``edge_ends="either"``.""" if roi is not None and nodes is not None: raise ValueError( "read_edges does not support both roi and nodes at the same time. " diff --git a/tests/test_csr_empty_cases.py b/tests/test_csr_empty_cases.py new file mode 100644 index 0000000..943a564 --- /dev/null +++ b/tests/test_csr_empty_cases.py @@ -0,0 +1,221 @@ +"""Every read and write of the CSR graph database on the four ways a result +can be empty: a region with no node, a region with nodes and no edge, a +graph with no edge at all, and a graph with no node.""" + +import itertools + +import networkx as nx +import numpy as np +import pytest +from funlib.geometry import Roi + +from funlib.persistence.graphs import CSRGraphDataBase +from funlib.persistence.types import Vec + +NONE = np.zeros(0, dtype=np.uint64) +WHOLE = Roi((0, 0, 0), (1000, 1000, 1000)) + + +def build(path, case): + """The graph of a case, the region to read, and the ids of the nodes in + that region and of those within reach of it.""" + if case == "no node in the graph": + ids, pos = NONE, np.zeros((0, 3)) + u = v = NONE + else: + # 1-2-3 joined near the origin; 7 and 8 on their own, far away + ids = np.array([1, 2, 3, 7, 8], dtype=np.uint64) + pos = np.array( + [[5, 5, 5], [5, 5, 15], [5, 5, 25], [505, 505, 505], [505, 505, 515]], + dtype=np.float64, + ) + u, v = ids[:2], ids[1:3] + if case == "no edge in the graph": + u = v = NONE + weight = np.full(len(u), 0.5, dtype=np.float32) + kind = np.ones(len(u), dtype=np.int8) + if case == "no edge in the graph, none given": + db = CSRGraphDataBase.from_arrays( + path, ids, {"position": pos, "size": np.arange(len(ids))}, cell_size=20.0 + ) + else: + db = CSRGraphDataBase.from_arrays( + path, + ids, + {"position": pos, "size": np.arange(len(ids))}, + u, + v, + {"weight": weight, "kind": kind}, + cell_size=20.0, + ) + db.close() + roi = { + "no node in the region": Roi((800, 800, 800), (10, 10, 10)), + "nodes and no edge in the region": Roi((500, 500, 500), (20, 20, 20)), + }.get(case, WHOLE) + lo, hi = np.array(roi.begin), np.array(roi.end) + inside = ids[((pos >= lo) & (pos < hi)).all(axis=1)] if len(ids) else NONE + return roi, sorted(inside.tolist()) + + +CASES = [ + "no node in the region", + "nodes and no edge in the region", + "no edge in the graph", + "no edge in the graph, none given", + "no node in the graph", +] + + +def check(db, nodes, edges, expected_ids, extras, own=False, node_attrs=None): + """A result of the documented shape, whatever it holds.""" + n = len(nodes["id"]) + assert nodes["id"].dtype == np.uint64 and nodes["id"].ndim == 1 + assert nodes["step"].dtype == np.int16 and nodes["step"].shape == (n,) + if expected_ids is not None: + assert sorted(nodes["id"].tolist()) == expected_ids + names = list(db.node_attrs) if node_attrs is None else node_attrs + assert set(nodes) == {"id", "step", *names, *(["own"] if own else [])} + if "position" in names: + assert nodes["position"].shape == (n, 3) + assert nodes["position"].dtype == np.float64 + if "size" in names: + assert nodes["size"].shape == (n,) and nodes["size"].dtype == np.int64 + if extras and node_attrs is None: + assert nodes["vec"].shape == (n, 3) and nodes["vec"].dtype == np.float32 + assert nodes["label"].shape == (n,) and nodes["label"].dtype == np.int32 + if own: + assert nodes["own"].dtype == bool and nodes["own"].shape == (n,) + m = len(edges["u"]) + assert edges["u"].dtype == edges["v"].dtype == np.uint64 + assert edges["v"].shape == (m,) + assert set(edges) == {"u", "v", *db.edge_attrs} + for name, dtype in (("weight", np.float32), ("kind", np.int8)): + if name in edges: + assert edges[name].shape == (m,) and edges[name].dtype == dtype + return n, m + + +@pytest.mark.parametrize("extras", [False, True], ids=["plain", "extra fields"]) +@pytest.mark.parametrize("case", CASES) +def test_every_read_and_write_on_an_empty_result(tmp_path, case, extras): + path = tmp_path / "g.csr" + roi, inside = build(path, case) + ids_all = sorted(CSRGraphDataBase(path).read_arrays()[0]["id"].tolist()) + has_weight = "weight" in CSRGraphDataBase(path).edge_attrs + + if extras: + # -- the extra-fields writes and their finalize --------------------- + db = CSRGraphDataBase(path, mode="r+", extra_fields=tmp_path / "pred") + db.finalize() # nothing written yet + with db.bulk_write_mode(): + pass + nodes_in, _ = db.read_arrays(roi) + with db.bulk_write_mode(): + # the nodes of the region, which may be none + db.write_node_arrays( + nodes_in["id"], + vec=np.ones((len(nodes_in["id"]), 3), np.float32), + label=np.full(len(nodes_in["id"]), 4, np.int32), + ) + assert db.node_attrs["vec"] == Vec("float32", 3) + graph = db.read_graph(roi, node_attrs=["position", "label"]) + for _, data in graph.nodes(data=True): + if "position" in data: + data["label"] = 9 + db.write_attrs(graph, roi=roi, node_attrs=["label"]) + db.write_nodes({}, attributes=["label", "another"]) + db.write_nodes({int(i): {"label": 9} for i in inside}) + db.finalize() + db = CSRGraphDataBase(path, extra_fields=tmp_path / "pred") + labels = db.read_arrays()[0] + written = sorted(labels["id"][labels["label"] == 9].tolist()) + assert written == inside + else: + db = CSRGraphDataBase(path) + + # -- read_arrays ------------------------------------------------------- + step_choices = [None, [], *([["weight"]] if has_weight else [])] + for steps, step_edges, edge_ends in itertools.product( + (0, 1, 3), step_choices, ("both", "u", "either") + ): + nodes, edges = db.read_arrays( + roi, num_steps=steps, step_edges=step_edges, edge_ends=edge_ends + ) + n, m = check(db, nodes, edges, inside if steps == 0 else None, extras) + assert set(inside) <= set(nodes["id"].tolist()) <= set(ids_all) + if edge_ends == "both": + assert set(edges["u"].tolist()) | set(edges["v"].tolist()) <= set( + nodes["id"].tolist() + ) + nodes, edges = db.read_arrays(roi, node_attrs=[], edge_attrs=[]) + assert set(nodes) == {"id", "step"} and set(edges) == {"u", "v"} + nodes, edges = db.read_arrays() + assert check(db, nodes, edges, ids_all, extras)[0] == len(ids_all) + + # -- read_block -------------------------------------------------------- + contexts = (None, 0, 5, 2.5, [0, 0, 30], 2000) + for context, steps, edge_ends in itertools.product( + contexts, (0, 2), ("both", "u", "either") + ): + for step_edges in step_choices: + for node_attrs in (None, [], ["size"]): + nodes, edges = db.read_block( + roi, + context=context, + num_steps=steps, + node_attrs=node_attrs, + step_edges=step_edges, + edge_ends=edge_ends, + ) + check(db, nodes, edges, None, extras, own=True, node_attrs=node_attrs) + assert sorted(nodes["id"][nodes["own"]].tolist()) == inside + if context is None and steps == 0: + assert nodes["own"].all() + + # -- the reads that give dictionaries and a networkx graph ------------- + listed = db.read_nodes(roi) + assert sorted(n["id"] for n in listed) == inside + assert db.read_nodes(roi, attr_filter={"size": 10**6}) == [] + for fetch_on_v in (False, True): + from_roi = db.read_edges(roi, fetch_on_v=fetch_on_v) + from_nodes = db.read_edges(nodes=listed, fetch_on_v=fetch_on_v) + assert sorted((e["u"], e["v"]) for e in from_roi) == sorted( + (e["u"], e["v"]) for e in from_nodes + ) + assert db.read_edges(nodes=[], fetch_on_v=fetch_on_v) == [] + graph = db.read_graph(roi, fetch_on_v=fetch_on_v) + assert set(inside) <= set(graph.nodes) + assert graph.number_of_edges() == len(from_roi) + _, edges = db.read_arrays(roi, edge_ends="either" if fetch_on_v else "u") + assert len(edges["u"]) == len(from_roi) + assert db.read_graph(roi, read_edges=False).number_of_edges() == 0 + assert db.read_graph(roi, nodes_filter={"size": 10**6}).number_of_nodes() == 0 + assert isinstance(db.read_graph(), nx.Graph) + assert db.has_edges(roi) is bool(db.read_edges(roi, fetch_on_v=True)) + assert db.num_nodes == len(ids_all) + + +def test_a_database_that_was_created_and_never_written_reads_as_empty(tmp_path): + db = CSRGraphDataBase( + tmp_path / "g.csr", + mode="w", + node_attrs={"position": Vec(float, 3), "size": int}, + edge_attrs={"weight": "float32", "kind": "int8"}, + cell_size=20.0, + ) + for handle in (db, CSRGraphDataBase(tmp_path / "g.csr")): + for context, steps, edge_ends in itertools.product( + (None, 0, 5), (0, 2), ("both", "u", "either") + ): + nodes, edges = handle.read_block( + WHOLE, context=context, num_steps=steps, edge_ends=edge_ends + ) + assert check(handle, nodes, edges, [], False, own=True) == (0, 0) + nodes, edges = handle.read_arrays(num_steps=1, step_edges=["weight"]) + assert check(handle, nodes, edges, [], False) == (0, 0) + assert handle.read_nodes(WHOLE) == [] and handle.read_edges(WHOLE) == [] + assert handle.read_graph(WHOLE).number_of_nodes() == 0 + assert handle.has_edges(WHOLE) is False + db.finalize() # nothing to merge + assert db.num_nodes == 0 diff --git a/tests/test_csr_extra_fields.py b/tests/test_csr_extra_fields.py new file mode 100644 index 0000000..636b6bb --- /dev/null +++ b/tests/test_csr_extra_fields.py @@ -0,0 +1,916 @@ +"""Extra node attributes of a CSR graph, kept in directories of their own.""" + +import hashlib +import json +import multiprocessing as mp +from typing import Any + +import networkx as nx +import numpy as np +import pytest +from funlib.geometry import Roi + +from funlib.persistence.graphs import CSRGraphDataBase +from funlib.persistence.graphs.csr_graph_database import ( + GraphIsReadOnly, + UnfinalizedWrites, +) +from funlib.persistence.graphs.graph_database import AttributeType +from funlib.persistence.types import Vec + +N = 600 +TYPES: dict[str, AttributeType] = { + "vec": Vec("float32", 3), + "label": "int32", + "seen": bool, + "score": float, +} + + +def graph_arrays(n=N, seed=0): + rng = np.random.default_rng(seed) + ids = rng.choice(10 * n, size=n, replace=False).astype(np.uint64) + 1 + pos = rng.uniform(0, 100, size=(n, 3)) + u, v = ids[:-1], ids[1:] # a path through the nodes in the order given + return ids, pos, u, v + + +def make_graph(path, n=N, seed=0): + ids, pos, u, v = graph_arrays(n, seed) + weight = np.ones(len(u), dtype=np.float32) + CSRGraphDataBase.from_arrays( + path, ids, {"position": pos}, u, v, {"weight": weight}, cell_size=20.0 + ).close() + return ids, pos + + +def vec_of(ids): + ids = np.asarray(ids, dtype=np.float32) + return np.stack([ids, ids * 2, ids * 3], axis=1) + + +def expanded(tmp_path, mode="r+", names=("vec", "label", "seen", "score")): + """The graph with the directory ``pred``; in mode r+ the attributes + ``names`` are declared up front, with the types of ``TYPES``.""" + return CSRGraphDataBase( + tmp_path / "g.csr", + mode=mode, + node_attrs={k: TYPES[k] for k in names} if mode == "r+" else None, + extra_fields=tmp_path / "pred", + ) + + +def opened(tmp_path, mode="r", folder="pred"): + """The graph opened with a directory, by its path alone.""" + return CSRGraphDataBase( + tmp_path / "g.csr", mode=mode, extra_fields=tmp_path / folder + ) + + +def snapshot(folder): + """Every file under a directory with the sha256 of its bytes.""" + return { + str(p.relative_to(folder)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(folder.rglob("*")) + if p.is_file() + } + + +def by_id(nodes, name): + return dict(zip(nodes["id"].tolist(), nodes[name].tolist(), strict=True)) + + +def test_extra_attributes_are_written_and_read_through_the_graph(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + before = snapshot(tmp_path / "g.csr") + db = expanded(tmp_path) + assert db.node_attrs == { + "position": Vec("float64", 3), + "vec": Vec("float32", 3), + "label": "int32", + "seen": "bool", + "score": "float64", + } + half = ids[: N // 2] + with db.bulk_write_mode(): + db.write_node_arrays( + half, + vec=vec_of(half), + label=(half % 5 + 1).astype(np.int32), + seen=np.ones(len(half), dtype=bool), + score=half / 7, + ) + + # the graph's own directory: no file added, removed or changed + assert snapshot(tmp_path / "g.csr") == before + # the extra directory: meta.json, the lock, one array per attribute + names = sorted(p.name.split("-")[0] for p in (tmp_path / "pred").iterdir()) + assert names == [ + "finalize.lock", + "meta.json", + "node_label", + "node_score", + "node_seen", + "node_vec", + "segments", + ] + assert list((tmp_path / "pred" / "segments").iterdir()) == [] + + # read back, by a new handle that names what it wants + db = expanded(tmp_path, mode="r") + nodes, edges = db.read_arrays() + assert len(nodes["id"]) == N and len(edges["u"]) == N - 1 + written = np.isin(nodes["id"], half) + assert nodes["vec"][written].tolist() == vec_of(nodes["id"][written]).tolist() + assert nodes["label"][written].tolist() == (nodes["id"][written] % 5 + 1).tolist() + assert nodes["seen"][written].all() + assert nodes["score"][written].tolist() == (nodes["id"][written] / 7).tolist() + # a node that was never written: NaN for a float, 0 for an integer or bool + assert np.isnan(nodes["vec"][~written]).all() + assert np.isnan(nodes["score"][~written]).all() + assert not nodes["label"][~written].any() and not nodes["seen"][~written].any() + # values are in the graph's row order: the arrays line up with its ids + rows = np.load(tmp_path / "g.csr" / db.meta["generation"] / "ids.npy") + (file,) = (tmp_path / "pred").glob("node_label-*.npy") + stored = np.load(file) + assert stored.shape == (N,) + assert stored.tolist() == np.where(np.isin(rows, half), rows % 5 + 1, 0).tolist() + + +def test_region_and_step_reads_return_extra_attributes(tmp_path): + ids, pos = make_graph(tmp_path / "g.csr") + db = expanded(tmp_path, names=("vec", "label")) + with db.bulk_write_mode(): + db.write_node_arrays(ids, vec=vec_of(ids), label=(ids % 9).astype(np.int32)) + plain = CSRGraphDataBase(tmp_path / "g.csr") + roi = Roi((0, 0, 0), (50, 60, 70)) + + for steps in (0, 2): + wanted, wanted_edges = plain.read_arrays(roi, num_steps=steps) + nodes, edges = db.read_arrays(roi, num_steps=steps) + assert ( + nodes["id"].tolist() == wanted["id"].tolist() and 0 < len(nodes["id"]) < N + ) + assert nodes["step"].tolist() == wanted["step"].tolist() + assert edges["u"].tolist() == wanted_edges["u"].tolist() + assert nodes["vec"].tolist() == vec_of(nodes["id"]).tolist() + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + + nodes, _ = db.read_block(roi, context=10, num_steps=1, node_attrs=["label"]) + assert set(nodes) == {"id", "label", "step", "own"} + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + assert 0 < nodes["own"].sum() < len(nodes["id"]) + + listed = db.read_nodes(roi, read_attrs=["label", "vec"]) + assert sorted(n["id"] for n in listed) == sorted(plain.read_arrays(roi)[0]["id"]) + assert all(n["label"] == n["id"] % 9 for n in listed) + assert all(n["vec"] == (n["id"], n["id"] * 2, n["id"] * 3) for n in listed) + only = db.read_nodes(roi, attr_filter={"label": 4}, read_attrs=["label"]) + assert only and all(n["id"] % 9 == 4 for n in only) + + graph = db.read_graph(roi) + inside = [n for n, d in graph.nodes(data=True) if "position" in d] + assert all(graph.nodes[n]["label"] == n % 9 for n in inside) + assert graph.number_of_edges() == plain.read_graph(roi).number_of_edges() + + with pytest.raises(ValueError, match="unknown node attribute 'nope'"): + db.read_arrays(roi, node_attrs=["nope"]) + # the plain handle does not know the extra attributes + with pytest.raises(ValueError, match="unknown node attribute 'label'"): + plain.read_arrays(roi, node_attrs=["label"]) + + +def _worker(root, part, parts, start): + ids, _, _, _ = graph_arrays() + # the path alone: every worker creates the attributes with its first write + db = CSRGraphDataBase(root / "g.csr", mode="r+", extra_fields=root / "pred") + start.wait() + with db.bulk_write_mode(worker=True): + for block in np.array_split(ids[part::parts], 10): + db.write_node_arrays( + block, vec=vec_of(block), label=(block % 9).astype(np.int32) + ) + + +def test_several_processes_create_and_write_the_same_attributes(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + before = snapshot(tmp_path / "g.csr") + assert not (tmp_path / "pred").exists() + parts = 4 + ctx = mp.get_context("spawn") + start = ctx.Barrier(parts) + procs = [ + ctx.Process(target=_worker, args=(tmp_path, part, parts, start)) + for part in range(parts) + ] + for p in procs: + p.start() + for p in procs: + p.join() + assert [p.exitcode for p in procs] == [0] * parts + assert len(list((tmp_path / "pred" / "segments").glob("*.npys"))) == parts + # they agreed on one declaration, the type of the values written + assert CSRGraphDataBase.stored_extra_fields(tmp_path / "pred") == { + "vec": Vec("float32", 3), + "label": "int32", + } + + db = opened(tmp_path, "r+") + # until the finalize a read of the extra attributes is refused, a read + # of the graph's own is not + with pytest.raises(UnfinalizedWrites, match="pred has writes"): + db.read_arrays() + assert len(db.read_arrays(node_attrs=["position"])[0]["id"]) == N + db.finalize() + nodes, _ = db.read_arrays() + assert sorted(nodes["id"].tolist()) == sorted(ids.tolist()) + assert nodes["vec"].tolist() == vec_of(nodes["id"]).tolist() + assert nodes["label"].tolist() == (nodes["id"] % 9).tolist() + assert list((tmp_path / "pred" / "segments").iterdir()) == [] + assert snapshot(tmp_path / "g.csr") == before + + +def test_the_path_alone_opens_what_a_directory_holds(tmp_path): + ids, _ = make_graph(tmp_path / "g.csr") + with pytest.raises(ValueError, match="holds no extra node attributes.*'r\\+'"): + opened(tmp_path) + (tmp_path / "empty").mkdir() + with pytest.raises(ValueError, match="holds no extra node attributes"): + opened(tmp_path, folder="empty") + db = opened(tmp_path, "r+") # a directory that does not exist yet + assert not (tmp_path / "pred").exists() + assert db.node_attrs == {"position": Vec("float64", 3)} + assert len(db.read_arrays()[0]["id"]) == N + + # the first write of a name creates it, with the type of its values + with db.bulk_write_mode(): + db.write_node_arrays( + ids, + vec=vec_of(ids), + label=(ids % 9).astype(np.int16), + seen=ids % 2 == 0, + ) + types: dict[str, AttributeType] = { + "vec": Vec("float32", 3), + "label": "int16", + "seen": "bool", + } + assert CSRGraphDataBase.stored_extra_fields(tmp_path / "pred") == types + assert db.node_attrs == {"position": Vec("float64", 3), **types} + stored = json.loads((tmp_path / "pred" / "meta.json").read_text()) + assert stored["node_attrs"]["vec"] == {"dtype": "-<12 characters>.npy, of at most 255 bytes + for name in ("x" * 234, "x" * 300): + with pytest.raises(ValueError, match="at most 233 characters"): + db.write_node_arrays(few, **{name: np.ones(4, np.float32)}) + longest = CSRGraphDataBase( + tmp_path / "g.csr", mode="r+", extra_fields=tmp_path / "l" + ) + longest.write_node_arrays(few, **{"x" * 233: np.ones(4, np.float32)}) + (stored,) = (tmp_path / "l").glob("node_*.npy") + assert len(stored.name) == 255 + assert np.nansum(opened(tmp_path, folder="l").read_arrays()[0]["x" * 233]) == 4 + # an id is not negative + with pytest.raises(ValueError, match="-1 is not a node id"): + db.write_node_arrays(np.array([-1, 2, 3, 4]), late=np.ones(4)) + with pytest.raises(ValueError, match="-1 is not a node id"): + db.write_nodes({-1: {"label": 1}}) + db.write_node_arrays(few[:0], **{"ok-1.b_2": np.ones(0, np.float32)}) + assert "ok-1.b_2" in db.node_attrs + # node ids are integers: 2.5 is not node 2 + for bad in (few.astype(np.float64), few.reshape(2, 2), np.array(["1"] * 4)): + with pytest.raises(ValueError, match="node ids are integers, one per node"): + db.write_node_arrays(bad, late=np.ones(4)) + assert "late" not in db.node_attrs + # a call that is refused for one attribute declares none of the others + with pytest.raises(ValueError, match="'label' is int32 in .*pred, not int64"): + db.write_node_arrays(few, fresh=np.ones(4), label=np.ones(4, np.int64)) + with pytest.raises(ValueError, match="'cube' has shape"): + db.write_node_arrays(few, fresh=np.ones(4), cube=np.zeros((4, 2, 2))) + with pytest.raises(ValueError, match="each of the 4"): + db.write_node_arrays(few, fresh=np.ones(4), short=np.ones(1)) + with pytest.raises(ValueError, match="'label' is int32"): + db.write_nodes( + {int(few[0]): {"fresh": 1, "label": 0.5}}, attributes=["fresh", "label"] + ) + assert list((tmp_path / "pred" / "segments").glob("*.npys")) == [] + assert sorted(CSRGraphDataBase.stored_extra_fields(tmp_path / "pred")) == [ + "label", + "ok-1.b_2", + "vec", + ] + nodes, _ = opened(tmp_path).read_arrays() + assert sorted(nodes) == ["id", "label", "ok-1.b_2", "position", "step", "vec"] + assert nodes["id"].dtype == np.uint64 and sorted(nodes["id"]) == sorted(ids) + # a directory that holds such a name (written by an earlier version) is + # refused when it is opened, not read with the node ids overwritten + meta = json.loads((tmp_path / "pred" / "meta.json").read_text()) + poisoned = tmp_path / "poisoned" + poisoned.mkdir() + meta["node_attrs"]["id"] = {"dtype": "