Skip to content

Commit

Permalink
Fixes docs/api for rebin, fixes #114; add for Vec
Browse files Browse the repository at this point in the history
also added rebinning for Vector
  • Loading branch information
fzeiser committed Mar 27, 2020
1 parent e12d8b1 commit a2e5f10
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 28 deletions.
45 changes: 18 additions & 27 deletions ompy/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,17 +683,17 @@ def trapezoid(self, Ex_min: float, Ex_max: float,
return matrix

def rebin(self, axis: Union[int, str],
edges: Optional[Sequence[float]] = None,
mids: Optional[Sequence[float]] = None,
factor: Optional[float] = None,
inplace: bool = True) -> Optional[Matrix]:
""" Rebins one axis of the matrix
Args:
axis: the axis to rebin.
edges: The new edges along the axis. Can not be
mids: The new mids along the axis. Can not be
given alongside 'factor'.
factor: The factor by which the step size shall be
changed. Can not be given alongside 'edges'.
changed. Can not be given alongside 'mids'.
inplace: Whether to change the axis and values
inplace or return the rebinned matrix.
Returns:
Expand All @@ -705,46 +705,37 @@ def rebin(self, axis: Union[int, str],
axis: int = to_plot_axis(axis)
if axis not in (0, 1):
raise ValueError("Axis must be 0 or 1")
if not (edges is None) ^ (factor is None):
raise ValueError("Either 'edges' or 'factor' must be"
if not (mids is None) ^ (factor is None):
raise ValueError("Either 'mids' or 'factor' must be"
" specified, but not both.")
edges_old = self.Ex if axis else self.Eg
mids_old = self.Ex if axis else self.Eg

if factor is not None:
if factor <= 0:
raise ValueError("'factor' must be positive")
num_edges = int(len(edges_old)/factor)
old_step = edges_old[1] - edges_old[0]
step = factor*old_step
edge = edges_old[0]
edges = []
while len(edges) < num_edges:
edges.append(edge)
edge += step
LOG.debug("Rebinning with factor %g, giving %g edges",
factor, num_edges)
num_mids = int(len(mids_old)/factor)
mids, step = np.linspace(mids_old[0], mids_old[-1],
num=num_mids, retstep=True)
LOG.debug("Rebinning with factor %g, giving %g mids",
factor, num_mids)
LOG.debug("Old step size: %g\nNew step size: %g",
old_step, step)
edges = np.asarray(edges, dtype=float)
mids_old[1] - mids_old[0], step)
mids = np.asarray(mids, dtype=float)

naxis = (axis + 1) % 2
rebinned = rebin_2D(self.values, edges_old, edges, naxis)
rebinned = rebin_2D(self.values, mids_old, mids, naxis)
if inplace:
self.values = rebinned
if axis:
self.Ex = edges
self.Ex = mids
else:
self.Eg = edges
self.Eg = mids
self.verify_integrity()
else:
if naxis:
return Matrix(Eg=edges, Ex=self.Ex, values=rebinned)
return Matrix(Eg=mids, Ex=self.Ex, values=rebinned)
else:
return Matrix(Eg=self.Eg, Ex=edges, values=rebinned)

def copy(self) -> Matrix:
""" Return a copy of the matrix """
return copy.deepcopy(self)
return Matrix(Eg=self.Eg, Ex=mids, values=rebinned)

def diagonal_elements(self) -> Iterator[Tuple[int, int]]:
""" Iterates over the last non-zero elements
Expand Down
47 changes: 46 additions & 1 deletion ompy/vector.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations
from typing import Optional, Iterable, Union, Any, Tuple, Dict
from typing import Optional, Iterable, Union, Any, Tuple, Dict, Sequence
import logging
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -11,8 +12,12 @@
load_tar, save_tar)
from .decomposition import index
from .library import div0
from .rebin import rebin_1D
from .abstractarray import AbstractArray

LOG = logging.getLogger(__name__)
logging.captureWarnings(True)


class Vector(AbstractArray):
""" Stores 1d array with energy axes (a vector)
Expand Down Expand Up @@ -335,6 +340,46 @@ def cut_nan(self, inplace: bool = True) -> Vector:
else:
return Vector(values=values, E=E, units=self.units)

def rebin(self, mids: Optional[Sequence[float]] = None,
factor: Optional[float] = None,
inplace: bool = True) -> Optional[Vector]:
""" Rebins vector
Args:
mids: The new energy mids. Can not be
given alongside 'factor'.
factor: The factor by which the step size shall be
changed. Can not be given alongside 'mids'.
inplace: Whether to change E and values
inplace or return the rebinned vector.
Returns:
The rebinned vector if inplace is 'False'.
"""
if not (mids is None) ^ (factor is None):
raise ValueError("Either 'mids' or 'factor' must be"
" specified, but not both.")
mids_old = self.E

if factor is not None:
if factor <= 0:
raise ValueError("'factor' must be positive")
num_mids = int(len(mids_old)/factor)
mids, step = np.linspace(mids_old[0], mids_old[-1],
num=num_mids, retstep=True)
LOG.debug("Rebinning with factor %g, giving %g mids",
factor, num_mids)
LOG.debug("Old step size: %g\nNew step size: %g",
mids_old[1] - mids_old[0], step)
mids = np.asarray(mids, dtype=float)

rebinned = rebin_1D(self.values, mids_old, mids)
if inplace:
self.values = rebinned
self.E = mids
self.verify_integrity()
else:
return Vector(E=mids, values=rebinned)

def to_MeV(self) -> Vector:
""" Convert E from keV to MeV if necessary """
if self.units == "MeV":
Expand Down

0 comments on commit a2e5f10

Please sign in to comment.