Skip to content

Commit

Permalink
Merge pull request #10 from FAIRmat-NFDI/add_NVRS_schema
Browse files Browse the repository at this point in the history
Add nvrs and IR schema
  • Loading branch information
Pepe-Marquez authored May 29, 2024
2 parents 9498861 + eec72e5 commit ff3ad29
Show file tree
Hide file tree
Showing 6 changed files with 203 additions and 22 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ select = [
"UP",
# isort
"I",
# pylint
# pylint
"PL",
]

Expand Down
208 changes: 193 additions & 15 deletions src/nomad_unisyscat/schema_packages/mypackage.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import os
from typing import (
TYPE_CHECKING,
)

import numpy as np

if TYPE_CHECKING:
from nomad.datamodel.datamodel import (
EntryArchive,
)
from structlog.stdlib import (
BoundLogger,
)
pass

import plotly.express as px
from nomad.config import config
from nomad.datamodel.data import Schema
from nomad.datamodel.metainfo.annotations import ELNAnnotation, ELNComponentEnum
from nomad.metainfo import Quantity, SchemaPackage
from nomad.datamodel.metainfo.annotations import ELNAnnotation
from nomad.datamodel.metainfo.basesections import Measurement, MeasurementResult
from nomad.datamodel.metainfo.plot import PlotlyFigure, PlotSection
from nomad.metainfo import Quantity, SchemaPackage, Section

