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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/source/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
202 changes: 202 additions & 0 deletions docs/source/graphs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<x>.npy (N, 64), in the graph's row order
pred/model_a/node_label-<x>.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_<attr>-*.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.
2 changes: 1 addition & 1 deletion src/funlib/persistence/__init__.py
Original file line number Diff line number Diff line change
@@ -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("."))
40 changes: 40 additions & 0 deletions src/funlib/persistence/graphs/_files.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading