Matrix

class ompy.Matrix(values=None, Eg=None, Ex=None, std=None, path=None, shape=None, state=None)[source]

Bases: ompy.AbstractArray

Stores 2d array with energy axes (a matrix).

Stores matrices along with calibration and energy axis arrays. Performs several integrity checks to verify that the arrays makes sense in relation to each other.

Note that since a matrix is numbered NxM where N is rows going in the y-direction and M is columns going in the x-direction, the “x-dimension” of the matrix has the same shape as the Ex array (Excitation axis)

          Diagonal Ex=Eγ
                         v
a y E │██████▓▓██████▓▓▓█░   ░
x   x │██ █████▓████████░   ░░
i a   │█████████████▓▓░░░░░
s x i │███▓████▓████░░░░░ ░░░░
  i n │███████████░░░░   ░░░░░
1 s d │███▓█████░░   ░░░░ ░░░░ <-- "Folded" counts
    e │███████▓░░░░░░░░░░░░░░░
    x │█████░     ░░░░ ░░  ░░
      │███░░░░░░░░ ░░░░░░  ░░░
    N │█▓░░  ░░░  ░░░░░  ░░░░░
      └───────────────────────
            Eγ, index M
            x axis
            axis 0 of plot
            axis 1 of matrix
Variables
  • values – 2D matrix storing the counting data

  • Eg – The gamma energy along the x-axis (mid-bin calibration)

  • Ex – The excitation energy along the y-axis (mid-bin calibration)

  • std – Array of standard deviations

  • path – Load a Matrix from a given path

  • state – An enum to keep track of what has been done to the matrix

Todo

  • Find a way to handle units

  • Synchronize cuts. When a cut is made along one axis, such as values[min:max, :] = 0, make cuts to the other relevant variables

  • Make values, Ex and Eg to properties so that the integrity of the matrix can be ensured.

There is the option to initialize it in an empty state. In that case, all class variables will be None. It can be filled later using the load() method.

For initializing one can give values, [Ex, Eg] arrays, a filename for loading a saved matrix or a shape for initialzing it with zero entries.

Parameters
  • values (Optional[ndarray]) – Set the matrix’ values.

  • Eg (Optional[ndarray]) – The gamma ray energies using midbinning.

  • Ex (Optional[ndarray]) – The excitation energies using midbinning.

  • std (Optional[ndarray]) – The standard deviations at each bin of values

  • path (Union[str, Path, None]) – Load a Matrix from a given path

  • shape (Optional[Tuple[int, int]]) – Tuple (len(Ex), len(Ex)) to create a matrix with 0 counts.

  • state (Union[str, MatrixState, None]) – An enum to keep track of what has been done to the matrix. Can also be a str. like in [“raw”, “unfolded”, …]

Attributes Summary

counts

rtype

float

range_Eg

Returns all indices of Eg

range_Ex

Returns all indices of Ex

shape

rtype

Union[Tuple[int], Tuple[int, int]]

state

rtype

MatrixState

Methods Summary

ascii_plot([shape])

Plots a rebinned ascii version of the matrix

calibration()

Calculates the calibration coefficients of the energy axes

copy()

Return a copy of the matrix

cut(axis[, Emin, Emax, inplace, …])

Cuts the matrix to the sub-interval limits along given axis.

cut_diagonal([E1, E2, inplace])

Cut away counts to the right of a diagonal line defined by indices

cut_like(other[, inplace])

Cut a matrix like another matrix (according to energy arrays)

diagonal_elements()

Iterates over the last non-zero elements ..

fill_and_remove_negative(window_size)

Combination of ompy.Matrix.fill_negative() and ompy.Matrix.remove_negative()

fill_negative(window_size)

Wrapper for ompy.fill_negative()

has_equal_binning(other, **kwargs)

Check whether other has equal binning as self within precision.

index_Eg(E)

Returns the closest index corresponding to the Eg value

index_Ex(E)

Returns the closest index corresponding to the Ex value

indices_Eg(E)

Returns the closest indices corresponding to the Eg value

indices_Ex(E)

Returns the closest indices corresponding to the Ex value

iter()

rtype

Iterator[Tuple[int, int]]

line_mask(E1, E2)

Create a mask for above (True) and below (False) a line

load(path[, filetype])

Load matrix from specified format

plot(*[, ax, title, scale, vmin, vmax, …])

Plots the matrix with the energy along the axis

plot_projection(axis[, Emin, Emax, ax, …])

Plots the projection of the matrix along axis

