API#

Arrays#

Array, open_ds, prepare_ds, open_ome_ds and prepare_ome_ds are importable from funlib.persistence.

class funlib.persistence.arrays.array.Array(data, offset=None, voxel_size=None, axis_names=None, units=None, types=None, chunks='auto', lazy_op=None, strict_metadata=False, scheduler=None)#

A thin wrapper around a dask array containing additional metadata such as the voxel size, offset, and axis names.

Parameters:
  • data (np.ndarray) – The numpy array like object to wrap.

  • offset (Sequence[int] | None) – The offset of the array in world units. Defaults to 0 for every dimension if not provided

  • voxel_size (Sequence[int] | None) – The size of a voxel. If not provided the voxel size is assumed to be 1 in all dimensions.

  • axis_names (Sequence[str] | None) – The name of each axis. If not provided, the axis names are given names [“c1”, “c2”, “c3”, …]

  • units (Sequence[str] | None) – The units of each spatial dimension.

  • types (Sequence[str] | None) – The type of each dimension. Can be “space”, “channel”, or “time”. We treat both “space” and “time” as spatial dimensions for indexing with Roi and Coordinate classes in world units. If not provided, we fall back on the axis names and assume “channel” for any axis name that ends with “^” and “space” otherwise. If neither are provided we assume “space” for all dimensions. Note that the axis name parsing is depricated and will be removed in future versions and we highly recommend providing the types directly.

  • chunks (int | Sequence[int] | str | None) – See https://docs.dask.org/en/stable/generated/dask.array.from_array.html for details.

  • lazy_op (slice | int | tuple[int | slice | list[int] | ndarray, ...] | Callable | Roi | None) – The lazy_op to use for this array. If you would like apply multiple lazy_ops, please look into either the .lazy_op method or the SequentialLazyOp class.

  • strict_metadata (bool) – If True, then all metadata fields must be provided, including offset, voxel_size, axis_names, units, and types. Metadata can either be passed in or read from array attributes.

  • scheduler (str | None) – The dask scheduler used to compute reads (__getitem__ and to_ndarray); writes do not go through dask. None (the default) leaves the choice to dask, which uses its threaded scheduler for arrays. Pass “single-threaded” when the caller already parallelises array access (one process or thread per block, as daisy does), where dask’s own thread pool only adds contention and can deadlock. See https://docs.dask.org/en/stable/scheduler-overview.html for the available schedulers.

data: Array#
property attrs: dict#

Return dict that can be used to store custom metadata. Will be persistent for zarr arrays. If reading from zarr, any existing metadata (such as voxel_size, axis_names, etc.) will also be exposed here.

property chunk_shape: Coordinate | None#

the shard shape if sharded, else the chunk shape (an open_ds(chunks=...) override is reported as given). None for a view that is not writeable or that lazy operations moved off the stored chunk grid.

Type:

The write-safe chunk shape

property inner_chunk_shape: Coordinate | None#

Chunk shape for efficient reads. Can be smaller than the write-safe chunk_shape in the case of sharding. None for a view that lazy operations moved off the stored chunk grid.

property shard_shape: Coordinate | None#

The shard shape in the case of sharded datasets. None for non sharded or unwritable datasets, or off the stored chunk grid. See https://zarr.readthedocs.io/en/stable/user-guide/performance.html#sharding

uncollapsed_dims(physical=False)#

We support lazy slicing of arrays, such as x = Array(np.ones(5,5,5)) and x.lazy_op(np.s![0, :, :]). This will result in the first dimension being collapsed and future slicing operations will need to be 2D. We use _uncollapsed_dims to keep track of which dimensions are sliceable.

Return type:

list[bool]

property offset: Coordinate#

Get the offset of this array in world units.

property voxel_size: Coordinate#

Get the size of a voxel in world units.

property units: list[str]#
property axis_names: list[str]#
property types: list[str]#
property physical_shape#
property roi#

Get the Roi associated with this data.

property dims#
property channel_dims#
property spatial_dims#
property shape#

Get the shape in voxels of this array, This is equivalent to:

array.data.shape
property dtype#

Get the dtype of this array.

