Vector

class ompy.Vector(values=None, E=None, path=None, std=None, units='keV', **kwargs)[source]

Bases: AbstractArray

Stores 1d array with energy axes (a vector)

Variables:
  • values (np.ndarray) – The values at each bin.

  • E (np.ndarray) – The energy of each bin. (mid-bin calibration)

  • path (str or Path) – The path to load a saved vector from

  • std (np.ndarray) – The standard deviation of the counts

  • unit (str) – Unit of the energies. Can be “keV” or “MeV”. Defaults to “keV”.

There are several ways to initialize

  • An initialization with only E, or energy, defaults to zero values.

  • An initialization using a path loads a vector from said path.

If no std is given, it will default to None

Parameters:
Raises:

ValueError if the given arrays are of differing lenghts.

Todo

  • Crean up initialization.

Attributes Summary

shape

Methods Summary

calibration()

Calculate and return the calibration coefficients of the energy axes

closest(E_new[, side, inplace])

Re-bin the vector without merging bins.

copy()

Return a deepcopy of the class

cumulative([factor, inplace])

Cumulative sum of the vector.

cut([Emin, Emax, inplace])

Cut the vector at the energy limits

cut_nan([inplace])

Cut the vector where elements are np.nan

error(other[, std])

Computes the (weighted) χ²

has_equal_binning(other, **kwargs)

Check whether other has equal_binning as self within precision.

index(E)

Returns the closest index corresponding to the E value

load(path[, filetype])

Load to a file of specified format

plot([ax, scale, kind])

Plots the vector

rebin([mids, factor, inplace])

Rebins vector, assuming equidistant binning

save(path[, filetype, units])

Save to a file of specified format

to_MeV()

Convert E from keV to MeV if necessary

to_keV()

Convert E from MeV to keV if necessary

transform([const, alpha, inplace])

Apply a normalization transformation.

verify_equdistant(axis)

Runs checks to verify if energy arrays are equidistant

verify_integrity([check_equidistant])

Verify the internal consistency of the vector

Attributes Documentation

shape

Methods Documentation

calibration()[source]

Calculate and return the calibration coefficients of the energy axes

Formatted as “a{axis}{power of E}”

Return type:

Dict[str, float]

closest(E_new, side='right', inplace=False)[source]

Re-bin the vector without merging bins.

The resulting vector will have E_new as the x-axis while the jth y-value will be given by the ith value of the original y-values where E[i] < E_new[j] <= E[i+1] or E[i] <= E_new[j] < E[i+1].

Parameters:
  • E_new (ndarray) – Bin value to find. Value or array.

  • side (Optional[str]) – ‘left’: E[i] < E[j] <= E[i+1], ‘right’: E[i] <= E[j] <= E[i+1]

  • inplace – Whether to make the change inplace or not.

Return type:

Optional[Vector]

Returns:

Vector with the new E axis and the bin content of the bins that contains E.

Raises:
  • RuntimeError if the x-axis of the original vector is

  • not sorted.

copy()

Return a deepcopy of the class

Return type:

AbstractArray

cumulative(factor=None, inplace=False)[source]

Cumulative sum of the vector.

Parameters:
  • factor (Union[float, str, None]) – A factor to multiply to the resulting vector. Possible

  • None (values are) –

  • E[0]. (factor will be calculated by E[1] -) –

  • inplace – Whether to make the change inplace or not.

Return type:

Optional[Vector]

Returns:

The cumulative sum vector if inplace is ‘False’

Raises:
  • RuntimeError if elements in self.E are not equidistant

  • and factor='de'.

  • ValueError if factor is a string other than 'de'.

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

Cut the vector at the energy limits

Parameters:
  • Emin (float, optional) – The lower energy limit

  • Emax (float, optional) – The higher energy limit

  • inplace (bool, optional) – If True perform the cut on this vector or if False returns a copy. Defaults to True

Return type:

Optional[Vector]

Returns:

