Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convenience functions for Matrix, Vector and NormalizationParameters #161

Merged
merged 9 commits into from
Jan 4, 2021
Merged
Show file tree
Hide file tree
Changes from 6 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
15 changes: 11 additions & 4 deletions ompy/matrix.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations
import logging
import warnings
import copy
import numpy as np
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -218,6 +219,10 @@ def save(self, path: Union[str, Path], filetype: Optional[str] = None,
filetype = filetype_from_suffix(path)
filetype = filetype.lower()

if self.std is not None:
warnings.warn(UserWarning(
"The `std` attribute of Matrix class cannot be saved to file."))
vetlewi marked this conversation as resolved.
Show resolved Hide resolved

if filetype == 'numpy':
save_numpy_2D(self.values, self.Eg, self.Ex, path)
elif filetype == 'txt':
Expand Down Expand Up @@ -307,7 +312,7 @@ def plot(self, *, ax: Any = None,
ax.tick_params(axis='x', rotation=40)
ax.yaxis.set_major_locator(MeshLocator(self.Ex))
# ax.xaxis.set_major_locator(ticker.FixedLocator(self.Eg, nbins=10))
#fix_pcolormesh_ticks(ax, xvalues=self.Eg, yvalues=self.Ex)
# fix_pcolormesh_ticks(ax, xvalues=self.Eg, yvalues=self.Ex)

ax.set_title(title if title is not None else self.state)
ax.set_xlabel(r"$\gamma$-ray energy $E_{\gamma}$")
Expand Down Expand Up @@ -612,7 +617,8 @@ def line_mask(self, E1: Iterable[float],
def trapezoid(self, Ex_min: float, Ex_max: float,
Eg_min: float, Eg_max: Optional[float] = None,
inplace: bool = True) -> Optional[Matrix]:
"""Create a trapezoidal cut or mask delimited by the diagonal of the matrix
"""Create a trapezoidal cut or mask delimited by the diagonal of the
matrix

Args:
Ex_min: The bottom edge of the trapezoid
Expand Down Expand Up @@ -729,8 +735,8 @@ def diagonal_elements(self) -> Iterator[Tuple[int, int]]:
entries with `Eg > Ex + dE`.
Args:
mat: The matrix to iterate over
Iterator[Tuple[int, int]]: Indicies (i, j) over the last non-zero (=diagonal)
elements.
Iterator[Tuple[int, int]]: Indicies (i, j) over the last
non-zero(=diagonal) elements.
"""
return diagonal_elements(self.values)

Expand Down Expand Up @@ -863,6 +869,7 @@ def __matmul__(self, other: Matrix) -> Matrix:
result.values = [email protected]
return result


class MeshLocator(ticker.Locator):
def __init__(self, locs, nbins=10):
'place ticks on the i-th data points where (i-offset)%base==0'
Expand Down
6 changes: 6 additions & 0 deletions ompy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,12 @@ class NormalizationParameters(Model):
"""Storage for normalization parameters + some convenience functions
"""

#: Element number of the nucleus
Z: Optional[int] = field(default=None,
metadata="Element number of the nucleus") # noqa
#: Mass number of the nucleus
A: Optional[int] = field(default=None,
metadata="Mass number of the nucleus") # noqa
vetlewi marked this conversation as resolved.
Show resolved Hide resolved
#: Average s-wave resonance spacing D0 [eV]
D0: Optional[Tuple[float, float]] = field(default=None,
metadata='Average s-wave resonance spacing D0 [eV]') # noqa
Expand Down
3 changes: 3 additions & 0 deletions ompy/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ def __init__(self, values: Optional[Iterable[float]] = None,
self.load(path)
self.verify_integrity()

def __len__(self):
return len(self.values)

def verify_integrity(self, check_equidistant: bool = False):
""" Verify the internal consistency of the vector

Expand Down
18 changes: 17 additions & 1 deletion tests/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ def ones(shape: Tuple[int, int]) -> om.Matrix:
mat = np.tril(mat)
return om.Matrix(values=mat)


@pytest.fixture()
def Si28():
return om.example_raw('Si28')


@pytest.mark.parametrize(
"axis,Emin,Emax,shape",
[('Ex', None, None, (10, 10)),
Expand Down Expand Up @@ -78,7 +80,7 @@ def test_index(E, index):
assert mat.index_Ex(E) == index


@pytest.mark.filterwarnings('ignore:divide by zero encountered in true_divide:RuntimeWarning')
@pytest.mark.filterwarnings('ignore:divide by zero encountered in true_divide:RuntimeWarning') # noqa
def test_numericals():
E = np.array([0, 1, 2])
values1 = np.array([[0, 1, 2.], [-2, 1, 2.], [2, 3, -10.]])
Expand All @@ -98,6 +100,7 @@ def test_numericals():
assert_equal((matrix2@matrix1).values, values2@values1)
assert_equal((matrix1@matrix2).values, values1@values2)


@pytest.mark.parametrize(
"Ex,Eg",
[(np.linspace(0, 10., num=10), np.linspace(10, 20., num=15)),
Expand All @@ -120,6 +123,19 @@ def test_bin_shift(Ex, Eg):
assert_almost_equal(Ex, mat.Ex)
assert_almost_equal(Eg, mat.Eg)


@pytest.mark.parametrize(
"Ex,Eg",
[(np.linspace(0, 10., num=10), np.linspace(10, 20., num=15)),
([0, 1, 2, 3, 7, 10.], [0, 1, 2, 3, 80, 90.])
])
def test_save_warning(Ex, Eg):
values = np.ones((len(Ex), len(Eg)), dtype="float")
mat = om.Matrix(values=values, Ex=Ex, Eg=Eg, std=0.5*values)
with pytest.warns(UserWarning):
mat.save("/tmp/mat.npy")


# This does not work as of now...
# def test_mutable():
# E = np.array([0, 1, 2])
Expand Down
11 changes: 10 additions & 1 deletion tests/test_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ def test_init():
om.Vector(vals, [1, 2, 3, 4, 5])


def test_len():
N = 100
E = np.linspace(0, 1, N)
vals = np.linspace(2, 3.4, N)
vec = om.Vector(values=vals, E=E)
assert_equal(len(vec), N)


def test_save_load_no_std():
E = np.linspace(0, 1, 100)
vals = np.linspace(2, 3.4, 100)
Expand Down Expand Up @@ -184,7 +192,8 @@ def test_cut():
assert_equal(vector.E, Ecut)
assert_equal(vector.values, valcut)

@pytest.mark.filterwarnings('ignore:divide by zero encountered in true_divide:RuntimeWarning')

@pytest.mark.filterwarnings('ignore:divide by zero encountered in true_divide:RuntimeWarning') # noqa
def test_numericals():
E = np.array([0, 1, 2])
values1 = np.array([0, 1, -2.])
Expand Down