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
7 changes: 5 additions & 2 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ The rules for this file:
-------------------------------------------------------------------------------
??/??/???? orbeckst

* 1.1.1
* 1.2.0

Fixes
Fixes

* Ensure that when Grid() or Grid.load() load a datafile with the
wrong format a ValueError is raised consistently. (PR #165)


01/22/2026 IAlibay, ollyfutur, conradolandia, orbeckst, PlethoraChutney,
Expand Down
25 changes: 24 additions & 1 deletion gridData/OpenDX.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,10 +561,33 @@ def read(self, stream):
dx = OpenDX.field.read(dxfile)

The classid is discarded and replaced with the one from the file.

Parameters
----------
stream : str or stream
read from the file in OpenDX format or open file-like object

Raises
------
ValueError
if the data could not be parsed correctly


.. versionchanged:: 1.2.0
Ensure that ValueError is raised (instead of
:exc:`UnicodeDecodeError` or :exc:`RecursionError`)

"""
DXfield = self
p = DXParser(stream)
p.parse(DXfield)
try:
p.parse(DXfield)
except (UnicodeDecodeError, RecursionError) as err:
# parser got confused, likely not a valid file
# (RecursionError was only observed on Windows)
raise ValueError("DX file could not be read. "
"The original error was\n"
f" {err.__class__.__name__}: {err}")

def add(self,component,DXobj):
"""add a component to the field"""
Expand Down
23 changes: 23 additions & 0 deletions gridData/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,29 @@ def load(self, filename, file_format=None, assume_volumetric=False):

The :meth:`load` method calls the class's constructor method and
completely resets all values, based on the loaded data.

Parameters
----------
filename : str
Name of the file.

file_format : str or None, optional
Set the file format (e.g., "DX" or "MRC"). If ``None`` then
try to guess the format.

assume_volumetric : bool, optional
Optional keyword argument that is only taken into account by
the :class:`gridData.mrc.MRC` file parser.

Raises
------
ValueError
The underlying file parser raises an :exc:`ValueError` if it fails
to parse the file.


.. versionchanged:: 1.2.0
Ensure that underlying parsers consistently raise ValueError.
"""
filename = str(filename)
if not os.path.exists(filename):
Expand Down
17 changes: 11 additions & 6 deletions gridData/gOpenMol.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,12 +209,17 @@ def read(self, filename):
from struct import calcsize, unpack
if not filename is None:
self.filename = str(filename)
with open(self.filename, 'rb') as plt:
h = self.header = self._read_header(plt)
nentries = h['nx'] * h['ny'] * h['nz']
# quick and dirty... slurp it all in one go
datafmt = h['bsaflag']+str(nentries)+self._data_bintype
a = numpy.array(unpack(datafmt, plt.read(calcsize(datafmt))))
try:
with open(self.filename, 'rb') as plt:
h = self.header = self._read_header(plt)
nentries = h['nx'] * h['ny'] * h['nz']
# quick and dirty... slurp it all in one go
datafmt = h['bsaflag'] + str(nentries) + self._data_bintype
a = numpy.array(unpack(datafmt, plt.read(calcsize(datafmt))))
except Exception as err:
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.

Do we want this to be more specific with the exceptions it catches?

raise ValueError(f"gOpenMol PLT file {filename} could not be read. "
"The original error was\n"
f" {err.__class__.__name__}: {err}")
self.header['filename'] = self.filename
self.array = a.reshape(h['nz'], h['ny'], h['nx']).transpose() # unpack plt in reverse!!
self.delta = self._delta()
Expand Down
9 changes: 3 additions & 6 deletions gridData/tests/test_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,15 +176,12 @@ def test_init_pickle_pathobjects(self, data, tmpdir):

@pytest.mark.parametrize("fileformat", ("pkl", "PKL", "pickle", "python"))
def test_load_fileformat(self, data, pklfile, fileformat):
h = Grid(pklfile, file_format="pkl")
h = Grid(pklfile, file_format=fileformat)
assert h == data['grid']

# At the moment, reading the file with the wrong parser does not give
# good error messages.
@pytest.mark.xfail
@pytest.mark.parametrize("fileformat", ("ccp4", "plt", "dx"))
def test_load_wrong_fileformat(self, data, pklfile, fileformat):
with pytest.raises('ValueError'):
def test_load_wrong_fileformat_raises_ValueError(self, pklfile, fileformat):
with pytest.raises(ValueError):
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.

maybe add a match= to be more specific?

Grid(pklfile, file_format=fileformat)

# just check that we can export without stupid failures; detailed
Expand Down
Loading