The cut vector if inplace is True.

cut_nan(inplace=True)[source]

Cut the vector where elements are np.nan

Parameters:

inplace (bool, optional) – If True perform the cut on this vector or if False returns a copy. Defaults to True

Return type:

Vector

Returns:

The cut vector if inplace is True.

error(other, std=None)[source]

Computes the (weighted) χ²

Parameters:
  • other (Vector or ndarray]) – The reference to compare itself to. If an array, assumes it has the same energy binning as itself.

  • std (Optional[ndarray], optional) – Standard deviations to use as inverse of the weights.

Returns:

χ²

Return type:

float

has_equal_binning(other, **kwargs)[source]

Check whether other has equal_binning as self within precision.

Parameters:
  • other (Vector) – Vector to compare to.

  • kwargs – Additional kwargs to np.allclose.

Return type:

bool

Returns:

Returns True if both arrays are equal .

Raises:
  • TypeError – If other is not a Vector.

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

index(E)[source]

Returns the closest index corresponding to the E value

Return type:

int

load(path, filetype=None, **kwargs)[source]

Load to a file of specified format

Parameters:
  • path (str or Path) – Path to Load

  • filetype (str, optional) – Filetype. Default uses auto-recognition from suffix.

Raises:

ValueError – Filetype is not supported

Return type:

None

plot(ax=None, scale='linear', kind='line', **kwargs)[source]

Plots the vector

Parameters:
  • ax (matplotlib axis, optional) – The axis to plot onto. If not provided, a new figure is created

  • scale (str, optional) – The scale to use. Can be linear (default), log, symlog or logit.

  • kind (str, optional) –

    • ‘line’ : line plot (default) evokes ax.plot

    • ’plot’ : same as ‘line’

    • ’step’ : step plot

    • ’bar’ : vertical bar plot

  • kwargs (optional) – Additional kwargs to plot command.

Return type:

Tuple[Any, Any]

Returns:

The figure and axis used.

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

Rebins vector, assuming equidistant binning

Parameters:
  • mids (Optional[Sequence[float]]) – The new energy mids. Can not be given alongside ‘factor’.

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

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

Return type:

Optional[Vector]

Returns:

The rebinned vector if inplace is ‘False’.

save(path, filetype=None, units='keV', **kwargs)[source]

Save to a file of specified format

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

  • filetype (str, optional) – Filetype. Default uses auto-recognition from suffix. Options: [“numpy”, “txt”, “tar”, “mama”, “csv”]

  • units (str, optional) – Units for the x-axis. Default uses keV. Options: [“keV”, “MeV”, “same”]. “same” option will use the current selected units of the vector. Note: This keyword is ignored when saving to “mama” type.

  • **kwargs – additional keyword arguments

Raises:
Return type:

None

to_MeV()[source]

Convert E from keV to MeV if necessary

Return type:

Vector

to_keV()[source]

Convert E from MeV to keV if necessary

Return type:

Vector

transform(const=1, alpha=0, inplace=True)[source]

Apply a normalization transformation:

vector -> const * vector * exp(alpha*energy)

If the vector has std, the std will be transformed as well.

Parameters:
  • const (float, optional) – The constant. Defaults to 1.

  • alpha (float, optional) – The exponential coefficient. Defaults to 0.

  • inplace (bool, optional) – Whether to apply the transformation inplace. If False, returns the transformed vector.

Return type:

Optional[Vector]

Returns:

Optional[Vector]

verify_equdistant(axis)

Runs checks to verify if energy arrays are equidistant

axis: The axis to project onto.

Can be either of (0, ‘Eg’, ‘x’), (1, ‘Ex’, ‘y’)

Raises:

ValueError – If any check fails

verify_integrity(check_equidistant=False)[source]

Verify the internal consistency of the vector

Parameters:

check_equidistant (bool, optional) – Check whether energy array are equidistant spaced. Defaults to False.

Raises:

AssertionError or ValueError if any test fails