Skip to content

Commit

Permalink
Merge pull request #194 from h2020charisma/bugfix_and_tests
Browse files Browse the repository at this point in the history
Bugfix and tests
  • Loading branch information
georgievgeorgi authored Nov 19, 2024
2 parents bfd5d28 + 008d40a commit bcb351e
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/ramanchada2/spectrum/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ def __init__(self,
metadata: Union[SpeMetadataModel, None] = None,
applied_processings: Union[SpeProcessingListModel, None] = None):
super(Plottable, self).__init__()
self._xdata = None
self._ydata = None
if x is not None:
if isinstance(x, int):
self.x = np.arange(x) * 1.
Expand All @@ -51,14 +53,15 @@ def __init__(self,
self._cachefile = cachefile
self._metadata = deepcopy(metadata or SpeMetadataModel(root={}))
self._applied_processings = deepcopy(applied_processings or SpeProcessingListModel(root=[]))
if self.x is not None and self.y is not None:
if len(self.x) != len(self.y):
raise ValueError(f'x and y shold have same dimentions len(x)={len(self.x)} len(y)={len(self.y)}')
if self._xdata is not None and self._ydata is not None:
if len(self._xdata) != len(self._ydata):
raise ValueError(
f'x and y shold have same dimentions len(x)={len(self._xdata)} len(y)={len(self._ydata)}')

def __copy__(self):
return Spectrum(
x=self.x,
y=self.y,
x=self._xdata,
y=self._ydata,
cachefile=self._cachefile,
metadata=self._metadata,
applied_processings=self._applied_processings,
Expand Down Expand Up @@ -125,7 +128,10 @@ def _sort_x(self):
self.y = self.y[idx]

@property
def x(self): return np.array(self._xdata)
def x(self):
if self._xdata is None:
raise ValueError('x of the spectrum is not set. self._xdata is None')
return np.array(self._xdata)

@x.setter
def x(self, val: npt.NDArray[np.float64]):
Expand All @@ -142,6 +148,8 @@ def x_bin_boundaries(self):

@property
def y(self) -> npt.NDArray[np.float64]:
if self._ydata is None:
raise ValueError('y of the spectrum is not set. self._ydata is None')
return np.array(self._ydata)

@y.setter
Expand Down Expand Up @@ -190,6 +198,8 @@ def x_err(self):

@x_err.setter
def x_err(self, val: Union[npt.NDArray, None]):
if self._xdata is None:
raise ValueError('x of the spectrum is not set. self._xdata is None')
if val is not None:
if val.shape != self._xdata.shape:
raise ValueError(
Expand All @@ -205,6 +215,8 @@ def y_err(self):

@y_err.setter
def y_err(self, val: Union[npt.NDArray, None]):
if self._ydata is None:
raise ValueError('y of the spectrum is not set. self._ydata is None')
if val is not None:
if val.shape != self._ydata.shape:
raise ValueError(
Expand Down
28 changes: 28 additions & 0 deletions tests/end_to_end/test_generate_and_fit.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import numpy as np
import pandas as pd

import ramanchada2 as rc2
from ramanchada2 import spectrum


Expand All @@ -20,3 +22,29 @@ def test_generate_and_fit():
assert len(true_pos) == len(calc_pos), 'wrong number of peaks found'
assert np.max(np.abs(true_pos - fit_pos - shift)) < 3, 'fit locations far from truth'
assert np.max(np.abs(true_pos - calc_pos - shift)) < 5, 'find_peaks locations far from truth'


def test_gaussian_fit_parameters():
x = np.linspace(-100, 3500, 2500)
params = [
dict(center=400, sigma=6, amplitude=500),
dict(center=430, sigma=3, amplitude=300),
dict(center=600, sigma=10, amplitude=500),
dict(center=625, sigma=5, amplitude=300),
dict(center=700, sigma=10, amplitude=500),
dict(center=780, sigma=5, amplitude=300),
]
spe = rc2.spectrum.from_theoretical_lines(shapes=['gaussian']*len(params),
params=params, x=x)
spe = spe.add_gaussian_noise_drift(sigma=.5, coef=.2, rng_seed=1111)
spe = spe.subtract_moving_minimum(100)
params_df = pd.DataFrame.from_records(params)

cand = spe.find_peak_multipeak(prominence=spe.y_noise_MAD()*10, width=3, wlen=100)
fitres = spe.fit_peak_multimodel(profile='Gaussian', candidates=cand, vary_baseline=True)
df = fitres.to_dataframe_peaks()

assert np.all(np.isclose(df['amplitude'], params_df['amplitude'], atol=df['amplitude_stderr']*5))
assert np.all(np.isclose(df['center'], params_df['center'], atol=df['center_stderr']*5))
assert np.all(np.isclose(df['sigma'], params_df['sigma'], atol=df['sigma_stderr']*5))
assert np.all(np.isclose(df['sigma']*np.sqrt(8*np.log(2)), df['fwhm']))
24 changes: 24 additions & 0 deletions tests/spectrum/creators/test_spectrum_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import numpy as np
import pytest

import ramanchada2 as rc2


def test_spectrum_init():
with pytest.raises(ValueError):
spe = rc2.spectrum.Spectrum(x=np.arange(100), y=np.arange(101))
with pytest.raises(ValueError):
spe = rc2.spectrum.Spectrum(x=np.arange(100), y=np.arange(99))
spe = rc2.spectrum.Spectrum(x=np.arange(100, dtype=int), y=np.random.uniform(size=100))
assert spe.x.dtype == float
assert spe.y.dtype == float
spec = spe.__copy__()
assert np.all(spe.x == spec.x)
assert np.all(spe.y == spec.y)
assert spe._xdata is spec._xdata
assert spe._ydata is spec._ydata

spe = rc2.spectrum.Spectrum(x=np.arange(100, dtype=int))
assert spe._ydata is None
with pytest.raises(ValueError):
spe.y

0 comments on commit bcb351e

Please sign in to comment.