diff --git a/AUTHORS b/AUTHORS index 78d26f7..d33a46b 100644 --- a/AUTHORS +++ b/AUTHORS @@ -27,5 +27,6 @@ Contributors: * Zhiyi Wu * Olivier Languin-Cattoën * Andrés Montoya (logo) +* Shreejan Dolai * Rich Waldo * Pradyumn Prasad diff --git a/CHANGELOG b/CHANGELOG index b3fb690..34717b9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -12,6 +12,9 @@ The rules for this file: use tabs but use spaces for formatting * accompany each entry with github issue/PR number (Issue #xyz) +------------------------------------------------------------------------------ +01/16/2026 IAlibay, ollyfutur, conradolandia, orbeckst, PlethoraChutney, + Pradyumn-cloud, spyke7 ------------------------------------------------------------------------------- ??/??/???? orbeckst @@ -27,6 +30,7 @@ The rules for this file: Changes + * Added OpenVDB module for exporting to .vdb format (PR #148) * update logo from https://github.com/MDAnalysis/mdanalysis-subprojects-branding (issue #143) * Python 3.13 and 3.14 are now supported (PR #140) @@ -35,6 +39,8 @@ The rules for this file: Enhancements + * Added openVDB format exports (Issue #141) + * `Grid` now accepts binary operations with any operand that can be * `Grid` now accepts binary operations with any operand that can be broadcasted to the grid's shape according to `numpy` broadcasting rules (PR #142) diff --git a/gridData/OpenVDB.py b/gridData/OpenVDB.py new file mode 100644 index 0000000..55e8fa5 --- /dev/null +++ b/gridData/OpenVDB.py @@ -0,0 +1,190 @@ +r""" +:mod:`~gridData.OpenVDB` --- routines to write OpenVDB files +============================================================= + +The OpenVDB format is used by Blender and other VFX software for +volumetric data. See https://www.openvdb.org + +pyopenvdb: https://github.com/AcademySoftwareFoundation/openvdb + +.. Note:: This module implements a simple writer for 3D regular grids, + sufficient to export density data for visualization in Blender. + +The OpenVDB format uses a sparse tree structure to efficiently store +volumetric data. It is the native format for Blender's volume system. + + +Writing OpenVDB files +--------------------- + +If you have a :class:`~gridData.core.Grid` object, you can write it to +OpenVDB format:: + + from gridData import Grid + g = Grid("data.dx") + g.export("data.vdb") + +This will create a file that can be imported directly into Blender +(File -> Import -> OpenVDB). + + +Building an OpenVDB field from a numpy array +--------------------------------------------- + +Requires: + +grid + numpy 3D array +origin + cartesian coordinates of the center of the (0,0,0) grid cell +delta + n x n array with the length of a grid cell along each axis + +Example:: + + import OpenVDB + vdb_field = OpenVDB.field('density') + vdb_field.populate(grid, origin, delta) + vdb_field.write('output.vdb') + + +Classes and functions +--------------------- + +""" + +import numpy +import warnings + +try: + import pyopenvdb as vdb +except ImportError: + try: + import openvdb as vdb + except ImportError: + vdb = None + + +class field(object): + """OpenVDB field object for writing volumetric data. + + This class provides a simple interface to write 3D grid data to + OpenVDB format, which can be imported into Blender and other + VFX software. + + The field object holds grid data and metadata, and can write it + to a .vdb file. + + Example + ------- + Create a field and write it:: + + vdb_field = OpenVDB.field('density') + vdb_field.populate(grid, origin, delta) + vdb_field.write('output.vdb') + + Or use directly from Grid:: + + g = Grid(...) + g.export('output.vdb', format='vdb') + + """ + + def __init__(self, name='density'): + """Initialize an OpenVDB field. + + Parameters + ---------- + name : str + Name of the grid (will be visible in Blender) + + """ + if vdb is None: + raise ImportError( + "pyopenvdb is required to write VDB files. " + "Install it with: conda install -c conda-forge openvdb" + ) + self.name = name + self.grid = None + self.origin = None + self.delta = None + + def populate(self, grid, origin, delta): + """Populate the field with grid data. + + Parameters + ---------- + grid : numpy.ndarray + 3D numpy array with the data + origin : numpy.ndarray + Coordinates of the center of grid cell [0,0,0] + delta : numpy.ndarray + Grid spacing (can be 1D array or diagonal matrix) + + Raises + ------ + ValueError + If grid is not 3D + + """ + grid = numpy.asarray(grid) + if grid.ndim != 3: + raise ValueError( + "OpenVDB only supports 3D grids, got {}D".format(grid.ndim)) + + self.grid = grid.astype(numpy.float32) + self.origin = numpy.asarray(origin) + + # Handle delta: could be 1D array or diagonal matrix + delta = numpy.asarray(delta) + if delta.ndim == 2: + self.delta = numpy.array([delta[i, i] for i in range(3)]) + else: + self.delta = delta + + def write(self, filename): + """Write the field to an OpenVDB file. + + Parameters + ---------- + filename : str + Output filename (should end in .vdb) + + """ + if self.grid is None: + raise ValueError("No data to write. Use populate() first.") + + # Create OpenVDB grid + vdb_grid = vdb.FloatGrid() + vdb_grid.name = self.name + + # this is an explicit linear transform using per-axis voxel sizes + # world = diag(delta) * index + corner_origin + corner_origin = (self.origin - 0.5 * self.delta).astype(float) + + # Constructing 4x4 row-major matrix where the last row is the translation + matrix = [ + [float(self.delta[0]), 0.0, 0.0, 0.0], + [0.0, float(self.delta[1]), 0.0, 0.0], + [0.0, 0.0, float(self.delta[2]), 0.0], + [float(corner_origin[0]), float(corner_origin[1]), float(corner_origin[2]), 1.0] + ] + + transform = vdb.createLinearTransform(matrix) + vdb_grid.transform = transform + + vdb_grid.background = 0.0 + + # Populate the grid + accessor = vdb_grid.getAccessor() + threshold = 1e-10 + + mask = numpy.abs(self.grid) > threshold + indices = numpy.argwhere(mask) + + for idx in indices: + i, j, k = idx + value = float(self.grid[i, j, k]) + accessor.setValueOn((i, j, k), value) + + vdb.write(filename, grids=[vdb_grid]) \ No newline at end of file diff --git a/gridData/__init__.py b/gridData/__init__.py index bfe79a1..c5aaa0e 100644 --- a/gridData/__init__.py +++ b/gridData/__init__.py @@ -110,8 +110,9 @@ from . import OpenDX from . import gOpenMol from . import mrc +from . import OpenVDB -__all__ = ['Grid', 'OpenDX', 'gOpenMol', 'mrc'] +__all__ = ['Grid', 'OpenDX', 'gOpenMol', 'mrc', 'OpenVDB'] from importlib.metadata import version __version__ = version("GridDataFormats") diff --git a/gridData/core.py b/gridData/core.py index 035d769..f92db91 100644 --- a/gridData/core.py +++ b/gridData/core.py @@ -45,6 +45,7 @@ from . import OpenDX from . import gOpenMol from . import mrc +from . import OpenVDB def _grid(x): @@ -222,6 +223,7 @@ def __init__(self, grid=None, edges=None, origin=None, delta=None, 'PKL': self._export_python, 'PICKLE': self._export_python, # compatibility 'PYTHON': self._export_python, # compatibility + 'VDB': self._export_vdb, 'MRC': self._export_mrc, } self._loaders = { @@ -699,6 +701,26 @@ def _export_dx(self, filename, type=None, typequote='"', **kwargs): if ext == '.gz': filename = root + ext dx.write(filename) + + def _export_vdb(self, filename, **kwargs): + """Export the density grid to an OpenVDB file. + + The file format is compatible with Blender's volume system. + Only 3D grids are supported. + + For the file format see https://www.openvdb.org + """ + if self.grid.ndim != 3: + raise ValueError( + "OpenVDB export requires a 3D grid, got {}D".format(self.grid.ndim)) + + # Get grid name from metadata if available + grid_name = self.metadata.get('name', 'density') + + # Create and populate VDB field + vdb_field = OpenVDB.field(grid_name) + vdb_field.populate(self.grid, self.origin, self.delta) + vdb_field.write(filename) def _export_mrc(self, filename, **kwargs): """Export the density grid to an MRC/CCP4 file. diff --git a/gridData/tests/test_vdb.py b/gridData/tests/test_vdb.py new file mode 100644 index 0000000..af7f654 --- /dev/null +++ b/gridData/tests/test_vdb.py @@ -0,0 +1,195 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_equal + +import pytest + +import gridData.OpenVDB +from gridData import Grid + +from . import datafiles + + +try: + import pyopenvdb as vdb + HAS_OPENVDB = True +except ImportError: + try: + import openvdb as vdb + HAS_OPENVDB = True + except ImportError: + HAS_OPENVDB = False + + +@pytest.mark.skipif(not HAS_OPENVDB, reason="pyopenvdb/openvdb not installed") +class TestVDBWrite: + """Test OpenVDB file format writing""" + + def test_write_vdb_from_grid(self, tmpdir): + """Test basic VDB export from Grid""" + data = np.arange(1, 28).reshape(3, 3, 3).astype(np.float32) + g = Grid(data, origin=np.zeros(3), delta=np.ones(3)) + + outfile = str(tmpdir / "test.vdb") + g.export(outfile, file_format='VDB') + + assert tmpdir.join("test.vdb").exists() + grids, metadata = vdb.readAll(outfile) + assert len(grids) == 1 + assert grids[0].name == 'density' + + def test_write_vdb_autodetect_extension(self, tmpdir): + """Test that .vdb extension is auto-detected""" + data = np.arange(24).reshape(2, 3, 4).astype(np.float32) + g = Grid(data, origin=[0, 0, 0], delta=[1, 1, 1]) + + outfile = str(tmpdir / "auto.vdb") + g.export(outfile) + assert tmpdir.join("auto.vdb").exists() + + def test_write_vdb_default_grid_name(self, tmpdir): + """Test that default grid name is used when no metadata""" + data = np.ones((3, 3, 3), dtype=np.float32) + g = Grid(data, origin=[0, 0, 0], delta=[1, 1, 1]) + g.metadata = {} + + outfile = str(tmpdir / "default_name.vdb") + g.export(outfile) + grids, metadata = vdb.readAll(outfile) + assert grids[0].name == 'density' + + def test_write_vdb_with_metadata(self, tmpdir): + """Test that grid name from metadata is used""" + data = np.ones((3, 3, 3), dtype=np.float32) + g = Grid(data, origin=[0, 0, 0], delta=[1, 1, 1]) + g.metadata['name'] = 'test_density' + + outfile = str(tmpdir / "metadata.vdb") + g.export(outfile) + grids, metadata = vdb.readAll(outfile) + assert grids[0].name == 'test_density' + + def test_write_vdb_origin_and_spacing(self, tmpdir): + """Test that origin and spacing are correctly written""" + data = np.ones((4, 4, 4), dtype=np.float32) + origin = np.array([10.0, 20.0, 30.0]) + delta = np.array([0.5, 0.5, 0.5]) + + g = Grid(data, origin=origin, delta=delta) + outfile = str(tmpdir / "transform.vdb") + g.export(outfile) + + grids, metadata = vdb.readAll(outfile) + grid_vdb = grids[0] + voxel_size = grid_vdb.transform.voxelSize() + assert_allclose([voxel_size[i] for i in range(3)], delta, rtol=1e-5) + + def test_write_vdb_from_ccp4(self, tmpdir): + """Test exporting CCP4 file to VDB""" + g = Grid(datafiles.CCP4) + outfile = str(tmpdir / "from_ccp4.vdb") + + g.export(outfile, file_format='VDB') + + assert tmpdir.join("from_ccp4.vdb").exists() + grids, metadata = vdb.readAll(outfile) + assert len(grids) == 1 + + def test_write_vdb_non3d_raises(self, tmpdir): + """Test that non-3D grids raise ValueError""" + data_2d = np.arange(12).reshape(3, 4) + g = Grid(data_2d, origin=[0, 0], delta=[1, 1]) + + outfile = str(tmpdir / "invalid.vdb") + with pytest.raises(ValueError, match="3D grid"): + g.export(outfile, file_format='VDB') + + def test_write_vdb_with_delta_matrix(self, tmpdir): + """Test writing with delta as diagonal matrix""" + data = np.ones((3, 3, 3), dtype=np.float32) + delta = np.diag([1.0, 2.0, 3.0]) + + vdb_field = gridData.OpenVDB.field('matrix_delta') + vdb_field.populate(data, origin=[0, 0, 0], delta=delta) + + outfile = str(tmpdir / "matrix_delta.vdb") + vdb_field.write(outfile) + assert tmpdir.join("matrix_delta.vdb").exists() + + def test_write_vdb_nonuniform_spacing(self, tmpdir): + """Test writing with non-uniform spacing""" + data = np.ones((3, 3, 3), dtype=np.float32) + delta = np.array([0.5, 1.0, 1.5]) + g = Grid(data, origin=[0, 0, 0], delta=delta) + + outfile = str(tmpdir / "nonuniform.vdb") + g.export(outfile) + assert tmpdir.join("nonuniform.vdb").exists() + + def test_write_vdb_sparse_data(self, tmpdir): + """Test writing sparse data""" + data = np.zeros((10, 10, 10), dtype=np.float32) + data[2, 3, 4] = 5.0 + data[7, 8, 9] = 10.0 + + g = Grid(data, origin=[0, 0, 0], delta=[1, 1, 1]) + outfile = str(tmpdir / "sparse.vdb") + g.export(outfile) + + assert tmpdir.join("sparse.vdb").exists() + grids, metadata = vdb.readAll(outfile) + assert len(grids) == 1 + + def test_write_vdb_negative_values(self, tmpdir): + """Test writing data with negative values""" + data = np.array([[[1.0, -2.0, 3.0], + [-4.0, 5.0, -6.0], + [7.0, -8.0, 9.0]]], dtype=np.float32) + + g = Grid(data, origin=[0, 0, 0], delta=[1, 1, 1]) + outfile = str(tmpdir / "negative.vdb") + g.export(outfile) + assert tmpdir.join("negative.vdb").exists() + + def test_write_vdb_zero_threshold(self, tmpdir): + """Test that very small values near zero are treated as background""" + data = np.ones((3, 3, 3), dtype=np.float32) * 1e-11 + data[1, 1, 1] = 1.0 + + g = Grid(data, origin=[0, 0, 0], delta=[1, 1, 1]) + outfile = str(tmpdir / "threshold.vdb") + g.export(outfile) + assert tmpdir.join("threshold.vdb").exists() + + def test_vdb_field_direct(self, tmpdir): + """Test using OpenVDB.field directly""" + data = np.arange(27).reshape(3, 3, 3).astype(np.float32) + + vdb_field = gridData.OpenVDB.field('direct_test') + vdb_field.populate(data, origin=[0, 0, 0], delta=[1, 1, 1]) + + outfile = str(tmpdir / "direct.vdb") + vdb_field.write(outfile) + + grids, metadata = vdb.readAll(outfile) + assert grids[0].name == 'direct_test' + + def test_vdb_field_no_data_raises(self, tmpdir): + """Test that writing without data raises ValueError""" + vdb_field = gridData.OpenVDB.field('empty') + outfile = str(tmpdir / "empty.vdb") + with pytest.raises(ValueError, match="No data to write"): + vdb_field.write(outfile) + + def test_vdb_field_2d_raises(self): + """Test that 2D data raises ValueError in populate""" + data_2d = np.arange(12).reshape(3, 4) + vdb_field = gridData.OpenVDB.field('test') + + with pytest.raises(ValueError, match="3D grids"): + vdb_field.populate(data_2d, origin=[0, 0], delta=[1, 1]) + + +@pytest.mark.skipif(HAS_OPENVDB, reason="Testing import error handling") +def test_vdb_import_error(): + with pytest.raises(ImportError, match="pyopenvdb is required"): + gridData.OpenVDB.field('test') \ No newline at end of file