property is_writeable#
apply_lazy_ops(lazy_op)#
lazy_op(lazy_op)#

Apply an lazy operation to this array.

Parameters:

lazy_op (slice | int | tuple[int | slice | list[int] | ndarray, ...] | Callable | Roi) – The lazy operation to apply to this array. Common lazy operations include slicing (e.g. array.lazy_op(np.s_[0, :, :])), thresholding (e.g. array.lazy_op(lambda d: d > 0.5)), or normalizing (e.g. array.lazy_op(lambda d: d / 255)). Note that the lazy operation must come in the form of a slicing operation or a callable that takes a dask array and returns a dask array. Lazy operations that would change the shape of the array may make it impossible to properly query the data with Coordinate or Roi objects. In these cases, it may be more appropriate to recreate the array with the appropriate metadata. For example: sub_array = Array(array.data[::2, ::2, ::2], array.offset, array.voxel_size * 2, …)

__getitem__(key)#

Get a sub-array or a single value.

Parameters:

key (Roi or Coordinate or any numpy compatible key) – The Roi, Coordinate, or numpy compatible key indicating the data you want to read.

Return type:

ndarray

Returns:

A numpy array containing the data requested by the key. If using a Roi or Coordinate, the data will be returned in world units. If using a numpy compatible key, the data will be sliced as a regular numpy array.

__setitem__(key, value)#

Set the data of this array.

Parameters:
  • key (Roi | slice | tuple) – The region to write to. Can be a Roi for world-unit indexing, or any numpy-compatible key (e.g. np.s_[:], a slice, a tuple of slices).

  • value (ndarray | float | int) – The value to write. Can be a numpy array or a scalar that will be broadcast.

to_ndarray(roi, fill_value=0)#

An alternative implementation of __getitem__ that supports using fill values to request data that may extend outside the roi covered by self.

Parameters:
  • roi (Roi) –

    If given, copy only the data represented by this ROI. This is equivalent to:

    array[roi].to_ndarray()
    

  • fill_value (scalar, optional) – The value to use to fill in values that are outside the ROI provided by this data. Defaults to 0.

Return type:

ndarray

validate(strict=False)#
to_pixel_space(world_loc)#

Convert a point or roi in world space into the pixel space of this array. Works on sequences of floats by returning a numpy array that is not guaranteed to be aligned with pixels.

Parameters:

world_loc (Roi | Coordinate | Sequence[int | float] | ndarray) – The world space point or roi to convert to pixel space

Raises:

ValueError – If the world location falls outside the array’s roi

Returns:

The point or roi converted into the pixel

space of the array. If the input was a Coordinate or Roi, returns the same type of object. If the input was a sequence of python numbers, returns a numpy array with the result, which may or may not be integers.

Return type:

Roi | Coordinate | ndarray

to_world_space(pixel_loc)#

Convert a point or roi from pixel space in this array to the world coordinate system defined by this array’s roi and voxel size. Works on Coordiantes and Rois, as well as sequences of ints or floats.

Parameters:

pixel_loc (Roi | Coordinate | Sequence[int | float] | ndarray) – A location in pixel space of this array’s data.

Returns:

The world location of the given pixel location. If the input

was a Roi or Coordinate, return the same type of object. If it was a sequence of python numbers, return a numpy array that may be int or float.

Return type:

Roi | Coordinate | ndarray

funlib.persistence.arrays.datasets.open_ds(store, mode='r', metadata_format=None, offset=None, voxel_size=None, axis_names=None, units=None, types=None, chunks='strict', strict_metadata=False, scheduler=None, **kwargs)#

Open a dataset with common metadata that is useful for image processing.

Parameters:
Return type:

Array

Returns:

A Array supporting spatial indexing on your dataset.

funlib.persistence.arrays.datasets.prepare_ds(store, shape, offset=None, voxel_size=None, axis_names=None, units=None, types=None, chunk_shape=None, dtype=<class 'numpy.float32'>, mode='a', custom_metadata=None, sharding=False, inner_chunk_shape=None, scheduler=None, **kwargs)#

Prepare a Zarr or N5 dataset.

