Skip to content

Commit 1ca4310

Browse files
committed
add: saxswaxs.NexusResultsWriter
1 parent 19ffa45 commit 1ca4310

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

CHAP/saxswaxs/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@
99
from CHAP.saxswaxs.writer import (
1010
ZarrSetupWriter,
1111
ZarrResultsWriter,
12+
NexusResultsWriter,
1213
)

CHAP/saxswaxs/writer.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,66 @@ def zarr_writer(self, zarrfile, path, idx, data):
118118
f'Data written to "{path}" at slice {idx}.')
119119

120120

121+
class NexusResultsWriter(Writer):
122+
def write(self, data, filename):
123+
from nexusformat.nexus import NXFile
124+
125+
# Open file in append mode to allow modifications
126+
#nxroot = nxload(filename)
127+
128+
# Get list of PyfaiIntegrationProcessor results to write
129+
data = self.unwrap_pipelinedata(data)[0]
130+
for d in data:
131+
with NXFile(filename, 'a') as nxroot:
132+
self.nxs_writer(nxroot=nxroot, **d)
133+
134+
return data
135+
136+
def nxs_writer(self, nxroot, path, idx, data):
137+
"""Write data to a specific Zarr dataset.
138+
139+
This method writes `data` to a specified dataset within a Zarr
140+
file at the given index (`idx`). If the dataset does not
141+
exist, an error is raised. The method ensures that the shape
142+
of `data` matches the shape of the target slice before
143+
writing.
144+
145+
:param zarrfile: Zarr file root object
146+
:type zarrfile: zarr.core.group.Group
147+
:param path: Path to the dataset inside the Zarr file.
148+
:type path: str
149+
:param idx: Index or slice where the data should be written.
150+
:type idx: tuple or int
151+
:param data: Data to be written to the specified slice in the
152+
dataset.
153+
:type data: numpy.ndarray or compatible array-like object
154+
:return: The written data.
155+
:rtype: numpy.ndarray or compatible array-like object
156+
:raises ValueError: If the specified dataset does not exist or
157+
if the shape of `data` does not match the target slice.
158+
"""
159+
self.logger.info(f'Writing to {path} at {idx}')
160+
161+
# Check if the dataset exists
162+
if path not in nxroot:
163+
raise ValueError(
164+
f'Dataset "{path}" does not exist in the Zarr file.')
165+
166+
# Access the specified dataset
167+
dataset = nxroot[path]
168+
169+
# Check that the slice shape matches the data shape
170+
if dataset[idx].shape != data.shape:
171+
raise ValueError(
172+
f'Data shape {data.shape} does not match the target slice '
173+
+ f'shape {dataset[idx].shape}.')
174+
175+
# Write the data to the specified slice
176+
dataset[idx] = data
177+
self.logger.info(
178+
f'Data written to "{path}" at slice {idx}.')
179+
180+
121181
if __name__ == '__main__':
122182
# Local modules
123183
from CHAP.writer import main

0 commit comments

Comments
 (0)