Skip to content

reorganise .cha file for minimum NeXus compliance (to enable visualisation) #147

@vedina

Description

@vedina
import h5py
import numpy as np

def write_cha2(x, y, metadata, dataset_name="raw", filename='nexus_compliant_spectrum_file.h5'):
    """
    Create a NeXus compliant HDF5 file from given x, y arrays and metadata.

    :param x: numpy array for the x-axis data (e.g., wavenumbers).
    :param y: numpy array for the y-axis data (e.g., counts).
    :param metadata: dictionary containing metadata information.
    :param dataset_name: dataset name, e.g. "raw" , "processed"
    :param filename: The name of the output NeXus file.
    """
    # Create a new NeXus compliant HDF5 file (write mode)
    with h5py.File(filename, 'w') as nexus_file:
        
        # Create the root NXentry group
        nxentry = nexus_file.create_group('entry')
        nxentry.attrs['NX_class'] = 'NXentry'
        
        # Add the raw data group
        nxdata_raw = nxentry.create_group(dataset_name)
        nxdata_raw.attrs['NX_class'] = 'NXdata'
        
        # Add x and y datasets
        nxdata_raw.create_dataset('x', data=x)
        nxdata_raw.create_dataset('y', data=y)
        nxdata_raw['x'].attrs['units'] = "cm-1"
        nxdata_raw['y'].attrs['units'] = "a.u."
        nxdata_raw.attrs['signal'] = 'y'
        nxdata_raw.attrs['axes'] = 'x'
        
        # Add metadata
        for key, value in metadata.items():
            nxentry.attrs[key] = value


# Example usage
x = np.linspace(0, 10, 100)  # Example x data 
y = np.sin(x)  # Example y data (e.g., counts)

# Metadata dictionary example
metadata = {
    'title': 'Sample Spectrum Data',
    ...
}

# Create the NeXus file
write_cha2(x, y, metadata, "raw")
write_cha2(x, y, metadata, "processed")

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions