Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
22a5995
added a simple program to export files in .vdb format
spyke7 Dec 27, 2025
c871534
Merge branch 'master' into add_openvdb
spyke7 Jan 18, 2026
d809198
updated changelog and OpenVDB.py
spyke7 Jan 18, 2026
242edb5
updated changelog and OpenVDB.py
spyke7 Jan 18, 2026
79c96de
fixed core.py errors
spyke7 Jan 18, 2026
0649210
fixed typo in OpenVDB.py
spyke7 Jan 18, 2026
f83f709
updated OpenVDB.py
spyke7 Jan 19, 2026
09b88a3
removed transpose inside populate()
spyke7 Jan 19, 2026
3c93f8d
test_vdb.py updated
spyke7 Jan 23, 2026
1765ae1
Merge branch 'master' into add_openvdb
spyke7 Jan 24, 2026
31831cb
modified test_vdb.py for coverage
spyke7 Jan 24, 2026
c55366b
updated test_vdb.py
spyke7 Jan 24, 2026
ea446d7
updated CHANGELOG and gh-ci.yaml
spyke7 Jan 25, 2026
1e2fd80
Updated docs, test_vdb.py and OpenVDB.py
spyke7 Jan 26, 2026
145a1dd
Updated tests
spyke7 Jan 26, 2026
4bd1d8a
updated test_vdb.py
spyke7 Jan 28, 2026
d010391
updated tests and OpenVDB.py
spyke7 Jan 29, 2026
c8e643d
updated tests and OpenVDB.py
spyke7 Jan 29, 2026
f87d3d8
Test updated and reformatted with black
spyke7 Feb 3, 2026
97aef4b
added skip if
spyke7 Feb 3, 2026
b6e5568
Apply suggestion from @orbeckst
orbeckst Feb 5, 2026
53a6017
Implemented preScale and postTranslate
spyke7 Feb 5, 2026
2c75469
Updated tests, OpenVDB.py and core.py
spyke7 Feb 7, 2026
acff126
Updated the OpenVDB.py with new API structure
spyke7 Feb 11, 2026
0231a44
Updated tests
spyke7 Feb 12, 2026
df03e8b
updated test_vdb.py and OpenVDB.py
spyke7 Feb 13, 2026
65bcc79
updated the for loop a little inside _get_best_grid_type
spyke7 Feb 21, 2026
40ca264
Merge branch 'master' into add_openvdb
orbeckst Apr 15, 2026
08d7b68
Merge branch 'master' into add_openvdb
spyke7 Apr 24, 2026
34ff183
updated openvdb.py with from_grid() and native
spyke7 Apr 24, 2026
19e996b
Merge branch 'master' into add_openvdb
orbeckst Apr 30, 2026
9fd09c2
Update gridData/core.py
spyke7 May 2, 2026
08009a2
Update gridData/tests/test_vdb.py
spyke7 May 2, 2026
0f16137
Update gridData/OpenVDB.py
spyke7 May 2, 2026
90eba9d
simplify Grid._export_vdb
orbeckst May 2, 2026
24dc68b
fixed typo
orbeckst May 2, 2026
717bb33
updated numpy to np
spyke7 May 7, 2026
ddd8c0e
Removed np.asarray(grid)
spyke7 May 7, 2026
91c58ed
updated test_vdb.py
spyke7 May 8, 2026
3472d4f
CHANGELOG updated
spyke7 May 10, 2026
1533e1e
Update gridData/tests/test_vdb.py
spyke7 May 11, 2026
0234ee4
Update CHANGELOG
spyke7 May 11, 2026
ec05ff6
Updated test and OpenVDB.py regarding tolerance test
spyke7 May 11, 2026
6b17ab9
updated zero tolerance test with value close to zero
spyke7 May 11, 2026
e256be4
Update core.py
orbeckst May 17, 2026
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
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ Contributors:
* Zhiyi Wu <xiki-tempula>
* Olivier Languin-Cattoën <ollyfutur>
* Andrés Montoya <conradolandia> (logo)
* Shreejan Dolai <spyke7>
Comment thread
spyke7 marked this conversation as resolved.
Outdated
13 changes: 13 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ The rules for this file:
* accompany each entry with github issue/PR number (Issue #xyz)

------------------------------------------------------------------------------
27/12/2025 IAlibay, spyke7, orbeckst
* 1.1.0

Changes

* Added `OpenVDB.py` inside `gridData` to simply export and write in .vdb format
* Added `test_vdb.py` inside `gridData\tests`
Comment thread
spyke7 marked this conversation as resolved.
Outdated

Fixes

* Adding openVDB formats (Issue #141)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

not a fix but an Enhancement – put it into the existing 1.1.0 section and add you name there.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In the CHANGELOG, this PR and issue are in the 1.1.0 release, so should I add my name in the 1.1.0 release or remove those lines and put them in the new section?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yes, now move it to the new section above since we released 1.1.0.



??/??/???? IAlibay, ollyfutur, conradolandia, orbeckst
* 1.1.0

Expand Down
190 changes: 190 additions & 0 deletions gridData/OpenVDB.py
Original file line number Diff line number Diff line change
@@ -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
Comment thread
spyke7 marked this conversation as resolved.
Outdated

.. Note:: This module implements a simple writer for 3D regular grids,
sufficient to export density data for visualization in Blender.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just make Blender a link again, eg to the relevant 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.
Comment thread
spyke7 marked this conversation as resolved.


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
Comment thread
orbeckst marked this conversation as resolved.
(File -> Import -> OpenVDB).


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

Comment thread
orbeckst marked this conversation as resolved.
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
Comment thread
spyke7 marked this conversation as resolved.

Example::

import OpenVDB
Comment thread
orbeckst marked this conversation as resolved.
Outdated
vdb_field = OpenVDB.field('density')
vdb_field.populate(grid, origin, delta)
vdb_field.write('output.vdb')


Classes and functions
---------------------

"""

import numpy
Comment thread
spyke7 marked this conversation as resolved.
Outdated
import warnings

try:
import pyopenvdb as vdb
except ImportError:
vdb = None
Comment thread
spyke7 marked this conversation as resolved.


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')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

will need updating

Or use directly from Grid::

g = Grid(...)
g.export('output.vdb', format='vdb')

"""

def __init__(self, name='density'):
"""Initialize an OpenVDB field.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is there a reason for having to manually populate the field? I currently don't see one so I think it's much better to just have one object that directly creates and represents a OpenVDB density.

Rewrite this code so that it takes as input the grid, origin, delta.

Rename the class OpenVDBField.

Make _populate(self) a private method that is just called at the end of __init__ — or just inline the code.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah indeed
this is better, will be updating it

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done, made the populate private, and renamed the class


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. "
)
self.name = name
self.grid = None
self.origin = None
self.delta = None

Comment thread
orbeckst marked this conversation as resolved.
def populate(self, grid, origin, delta):
Comment thread
spyke7 marked this conversation as resolved.
Outdated
"""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
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Also describe error handling for delta


"""
grid = numpy.asarray(grid)
if grid.ndim != 3:
raise ValueError(
"OpenVDB only supports 3D grids, got {}D".format(grid.ndim))
Comment thread
spyke7 marked this conversation as resolved.
Outdated

self.grid = grid.astype(numpy.float32) # OpenVDB uses float32
self.origin = numpy.asarray(origin)

# Handle delta: could be 1D array or diagonal matrix
delta = numpy.asarray(delta)
Comment thread
orbeckst marked this conversation as resolved.
Outdated
if delta.ndim == 2:
# Extract diagonal if it's a matrix
self.delta = numpy.array([delta[i, i] for i in range(3)])
Comment thread
spyke7 marked this conversation as resolved.
Outdated
else:
self.delta = delta
Comment thread
orbeckst marked this conversation as resolved.

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.")
Comment thread
spyke7 marked this conversation as resolved.
Outdated

# Create OpenVDB grid
vdb_grid = vdb.FloatGrid()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Similar to a comment above. OpenVDB supports different grid types and we should probably create one that corresponds to the grid data type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

openvdb.GridTypes - gives this - [<class 'openvdb.FloatGrid'>, <class 'openvdb.BoolGrid'>, <class 'openvdb.Vec3SGrid'>],

So for this I guess - FloatGrid, BoolGrid, and Vec3SGrid these three are by deafult.

openvdb docs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

From the same link above:

The Python module supports a fixed set of grid types. If the symbol PY_OPENVDB_WRAP_ALL_GRID_TYPES is defined at compile time, most of the grid types declared in openvdb.h are accessible in Python, otherwise only FloatGrid, BoolGrid and Vec3SGrid are accessible.

It looks like even the official module on conda-forge has only these fixed types:

>>> import openvdb                                                                                                               
>>> openvdb.LIBRARY_VERSION
(13, 0, 0)
>>> openvdb.GridTypes                                                                                                            
[<class 'openvdb.FloatGrid'>, <class 'openvdb.BoolGrid'>, <class 'openvdb.Vec3SGrid'>]                                           
>>> hasattr(openvdb, "Int32Grid") 
False

Blender packages its own version of openvdb and here is the output from Blender's Python Console:

>>> import openvdb
>>> openvdb.LIBRARY_VERSION
(12, 0, 0)
>>> openvdb.GridTypes
[<class 'openvdb.FloatGrid'>, <class 'openvdb.DoubleGrid'>, <class 'openvdb.BoolGrid'>, <class 'openvdb.Int32Grid'>, <class 'openvdb.Int64Grid'>, <class 'openvdb.Vec3SGrid'>, <class 'openvdb.Vec3IGrid'>, <class 'openvdb.Vec3DGrid'>, <class 'openvdb.PointDataGrid'>]
>>> hasattr(openvdb, "Int32Grid")
True

This is not ideal. MN has so far created the grids based on the corresponding data types (defaulting to float32 when there is no match) and this wasn't a problem because it runs within Blender. The hasattr checks are one way to check. There could be files with very different data types (the test nAChR_M2_water.plt file is float64 for example). I will defer to others on how best to deal with this. Thanks

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We'll have to work with what's available and this seems to be FloatGrid, BoolGrid (and Vec3SGrid, which we don't care about because all our densities are scalar).

Let's add a check that selects BoolGrid if the input array is a python (bool) or numpy bool numpy.bool and chooses FloatGrid for anything else. Add a note to the docs that limitations in OpenVDB can lead to loss of precision when input data is float64 (double) as the FloatGrid is float32 (single).

vdb_grid.name = self.name

# Set up transform (voxel size and position)
# Check for uniform spacing
if not numpy.allclose(self.delta, self.delta[0]):
warnings.warn(
"Non-uniform grid spacing {}. Using average spacing.".format(
self.delta))
voxel_size = float(numpy.mean(self.delta))
else:
voxel_size = float(self.delta[0])

# Create linear transform with uniform voxel size
transform = vdb.createLinearTransform(voxelSize=voxel_size)

# OpenVDB transform is at corner of voxel [0,0,0],
# but GridDataFormats origin is at center of voxel [0,0,0]
corner_origin = self.origin - 0.5 * self.delta
transform.translate(corner_origin)
vdb_grid.transform = transform

# Set background value for sparse storage
vdb_grid.background = 0.0
Comment thread
spyke7 marked this conversation as resolved.
Outdated

# Populate the grid

accessor = vdb_grid.getAccessor()
threshold = 1e-10
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Where does 1e-10 come from?

This could be a kwarg for __init__ and stored as self.threshold in case users might actually want to customize.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think that in OpenVDB, does not store zero unless asked to. So values<threshold are treated as background.
Basically, it is there so that it does not write all tiny voxels which are less than this. Or else, the size will get bigger


for i in range(self.grid.shape[0]):
for j in range(self.grid.shape[1]):
for k in range(self.grid.shape[2]):
value = float(self.grid[i, j, k])
if abs(value) > threshold:
accessor.setValueOn((i, j, k), value)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks really slow — iterating over a grid explicitly. For a start, you can find all cells above a threshold with numpy operations (np.abs(g) > threshold) and then ideally use it in a vectorized form to set the accessor.


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
21 changes: 21 additions & 0 deletions gridData/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from . import OpenDX
from . import gOpenMol
from . import mrc
from . import OpenVDB


def _grid(x):
Expand Down Expand Up @@ -203,6 +204,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,
}
self._loaders = {
'CCP4': self._load_mrc,
Expand Down Expand Up @@ -676,7 +678,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))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

use f-string

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Still uses format.


# 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 save(self, filename):
"""Save a grid object to `filename` and add ".pickle" extension.

Expand Down
Loading