projection(axis[, Emin, Emax, normalize])

Returns the projection along the specified axis

rebin(axis[, edges, factor, inplace])

Rebins one axis of the matrix

remove_negative()

Entries with negative values are set to 0

save(path[, filetype])

Save matrix to file

to_lower_bin()

Transform Eg and Ex from mid bin (=default) to lower bin.

to_mid_bin()

Transform Eg and Ex from lower bin to mid bin (=default).

trapezoid(Ex_min, Ex_max, Eg_min[, Eg_max, …])

Create a trapezoidal cut or mask delimited by the diagonal of the matrix

verify_integrity()

Runs checks to verify internal structure

Attributes Documentation

counts
Return type

float

range_Eg

Returns all indices of Eg

Return type

ndarray

range_Ex

Returns all indices of Ex

Return type

ndarray

shape
Return type

Union[Tuple[int], Tuple[int, int]]

state
Return type

MatrixState

Methods Documentation

ascii_plot(shape=(5, 5))[source]

Plots a rebinned ascii version of the matrix

Parameters

shape (tuple, optional) – Shape of the rebinned matrix

calibration()[source]

Calculates the calibration coefficients of the energy axes

Return type

Dict[str, ndarray]

Returns

The calibration coefficients in a dictionary.

copy()[source]

Return a copy of the matrix

Return type

Matrix

cut(axis, Emin=None, Emax=None, inplace=True, Emin_inclusive=True, Emax_inclusive=True)[source]

Cuts the matrix to the sub-interval limits along given axis.

Parameters
  • axis (Union[int, str]) – Which axis to apply the cut to. Can be 0, “Eg” or 1, “Ex”.

  • Emin (Optional[float]) – Lowest energy to be included. Defaults to lowest energy. Inclusive.

  • Emax (Optional[float]) – Higest energy to be included. Defaults to highest energy. Inclusive.

  • inplace (bool) – If True make the cut in place. Otherwise return a new matrix. Defaults to True

  • Emin_inclusive (bool) – whether the bin containing the lower bin should be included (True) or excluded (False). Defaults to True.

  • Emax_inclusive (bool) – whether the bin containing the higest bin should be included (True) or excluded (False). Defaults to True.

Return type

Optional[Matrix]

Returns

None if inplace == False cut_matrix (Matrix): The cut version of the matrix

cut_diagonal(E1=None, E2=None, inplace=True)[source]

Cut away counts to the right of a diagonal line defined by indices

Parameters
  • E1 (Optional[Iterable[float]]) – First point of intercept, ordered as (Eg, Ex)

  • E2 (Optional[Iterable[float]]) – Second point of intercept

  • inplace (bool) – Whether the operation should be applied to the current matrix, or to a copy which is then returned.

Return type

Optional[Matrix]

Returns

The matrix with counts above diagonal removed (if inplace is False).

cut_like(other, inplace=True)[source]

Cut a matrix like another matrix (according to energy arrays)

Parameters
  • other (Matrix) – The other matrix

  • inplace (bool, optional) – If True make the cut in place. Otherwise return a new matrix. Defaults to True

Returns

If inplace is False, returns the cut matrix

Return type

Optional[Matrix]

diagonal_elements()[source]

Iterates over the last non-zero elements .. note:

Assumes that the matrix is diagonal, i.e. that there are no
entries with `Eg > Ex + dE`.
Parameters
  • mat – The matrix to iterate over

  • int]] (Iterator[Tuple[int,) – Indicies (i, j) over the last non-zero (=diagonal)

  • elements.

Return type

Iterator[Tuple[int, int]]

fill_and_remove_negative(window_size)[source]

Combination of ompy.Matrix.fill_negative() and ompy.Matrix.remove_negative()

fill_negative(window_size)[source]

Wrapper for ompy.fill_negative()

has_equal_binning(other, **kwargs)[source]

Check whether other has equal binning as self within precision. :param other: Matrix to compare to. :type other: Matrix :param kwargs: Additional kwargs to np.allclose.

Returns

Returns True if both arrays are equal .

Return type

bool (bool)

Raises
  • TypeError – If other is not a Matrix

  • ValueError – If any of the bins in any of the arrays are not equal.

index_Eg(E)[source]

Returns the closest index corresponding to the Eg value

Return type

int

index_Ex(E)[source]

Returns the closest index corresponding to the Ex value

Return type

int

indices_Eg(E)[source]

Returns the closest indices corresponding to the Eg value

Return type

ndarray

indices_Ex(E)[source]

Returns the closest indices corresponding to the Ex value

Return type

ndarray

iter()[source]
Return type

Iterator[Tuple[int, int]]

line_mask(E1, E2)[source]

Create a mask for above (True) and below (False) a line

Parameters
Return type

ndarray

Returns

The boolean array with counts below the line set to False

Todo

  • Write as a property with memonized output for unchanged matrix

Note

This method and Jørgen’s original method give 2 pixels difference Probably because of how the interpolated line is drawn

load(path, filetype=None)[source]

Load matrix from specified format

Parameters
  • path (str or Path) – path to file to load

  • filetype (str, optional) – Filetype to load. Has an auto-recognition.

Raises

ValueError – If filetype is unknown

Return type

None

plot(*, ax=None, title=None, scale=None, vmin=None, vmax=None, midbin_ticks=False, add_cbar=True, **kwargs)[source]

Plots the matrix with the energy along the axis

Parameters
  • ax (Optional[Any]) – A matplotlib axis to plot onto

  • title (Optional[str]) – Defaults to the current matrix state

  • scale (Optional[str]) – Scale along the z-axis. Can be either “log” or “linear”. Defaults to logarithmic if number of counts > 1000

  • vmin (Optional[float]) – Minimum value for coloring in scaling

  • Maximum value for coloring in scaling (vmax) –

  • add_cbar (bool) – Whether to add a colorbar. Defaults to True.

  • kwargs – Additional kwargs to plot command.

Return type

Any

Returns

The ax used for plotting

Raises

ValueError – If scale is unsupported

plot_projection(axis, Emin=None, Emax=None, *, ax=None, normalize=False, scale='linear', **kwargs)[source]

Plots the projection of the matrix along axis

Parameters
  • axis (Union[int, str]) – The axis to project onto. Can be either of (0, ‘Eg’, ‘x’), (1, ‘Ex’, ‘y’)

  • Emin (Optional[float]) – The minimum energy to be summed over.

  • Emax (Optional[float]) – The maximum energy to be summed over.

  • ax (Optional[Any]) – The axes object to plot onto.

  • normalize (bool) – If True, normalize the counts to 1. Defaults to False.

  • scale (optional, str) – y-scale, i.e log or linear. Defaults to “linear”.

  • kwargs – Additional kwargs to plot command.

Raises

ValueError – If axis is not in [0, 1]

Return type

Any

Returns

The ax used for plotting

projection(axis, Emin=None, Emax=None, normalize=False)[source]

Returns the projection along the specified axis

Parameters
  • axis (Union[int, str]) – The axis to project onto. Can be 0 or 1.

  • Emin (optional) – The minimum energy to be summed over.

  • Emax (optional) – The maximum energy to be summed over.

  • normalize (bool) – If True, normalize the counts to 1. Defaults to False.

Raises

ValueError – If axis is not in [0, 1]

Return type

Tuple[ndarray, ndarray]

Returns

The projection and the energies summed onto

rebin(axis, edges=None, factor=None, inplace=True)[source]

Rebins one axis of the matrix

Parameters
  • axis (Union[int, str]) – the axis to rebin.

  • edges (Optional[Sequence[float]]) – The new edges along the axis. Can not be given alongside ‘factor’.

  • factor (Optional[float]) – The factor by which the step size shall be changed. Can not be given alongside ‘edges’.

  • inplace (bool) – Whether to change the axis and values inplace or return the rebinned matrix.

Return type

Optional[Matrix]

Returns

The rebinned Matrix if inplace is ‘False’.

Raises

ValueError if the axis is not a valid axis.

remove_negative()[source]

Entries with negative values are set to 0

save(path, filetype=None)[source]

Save matrix to file

Parameters
  • path (str or Path) – path to file to save

  • filetype (str, optional) – Filetype to save. Has an auto-recognition. Options: [“numpy”, “tar”, “mama”]

Raises

ValueError – If filetype is unknown

to_lower_bin()[source]

Transform Eg and Ex from mid bin (=default) to lower bin.

to_mid_bin()[source]

Transform Eg and Ex from lower bin to mid bin (=default).

trapezoid(Ex_min, Ex_max, Eg_min, Eg_max=None, inplace=True)[source]

Create a trapezoidal cut or mask delimited by the diagonal of the matrix

Parameters
  • Ex_min (float) – The bottom edge of the trapezoid

  • Ex_max (float) – The top edge of the trapezoid

  • Eg_min (float) – The left edge of the trapezoid

  • Eg_max (Optional[float]) – The right edge of the trapezoid used for defining the diagonal. If not set, the diagonal will be found by using the last nonzeros of each row.

Return type

Optional[Matrix]

Returns

Cut matrix if ‘inplace’ is True

Todo

-possibility to have inclusive or exclusive cut

verify_integrity()[source]

Runs checks to verify internal structure

Raises

ValueError – If any check fails

ascii_plot(shape=(5, 5))[source]

Plots a rebinned ascii version of the matrix

Parameters

shape (tuple, optional) – Shape of the rebinned matrix

calibration()[source]

Calculates the calibration coefficients of the energy axes

Return type

Dict[str, ndarray]

Returns

The calibration coefficients in a dictionary.

copy()[source]

Return a copy of the matrix

Return type

Matrix

cut(axis, Emin=None, Emax=None, inplace=True, Emin_inclusive=True, Emax_inclusive=True)[source]

Cuts the matrix to the sub-interval limits along given axis.

Parameters
  • axis (Union[int, str]) – Which axis to apply the cut to. Can be 0, “Eg” or 1, “Ex”.

  • Emin (Optional[float]) – Lowest energy to be included. Defaults to lowest energy. Inclusive.

  • Emax (Optional[float]) – Higest energy to be included. Defaults to highest energy. Inclusive.

  • inplace (bool) – If True make the cut in place. Otherwise return a new matrix. Defaults to True

  • Emin_inclusive (bool) – whether the bin containing the lower bin should be included (True) or excluded (False). Defaults to True.

  • Emax_inclusive (bool) – whether the bin containing the higest bin should be included (True) or excluded (False). Defaults to True.

Return type

Optional[Matrix]

Returns

None if inplace == False cut_matrix (Matrix): The cut version of the matrix

cut_diagonal(E1=None, E2=None, inplace=True)[source]

Cut away counts to the right of a diagonal line defined by indices

Parameters
  • E1 (Optional[Iterable[float]]) – First point of intercept, ordered as (Eg, Ex)

  • E2 (Optional[Iterable[float]]) – Second point of intercept

  • inplace (bool) – Whether the operation should be applied to the current matrix, or to a copy which is then returned.

Return type

Optional[Matrix]

Returns

The matrix with counts above diagonal removed (if inplace is False).

cut_like(other, inplace=True)[source]

Cut a matrix like another matrix (according to energy arrays)

Parameters
  • other (Matrix) – The other matrix

  • inplace (bool, optional) – If True make the cut in place. Otherwise return a new matrix. Defaults to True

Returns

If inplace is False, returns the cut matrix

Return type

Optional[Matrix]

diagonal_elements()[source]

Iterates over the last non-zero elements .. note:

Assumes that the matrix is diagonal, i.e. that there are no
entries with `Eg > Ex + dE`.
Parameters
  • mat – The matrix to iterate over

  • int]] (Iterator[Tuple[int,) – Indicies (i, j) over the last non-zero (=diagonal)

  • elements.

Return type

Iterator[Tuple[int, int]]

fill_and_remove_negative(window_size)[source]

Combination of ompy.Matrix.fill_negative() and ompy.Matrix.remove_negative()

fill_negative(window_size)[source]

Wrapper for ompy.fill_negative()

has_equal_binning(other, **kwargs)[source]

Check whether other has equal binning as self within precision. :param other: Matrix to compare to. :type other: Matrix :param kwargs: Additional kwargs to np.allclose.

Returns

Returns True if both arrays are equal .

Return type

bool (bool)

Raises
  • TypeError – If other is not a Matrix

  • ValueError – If any of the bins in any of the arrays are not equal.

index_Eg(E)[source]

Returns the closest index corresponding to the Eg value

Return type

int

index_Ex(E)[source]

Returns the closest index corresponding to the Ex value

Return type

int

indices_Eg(E)[source]

Returns the closest indices corresponding to the Eg value

Return type

ndarray

indices_Ex(E)[source]

Returns the closest indices corresponding to the Ex value

Return type

ndarray

line_mask(E1, E2)[source]

Create a mask for above (True) and below (False) a line

Parameters
Return type

ndarray

Returns

The boolean array with counts below the line set to False

Todo

  • Write as a property with memonized output for unchanged matrix

Note

This method and Jørgen’s original method give 2 pixels difference Probably because of how the interpolated line is drawn

load(path, filetype=None)[source]

Load matrix from specified format

Parameters
  • path (str or Path) – path to file to load

  • filetype (str, optional) – Filetype to load. Has an auto-recognition.

Raises

ValueError – If filetype is unknown

Return type

None

plot(*, ax=None, title=None, scale=None, vmin=None, vmax=None, midbin_ticks=False, add_cbar=True, **kwargs)[source]

Plots the matrix with the energy along the axis

Parameters
  • ax (Optional[Any]) – A matplotlib axis to plot onto

  • title (Optional[str]) – Defaults to the current matrix state

  • scale (Optional[str]) – Scale along the z-axis. Can be either “log” or “linear”. Defaults to logarithmic if number of counts > 1000

  • vmin (Optional[float]) – Minimum value for coloring in scaling

  • Maximum value for coloring in scaling (vmax) –

  • add_cbar (bool) – Whether to add a colorbar. Defaults to True.

  • kwargs – Additional kwargs to plot command.

Return type

Any

Returns

The ax used for plotting

Raises

ValueError – If scale is unsupported

plot_projection(axis, Emin=None, Emax=None, *, ax=None, normalize=False, scale='linear', **kwargs)[source]

Plots the projection of the matrix along axis

Parameters
  • axis (Union[int, str]) – The axis to project onto. Can be either of (0, ‘Eg’, ‘x’), (1, ‘Ex’, ‘y’)

  • Emin (Optional[float]) – The minimum energy to be summed over.

  • Emax (Optional[float]) – The maximum energy to be summed over.

  • ax (Optional[Any]) – The axes object to plot onto.

  • normalize (bool) – If True, normalize the counts to 1. Defaults to False.

  • scale (optional, str) – y-scale, i.e log or linear. Defaults to “linear”.

  • kwargs – Additional kwargs to plot command.

Raises

ValueError – If axis is not in [0, 1]

Return type

Any

Returns

The ax used for plotting

projection(axis, Emin=None, Emax=None, normalize=False)[source]

Returns the projection along the specified axis

Parameters
  • axis (Union[int, str]) – The axis to project onto. Can be 0 or 1.

  • Emin (optional) – The minimum energy to be summed over.

  • Emax (optional) – The maximum energy to be summed over.

  • normalize (bool) – If True, normalize the counts to 1. Defaults to False.

Raises

ValueError – If axis is not in [0, 1]

Return type

Tuple[ndarray, ndarray]

Returns

The projection and the energies summed onto

property range_Eg

Returns all indices of Eg

Return type

ndarray

property range_Ex

Returns all indices of Ex

Return type

ndarray

rebin(axis, edges=None, factor=None, inplace=True)[source]

Rebins one axis of the matrix

Parameters
  • axis (Union[int, str]) – the axis to rebin.

  • edges (Optional[Sequence[float]]) – The new edges along the axis. Can not be given alongside ‘factor’.

  • factor (Optional[float]) – The factor by which the step size shall be changed. Can not be given alongside ‘edges’.

  • inplace (bool) – Whether to change the axis and values inplace or return the rebinned matrix.

Return type

Optional[Matrix]

Returns

The rebinned Matrix if inplace is ‘False’.

Raises

ValueError if the axis is not a valid axis.

remove_negative()[source]

Entries with negative values are set to 0

save(path, filetype=None)[source]

Save matrix to file

Parameters
  • path (str or Path) – path to file to save

  • filetype (str, optional) – Filetype to save. Has an auto-recognition. Options: [“numpy”, “tar”, “mama”]

Raises

ValueError – If filetype is unknown

to_lower_bin()[source]

Transform Eg and Ex from mid bin (=default) to lower bin.

to_mid_bin()[source]

Transform Eg and Ex from lower bin to mid bin (=default).

trapezoid(Ex_min, Ex_max, Eg_min, Eg_max=None, inplace=True)[source]

Create a trapezoidal cut or mask delimited by the diagonal of the matrix

Parameters
  • Ex_min (float) – The bottom edge of the trapezoid

  • Ex_max (float) – The top edge of the trapezoid

  • Eg_min (float) – The left edge of the trapezoid

  • Eg_max (Optional[float]) – The right edge of the trapezoid used for defining the diagonal. If not set, the diagonal will be found by using the last nonzeros of each row.

Return type

Optional[Matrix]

Returns

Cut matrix if ‘inplace’ is True

Todo

-possibility to have inclusive or exclusive cut

verify_integrity()[source]

Runs checks to verify internal structure

Raises

ValueError – If any check fails