Parameters:
  • Store – See https://zarr.readthedocs.io/en/stable/api/creation.html#zarr.creation.open_array

  • shape (Sequence[int]) – The shape of the dataset to create. For all dimensions, including non-physical.

  • offset (Coordinate | None) – The offset of the dataset to prepare in world units. Only provide for physical dimensions. Set to all 0’s by default.

  • voxel_size (Coordinate | None) – The size of one voxel in the dataset in world units. Only provide for physical dimensions. Set to all 1’s by default.

  • axis_names (Sequence[str] | None) – The axis names of the dataset to create. Set to [“c{i}^”, “d{j}”] by default. Where i, j are the index of the non-physical and physical dimensions respectively.

  • units (Sequence[str] | None) – The units of the dataset to create. Only provide for physical dimensions. Set to all “” by default.

  • types (Sequence[str] | None) – The types of the axes of the dataset to create. For more details see: https://ngff.openmicroscopy.org/latest/#axes-md If not provided, we will first fall back on to axis_names if provided and use “channel” for axis names ending in “^”, and “space” otherwise. If neither are provided, we will assume all dimensions are spatial. Note that axis name parsing is depricated and will be removed in the future. Please provide types directly if you have a mix of spatial and non-spatial dimensions.

  • chunk_shape (Coordinate | None) – The shape of the write-safe chunks to use in the dataset. For all dimensions, including non-physical. This is the shard shape if using shards.

  • dtype (DTypeLike) – The datatype of the dataset to create.

  • mode (Literal['r', 'r+', 'a', 'w', 'w-']) – The mode to open the dataset in. See https://zarr.readthedocs.io/en/stable/api/creation.html#zarr.creation.open_array

  • custom_metadata (dict[str, Any] | None) – A dictionary of custom metadata to add to the dataset. This will be written to the zarr .attrs object.

  • sharding (bool) – Create a zarr v3 array of chunk_shape shards, each holding inner_chunk_shape chunks. A creation option: an existing dataset is compared by its write-safe chunk shape, sharded or not. For more information see https://zarr.readthedocs.io/en/stable/user-guide/performance.html#sharding

  • inner_chunk_shape (Coordinate | None) – The efficient-read chunk shape. Can be less than the write-safe chunk shape in the case of sharding; defaults per axis to the largest divisor of chunk_shape that is at most DEFAULT_INNER_CHUNK (64), or the whole axis if that divisor is below 16. Unsharded it can only restate chunk_shape. Given against an existing dataset it must match that dataset’s chunks.

  • scheduler (str | None) – The dask scheduler the returned Array computes reads with. None (the default) leaves the choice to dask. See Array.

  • kwargs –

    See additional arguments available here: https://zarr.readthedocs.io/en/stable/api/creation.html#zarr.creation.open_array (with sharding, a new array is created by zarr.create_array, which takes compressors, filters, serializer, …).

    Of particular interest might be compressor if you would like to use a different compression algorithm and synchronizer if you want to guarantee that no data is corrupted due to concurrent reads or writes.

Return type:

Array

Returns:

A Array pointing to the newly created dataset.

Raises:
  • A combination of chunk_shape, sharding and inner_chunk_shape that cannot –

  • be created raises ValueError, and a keyword argument the create does not –

  • take raises TypeError. With sharding=True this also covers a value –

  • zarr.create_array –

  • touched – nothing is created at store and nothing already there is changed,

  • so the corrected call can be retried in any mode. –

funlib.persistence.arrays.ome_datasets.open_ome_ds(store, name, mode='r', **kwargs)#

Open an ome-zarr dataset with common metadata that is useful for indexing with physcial coordinates.

Parameters:
Return type:

Array

Returns:

A Array supporting spatial indexing on your dataset.

funlib.persistence.arrays.ome_datasets.prepare_ome_ds(store, name, shape, dtype, chunk_shape=None, offset=None, voxel_size=None, axis_names=None, units=None, types=None, channel_names=None, **kwargs)#

Prepare an OME-Zarr dataset with common metadata that we use for indexing images with spatial coordinates.