configuration = config.get_plugin_entry_point(
'nomad_unisyscat.schema_packages:mypackage'
Expand All @@ -22,17 +23,194 @@
m_package = SchemaPackage()


class MySchema(Schema):
name = Quantity(
type=str, a_eln=ELNAnnotation(component=ELNComponentEnum.StringEditQuantity)
class NRVSResult(MeasurementResult):
m_def = Section()

array_index = Quantity(
type=np.float64,
shape=['*'],
description=(
'A placeholder for the indices of vectorial quantities. '
'Used as x-axis for plots within quantities.'
),
a_display={'visible': False},
)
intensity = Quantity(
type=np.float64,
shape=['*'],
unit='dimensionless',
description='The 57Fe PVDOS count at each wavenumber value, dimensionless',
a_plot={'x': 'array_index', 'y': 'intensity'},
)
wavenumber = Quantity(
type=np.float64,
shape=['*'],
unit='1/cm',
description='The wavenumber range of the spectrum',
a_eln=ELNAnnotation(defaultDisplayUnit='1/cm'),
a_plot={'x': 'array_index', 'y': 'wavenumber'},
)


class NRVSpectroscopy(Measurement, PlotSection, Schema):
measurement_data_file = Quantity(
type=str,
description="""
experimental tab data file
""",
a_eln=ELNAnnotation(component='FileEditQuantity'),
a_browser=dict(adaptor='RawFileAdaptor'),
)
message = Quantity(type=str)

def normalize(self, archive: 'EntryArchive', logger: 'BoundLogger') -> None:
# simulation_data_file = Quantity(
# type=str,
# description="""
# simulated tab data file
# """,
# a_eln=dict(component='FileEditQuantity'),
# a_browser=dict(adaptor='RawFileAdaptor')
# )

method = Quantity(
type=str,
description="""
name of the method
""",
a_eln=ELNAnnotation(
component='StringEditQuantity',
default='nuclear resonance vibrational spectroscopy',
props=dict(
suggestions=[
'experimental nuclear resonance vibrational spectroscopy',
'simulated nuclear resonance vibrational spectroscopy',
]
),
),
)

results = Measurement.results.m_copy()
results.section_def = NRVSResult

def normalize(self, archive, logger):
super().normalize(archive, logger)
if self.measurement_data_file is None:
return

if (self.measurement_data_file is not None) and (
os.path.splitext(self.measurement_data_file)[-1] != '.dat'
):
raise ValueError('Unsupported file format. Only .dat file')

if self.measurement_data_file.endswith('.dat'):
with archive.m_context.raw_file(self.measurement_data_file) as f:
import pandas as pd

col_names = ['wavenumber, cm-1', '57Fe PVDOS']
data = pd.read_csv(f.name, header=None, names=col_names)
result = NRVSResult()
result.wavenumber = data['wavenumber, cm-1']
result.intensity = data['57Fe PVDOS']
results = []
results.append(result)
self.results = results

self.figures = []

fig = px.line(x=data['wavenumber, cm-1'], y=data['57Fe PVDOS'])
fig.update_xaxes(title_text=col_names[0])
fig.update_yaxes(title_text=col_names[1])
self.figures.append(PlotlyFigure(label='NRVS', figure=fig.to_plotly_json()))


class IRResult(MeasurementResult):
m_def = Section()

array_index = Quantity(
type=np.float64,
shape=['*'],
description=(
'A placeholder for the indices of vectorial quantities. '
'Used as x-axis for plots within quantities.'
),
a_display={'visible': False},
)
intensity = Quantity(
type=np.float64,
shape=['*'],
unit='dimensionless',
description='The absorbance at each wavenumber value, dimensionless',
a_plot={'x': 'array_index', 'y': 'intensity'},
)
wavenumber = Quantity(
type=np.float64,
shape=['*'],
unit='1/cm',
description='The wavenumber range of the spectrum',
a_eln=ELNAnnotation(defaultDisplayUnit='1/cm'),
a_plot={'x': 'array_index', 'y': 'wavenumber'},
)


class IRSpectroscopy(Measurement, PlotSection, Schema):
data_file = Quantity(
type=str,
description="""
csv data file ending .dat
""",
a_eln=ELNAnnotation(component='FileEditQuantity'),
a_browser=dict(adaptor='RawFileAdaptor'),
)

method = Quantity(
type=str,
description="""
name of the method
""",
a_eln=ELNAnnotation(
component='StringEditQuantity',
default='infra red vibrational spectroscopy',
props=dict(
suggestions=[
'experimental IR vibrational spectroscopy',
'simulated IR vibrational spectroscopy',
]
),
),
)

results = Measurement.results.m_copy()
results.section_def = IRResult

def normalize(self, archive, logger):
super().normalize(archive, logger)
if self.data_file is None:
return

if (self.data_file is not None) and (
os.path.splitext(self.data_file)[-1] != '.dat'
):
raise ValueError('Unsupported file format. Only .dat file')

if self.data_file.endswith('.dat'):
with archive.m_context.raw_file(self.data_file) as f:
import pandas as pd

col_names = ['wavenumber, cm-1', 'Absorbance']
data = pd.read_csv(f.name, header=None, names=col_names)

result = IRResult()
result.wavenumber = data['wavenumber, cm-1']
result.intensity = data['Absorbance']
results = []
results.append(result)
self.results = results

self.figures = []

logger.info('MySchema.normalize', parameter=configuration.parameter)
self.message = f'Hello {self.name}!'
fig = px.line(x=data['wavenumber, cm-1'], y=data['Absorbance'])
fig.update_xaxes(title_text=col_names[0])
fig.update_yaxes(title_text=col_names[1])
self.figures.append(PlotlyFigure(label='IR', figure=fig.to_plotly_json()))


m_package.__init_metainfo__()
3 changes: 3 additions & 0 deletions tests/data/ir_test.archive.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
data:
m_def: nomad_unisyscat.schema_packages.mypackage.IRSpectroscopy
data_file: ReRH_Nia-C_H_IR_exp.dat
3 changes: 3 additions & 0 deletions tests/data/nrvs_test.archive.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
data:
m_def: nomad_unisyscat.schema_packages.mypackage.NRVSpectroscopy
measurement_data_file: ReRH_Nia-C_H_NRVS_exp.dat
3 changes: 0 additions & 3 deletions tests/data/test.archive.yaml

This file was deleted.

6 changes: 3 additions & 3 deletions tests/schema_packages/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from nomad.client import normalize_all, parse


def test_schema():
test_file = os.path.join('tests', 'data', 'test.archive.yaml')
def test_ir_schema():
test_file = os.path.join('tests', 'data', 'ir_test.archive.yaml')
entry_archive = parse(test_file)[0]
normalize_all(entry_archive)

assert entry_archive.data.message == 'Hello Markus!'
assert entry_archive.data.results[0].wavenumber is not None

0 comments on commit ff3ad29

Please sign in to comment.