Skip to content
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/gh-ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ jobs:

- name: install package deps
run: |
micromamba install numpy scipy mrcfile pytest pytest-cov codecov
micromamba install numpy scipy mrcfile pytest pytest-cov codecov openvdb

- name: check install
run: |
Expand Down
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ Contributors:
* Andrés Montoya <conradolandia> (logo)
* Rich Waldo <plethorachutney>
* Pradyumn Prasad <Pradyumn-cloud>
* Shreejan Dolai <spyke7>
15 changes: 12 additions & 3 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,20 @@ 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
??/??/???? orbeckst, spyke7

* 1.1.1
* 1.2.0

Fixes
Enhancements

* Added openVDB format exports (Issue #141, PR #148)


Fixes


01/22/2026 IAlibay, ollyfutur, conradolandia, orbeckst, PlethoraChutney,
Expand All @@ -35,6 +43,7 @@ The rules for this file:

Enhancements

* `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)
Expand Down
3 changes: 3 additions & 0 deletions doc/source/gridData/formats.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ small number of file formats is directly supported.
:mod:`~gridData.gOpenMol` gOpenMol_ plt x
:mod:`~gridData.mrc` CCP4_ ccp4,mrc x x subset implemented
:class:`~gridData.core.Grid` pickle pickle x x standard Python pickle of the Grid class
:mod:`~gridData.OpenVDB` OpenVDB_ vdb x implemented for Blender visualization
============================ ========== ========= ===== ===== =========================================


Expand All @@ -39,6 +40,7 @@ small number of file formats is directly supported.
.. _OpenDX: http://www.opendx.org/
.. _gOpenMol: http://www.csc.fi/gopenmol/
.. _CCP4: http://www.ccpem.ac.uk/mrc_format/mrc2014.php
.. _OpenVDB: https://www.openvdb.org/


Format-specific modules
Expand All @@ -50,3 +52,4 @@ Format-specific modules
formats/OpenDX
formats/gOpenMol
formats/mrc
formats/OpenVDB
2 changes: 2 additions & 0 deletions doc/source/gridData/formats/OpenVDB.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.. automodule:: gridData.OpenVDb

219 changes: 219 additions & 0 deletions gridData/OpenVDB.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
r"""
:mod:`~gridData.OpenVDB` --- routines to write OpenVDB files
=============================================================

The `OpenVDB format`_ is used by Blender_ and other VFX software for
volumetric data.

.. _`OpenVDB format`: https://www.openvdb.org
.. _Blender: https://www.blender.org/

This module uses the openvdb_ library to write OpenVDB files.

.. _openvdb: 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_.
See the `Blender volume docs`_ for details on importing VDB files.

.. _`Blender volume docs`: https://docs.blender.org/manual/en/latest/modeling/volumes/introduction.html

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) or (shift+A -> Volume -> Import OpenVDB). See `importing VDB in Blender`_ for details.

.. _`importing VDB in Blender`: https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/input/import/vdb.html


Building an OpenVDB field from a numpy array
---------------------------------------------

If you want to create VDB files without using the Grid class,
you can directly use the OpenVDB field API. This is useful
for custom workflows or when integrating with other libraries.

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

try:
import openvdb as vdb

except ImportError:
vdb = None


class OpenVDBField(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, grid, origin, delta, name='density', tolerance=1e-10):
"""Initialize an OpenVDB field.

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)
name : str
Name of the grid (will be visible in Blender), default 'density'
threshold : float
Values below this threshold are treated as background (sparse),
default 1e-10

Raises
------
ImportError
If openvdb is not installed
ValueError
If grid is not 3D, or if delta is not 1D/2D or describes
non-orthorhombic cell

"""
if vdb is None:
raise ImportError(
"openvdb is required to write VDB files. "
"Install it with: conda install -c conda-forge openvdb"
)
self.name = name
self.tolerance = tolerance
self._populate(grid, origin, delta)

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, or if delta is not 1D/2D or describes
non-orthorhombic cell

"""
grid = numpy.asarray(grid)
if grid.ndim != 3:
raise ValueError(
f"OpenVDB only supports 3D grids, got {grid.ndim}D")

self.grid = grid.astype(numpy.float32)
self.grid=numpy.ascontiguousarray(self.grid, dtype=numpy.float32)

self.origin = numpy.asarray(origin)

# Handle delta: could be 1D array or diagonal matrix
delta = numpy.asarray(delta)
if delta.ndim == 2:
if (delta.shape != (3,3)):
raise ValueError("delta as a matrix must be 3x3")

if not numpy.allclose(delta, numpy.diag(numpy.diag(delta))):
raise ValueError("Non-orthorhombic cells are not supported")

self.delta = numpy.diag(delta)

elif delta.ndim == 1:
if (len(delta) != 3):
raise ValueError("delta must have length-3 for 3D grids")
self.delta=delta

else:
raise ValueError(
"delta must be either a length-3 vector or a 3x3 diagonal matrix"
)

def write(self, filename):
"""Write the field to an OpenVDB file.

Parameters
----------
filename : str
Output filename (should end in .vdb)

"""

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)

matrix = [
[self.delta[0], 0.0, 0.0, 0.0],
[0.0, self.delta[1], 0.0, 0.0],
[0.0, 0.0, self.delta[2], 0.0],
[corner_origin[0], corner_origin[1], corner_origin[2], 1.0]
]

vdb_grid.background = 0.0
vdb_grid.transform = vdb.createLinearTransform(matrix)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume that the transformation is required to make the VDB grid to have the correct origin and delta in general.

Or is this something specific to the MN blender use, @PardhavMaradani ?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or is this something specific to the MN blender use, @PardhavMaradani ?

I addressed this in the comment below. Thanks


vdb_grid.copyFromArray(self.grid, tolerance=self.tolerance)
vdb_grid.prune()

vdb.write(filename, grids=[vdb_grid])
3 changes: 2 additions & 1 deletion gridData/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
24 changes: 24 additions & 0 deletions gridData/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from . import OpenDX
from . import gOpenMol
from . import mrc
from . import OpenVDB


def _grid(x):
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -699,6 +701,28 @@ 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(
f"OpenVDB export requires a 3D grid, got {self.grid.ndim}D")

grid_name = self.metadata.get('name', 'density')

vdb_field = OpenVDB.OpenVDBField(
grid=self.grid,
origin=self.origin,
delta=self.delta,
name=grid_name
)
vdb_field.write(filename)

def _export_mrc(self, filename, **kwargs):
"""Export the density grid to an MRC/CCP4 file.
Expand Down
Loading