Parameters:
  • Store – See https://czbiohub-sf.github.io/iohub/main/api/ngff.html#iohub.open_ome_zarr

  • shape (Sequence[int]) – The shape of the dataset to create. For all dimensions, including non-physical.

  • chunk_shape (Sequence[int] | None) – The shape of the chunks to use. If None, the default chunk shape is used.

  • offset (Sequence[int] | None) – The offset of the dataset in physical coordinates. If None, the default offset (0, …) is used.

  • voxel_size (Sequence[int] | None) – The size of a voxel in physical coordinates. If None, the default voxel size (1, …) is used.

  • axis_names (Sequence[str] | None) – The names of the axes in the dataset. If None, the default axis names (“d0”, “d1”, …) are used.

  • units (Sequence[str] | None) – The units of the axes in the dataset. If None, the default units (“”, “”, …) are used.

  • types (Sequence[str] | None) – The types of the axes in the dataset. If None, the default types (“space”, “space”, …) are used.

  • channel_names (list[str] | None) – The names of the channels in the dataset. If None, there must not be any channels. If channels are present and no channel names are provided an exception will be thrown.

  • mode – The mode to open the dataset in. See https://zarr.readthedocs.io/en/stable/api/creation.html#zarr.creation.open_array

  • kwargs – See additional arguments available here: https://czbiohub-sf.github.io/iohub/main/api/ngff.html#iohub.open_ome_zarr

Return type:

Array

Returns:

A Array pointing to the newly created dataset.

Metadata#

pydantic model funlib.persistence.arrays.metadata.MetaDataFormat#
Fields:
field axis_names_attr: str = 'axis_names'#
field offset_attr: str = 'offset'#
field types_attr: str = 'types'#
field units_attr: str = 'units'#
field voxel_size_attr: str = 'voxel_size'#
funlib.persistence.arrays.metadata.read_config()#
Return type:

dict | None

funlib.persistence.arrays.metadata.configure_library()#
funlib.persistence.arrays.metadata.get_default_metadata_format()#
Return type:

MetaDataFormat

funlib.persistence.arrays.metadata.set_default_metadata_format(metadata_format)#
class funlib.persistence.types.Vec(dtype, size)#

Graphs#

The graph databases are importable from funlib.persistence.graphs.

class funlib.persistence.graphs.graph_database.GraphDataBase#

Interface for graph databases that supports slicing to retrieve and write subgraphs.

Implementations should support the following interactions:

# graph_db is a GraphDataBase

# slicing with ROI to extract a subgraph
sub_graph = graph_db[Roi((0, 0, 0), (10, 10, 10))]

# sub_graph is a networkx Graph or DiGraph

# write graphs
graph_db.write_graph(sub_graph, Roi((0, 0, 0), (10, 10, 10)))
abstract property node_attrs: dict[str, type | str | Vec]#

Return the node attributes supported by the database.

abstract property edge_attrs: dict[str, type | str | Vec]#

Return the edge attributes supported by the database.

abstractmethod read_graph(roi=None, read_edges=True, node_attrs=None, edge_attrs=None, nodes_filter=None, edges_filter=None, fetch_on_v=False)#

Read a graph from the database for a given roi.

Parameters:
  • roi (Roi | None) – The region of interest to read. If None, read the entire graph.

  • read_edges (bool) – If True, read the edges of the graph. If False, only read the nodes.

  • node_attrs (list[str] | None) – If not None, only read the given node attributes.

  • edge_attrs (list[str] | None) – If not None, only read the given edge attributes.

  • nodes_filter (dict[str, Any] | None) – If not None, only read nodes matching these attribute values.

  • edges_filter (dict[str, Any] | None) – If not None, only read edges matching these attribute values.

  • fetch_on_v (bool) – If True, also fetch edges where the v endpoint matches (i.e., either endpoint is in the ROI or node list). If False (default), only fetch edges where u matches.

Return type:

Graph

abstractmethod write_graph(graph, roi=None, write_nodes=True, write_edges=True, node_attrs=None, edge_attrs=None, fail_if_exists=False, delete=False)#

Write a graph from the database for a given roi.

Parameters:
  • graph (Graph) – The graph to write.

  • roi (Roi | None) – The region of interest to write to. If None, write the entire graph.

  • write_nodes (bool) – If True, write the nodes of the graph. If False, only write the edges.

  • write_edges (bool) – If True, write the edges of the graph. If False, only write the nodes. Edges will only be written if u is contained in the roi.

  • node_attrs (list[str] | None) – If not None, only write the given node attributes.

  • edge_attrs (list[str] | None) – If not None, only write the given edge attributes.

  • fail_if_exists (bool) – If True, fail if a node or edge in the graph already exists in the database.

  • delete (bool) – If True, delete the graph (possibly within the roi) in the database before writing.

Return type:

None

abstractmethod write_attrs(graph, roi=None, node_attrs=None, edge_attrs=None)#

Alias call to write_graph with write_nodes and write_edges set to False.

Return type:

None

abstractmethod bulk_write_graph(graph, roi=None, write_nodes=True, write_edges=True, node_attrs=None, edge_attrs=None)#

Fast bulk write of a graph. Mirrors write_graph but optimized for large batch inserts. Does not support fail_if_exists or delete.

Return type:

None

abstractmethod bulk_write_mode(worker=False, node_writes=True, edge_writes=True)#

Context manager that optimizes the database for bulk writes.

Drops indexes and adjusts database settings for maximum write throughput, then restores them on exit.

Parameters:
  • worker (bool) – If False (default), drops and rebuilds indexes around the block. Set to True for parallel workers whose orchestrator manages indexes separately — only session-level performance settings will be adjusted.

  • node_writes (bool) – If True (default), drop/rebuild node primary key and position indexes. Ignored when worker=True.

  • edge_writes (bool) – If True (default), drop/rebuild edge primary key index. Ignored when worker=True.

class funlib.persistence.graphs.sql_graph_database.SQLGraphDataBase(mode='r+', position_attribute=None, directed=None, total_roi=None, nodes_table=None, edges_table=None, endpoint_names=None, node_attrs=None, edge_attrs=None)#

Bases: GraphDataBase

Base class for SQL-based graph databases.

Nodes must have a position attribute (set via argument position_attribute), which will be used for geometric slicing (see __getitem__ and read_graph).

Parameters:
  • mode (str) – Any of r (read-only), r+ (read and allow modifications), or w (create new database, overwrite if exists).

  • position_attribute (str | None) – The node attribute that contains position information. This will be used for slicing subgraphs via __getitem__.

  • directed (bool | None) – True if the graph is directed, false otherwise. If None, attempts to read value from existing database. If not found, defaults to false.

  • nodes_table (str | None) – The name of the nodes table. Defaults to nodes.

  • edges_table (str | None) – The name of the edges table. Defaults to edges.

  • endpoint_names (list[str] | None) – What names to use for the columns storing the start and end of an edge. Default is [‘u’, ‘v’].

  • node_attrs (dict[str, type | str | Vec] | None) – The custom attributes to store on each node.

  • edge_attrs (dict[str, type | str | Vec] | None) – The custom attributes to store on each edge.

read_graph(roi=None, read_edges=True, node_attrs=None, edge_attrs=None, nodes_filter=None, edges_filter=None, fetch_on_v=False)#

Read a graph from the database for a given roi.

Parameters:
  • roi (Roi | None) – The region of interest to read. If None, read the entire graph.

  • read_edges (bool) – If True, read the edges of the graph. If False, only read the nodes.

  • node_attrs (list[str] | None) – If not None, only read the given node attributes.

  • edge_attrs (list[str] | None) – If not None, only read the given edge attributes.

  • nodes_filter (dict[str, Any] | None) – If not None, only read nodes matching these attribute values.

  • edges_filter (dict[str, Any] | None) – If not None, only read edges matching these attribute values.

  • fetch_on_v (bool) – If True, also fetch edges where the v endpoint matches (i.e., either endpoint is in the ROI or node list). If False (default), only fetch edges where u matches.

Return type:

Graph

write_attrs(graph, roi=None, node_attrs=None, edge_attrs=None)#

Alias call to write_graph with write_nodes and write_edges set to False.

Return type:

None

write_graph(graph, roi=None, write_nodes=True, write_edges=True, node_attrs=None, edge_attrs=None, fail_if_exists=False, delete=False)#

Write a graph from the database for a given roi.

Parameters:
  • graph (Graph) – The graph to write.

  • roi (Roi | None) – The region of interest to write to. If None, write the entire graph.

  • write_nodes (bool) – If True, write the nodes of the graph. If False, only write the edges.

  • write_edges (bool) – If True, write the edges of the graph. If False, only write the nodes. Edges will only be written if u is contained in the roi.

  • node_attrs (list[str] | None) – If not None, only write the given node attributes.

  • edge_attrs (list[str] | None) – If not None, only write the given edge attributes.

  • fail_if_exists (bool) – If True, fail if a node or edge in the graph already exists in the database.

  • delete (bool) – If True, delete the graph (possibly within the roi) in the database before writing.

Return type:

None

bulk_write_graph(graph, roi=None, write_nodes=True, write_edges=True, node_attrs=None, edge_attrs=None)#

Fast bulk write of a graph. Mirrors write_graph but optimized for large batch inserts. Does not support fail_if_exists or delete.

Return type:

None

property node_attrs: dict[str, type | str | Vec]#

Return the node attributes supported by the database.

property edge_attrs: dict[str, type | str | Vec]#

Return the edge attributes supported by the database.

read_nodes(roi=None, attr_filter=None, read_attrs=None, join_collection=None)#

Return a list of nodes within roi.

Return type:

list[dict[str, Any]]

num_nodes(roi)#

Return the number of nodes in the roi.

Return type:

int

has_edges(roi)#

Returns true if there is at least one edge in the roi.

Return type:

bool

read_edges(roi=None, nodes=None, attr_filter=None, read_attrs=None, fetch_on_v=False)#

Returns a list of edges within roi, connected to provided nodes, or all edges.

Parameters:

fetch_on_v (bool) – If True, also match edges where the v endpoint is in the node list or ROI. If False (default), only match on u.

Raises:

ValueError – If both roi and nodes are provided.

Return type:

list[dict[str, Any]]

class funlib.persistence.graphs.sqlite_graph_database.SQLiteGraphDataBase(db_file, position_attribute, mode='r+', directed=None, total_roi=None, nodes_table='nodes', edges_table='edges', endpoint_names=None, node_attrs=None, edge_attrs=None)#

Bases: SQLGraphDataBase

bulk_write_mode(worker=False, node_writes=True, edge_writes=True)#

Context manager that optimizes the database for bulk writes.

Drops indexes and adjusts database settings for maximum write throughput, then restores them on exit.

Parameters:
  • worker (bool) – If False (default), drops and rebuilds indexes around the block. Set to True for parallel workers whose orchestrator manages indexes separately — only session-level performance settings will be adjusted.

  • node_writes (bool) – If True (default), drop/rebuild node primary key and position indexes. Ignored when worker=True.

  • edge_writes (bool) – If True (default), drop/rebuild edge primary key index. Ignored when worker=True.

class funlib.persistence.graphs.pgsql_graph_database.PgSQLGraphDatabase(position_attribute, db_name, db_host='localhost', db_user=None, db_password=None, db_port=None, mode='r+', directed=None, total_roi=None, nodes_table='nodes', edges_table='edges', endpoint_names=None, node_attrs=None, edge_attrs=None)#

Bases: SQLGraphDataBase

bulk_write_mode(worker=False, node_writes=True, edge_writes=True)#

Context manager that optimizes the database for bulk writes.

Drops indexes and adjusts database settings for maximum write throughput, then restores them on exit.

Parameters:
  • worker (bool) – If False (default), drops and rebuilds indexes around the block. Set to True for parallel workers whose orchestrator manages indexes separately — only session-level performance settings will be adjusted.

  • node_writes (bool) – If True (default), drop/rebuild node primary key and position indexes. Ignored when worker=True.

  • edge_writes (bool) – If True (default), drop/rebuild edge primary key index. Ignored when worker=True.