mass.calibration package

Submodules

mass.calibration.algorithms module

This file is intended to include algorithms that could be generally useful for calibration. Mostly they are pulled out of the former mass.calibration.young module.

class mass.calibration.algorithms.EnergyCalibrationAutocal(calibration, ph=None, line_names=None)[source]

Bases: object

property anyfailed
autocal(smoothing_res_ph=20, fit_range_ev=200.0, binsize_ev=1.0, nextra=2, nincrement=3, nextramax=8, maxacc=0.015)[source]
diagnose()[source]
fit_lines()[source]

All calibration emission lines are fitted with appropriate model. self.line_names will be sored by energy after this method is finished.

guess_fit_params(smoothing_res_ph=20, fit_range_ev=200.0, binsize_ev=1.0, nextra=2, nincrement=3, nextramax=8, maxacc=0.015)[source]

Calculate reasonable parameters for complex models or Gaussian models.

Args:
binsize_ev (float or list[float]): bin sizes of the histograms of given calibration lines.

If a single number is given, this same number will be used for all calibration lines.

class mass.calibration.algorithms.FailedFit(hist, bins)[source]

Bases: object

exception mass.calibration.algorithms.FailedToGetModelException[source]

Bases: Exception

mass.calibration.algorithms.build_fit_ranges(line_names, excluded_line_names, approx_ecal, fit_width_ev)[source]

Returns a list of (lo,hi) where lo and hi have units of energy of ranges to fit in for each energy in line_names.

Args:

line_names (list[str or float]): list or line names or energies excluded_line_names (list[str or float]): list of line_names or energies to

avoid when making fit ranges

approx_ecal: an EnergyCalibration object containing an approximate calibration fit_width_ev (float): full size in eV of fit ranges

mass.calibration.algorithms.build_fit_ranges_ph(line_names, excluded_line_names, approx_ecal, fit_width_ev)[source]

Call build_fit_ranges() to get (lo,hi) for fitranges in energy units, then convert to ph using approx_ecal

mass.calibration.algorithms.find_local_maxima(pulse_heights, gaussian_fwhm)[source]

Smears each pulse by a gaussian of gaussian_fhwm and finds local maxima, returns a list of their locations in pulse_height units (sorted by number of pulses in peak) AND their peak values as: (peak_locations, peak_intensities)

Args:

pulse_heights (np.array(dtype=float)): a list of pulse heights (eg p_filt_value) gaussian_fwhm = fwhm of a gaussian that each pulse is smeared with, in same units as pulse heights

mass.calibration.algorithms.find_opt_assignment(peak_positions, line_names, nextra=2, nincrement=3, nextramax=8, maxacc=0.015)[source]

Tries to find an assignment of peaks to line names that is reasonably self consistent and smooth

Args:
peak_positions (np.array(dtype=float)): a list of peak locations in arb units,

e.g. p_filt_value units

line_names (list[str or float)]): a list of calibration lines either as number (which is

energies in eV), or name to be looked up in STANDARD_FEATURES

nextra (int): the algorithm starts with the first len(line_names) + nextra peak_positions nincrement (int): each the algorithm fails to find a satisfactory peak assignment, it uses

nincrement more lines

nextramax (int): the algorithm stops incrementint nextra past this value, instead

failing with a ValueError saying “no peak assignment succeeded”

maxacc (float): an empirical number that determines if an assignment is good enough.

The default number works reasonably well for tupac data

mass.calibration.algorithms.get_model(lineNameOrEnergy, has_linear_background=True, has_tails=False)[source]
mass.calibration.algorithms.getmodel(lineNameOrEnergy, has_linear_background=True, has_tails=False)
mass.calibration.algorithms.line_names_and_energies(line_names)[source]

Given a list of line_names, return (names, energies) in eV.

Can also accept energies in eV directly and return (names, energies).

mass.calibration.algorithms.multifit(ph, line_names, fit_lo_hi, binsize_ev, slopes_de_dph, hide_deprecation=False)[source]
Args:

ph (np.array(dtype=float)): list of pulse heights line_names: names of calibration lines fit_lo_hi (list[list[float]]): a list of (lo,hi) with units of ph, used as

edges of histograms for fitting

binsize_ev (list[float]): list of binsizes in eV for calibration lines slopes_de_dph (list[float]): - list of slopes de_dph (e in eV) hide_deprecation: whether to suppress deprecation warnings

mass.calibration.algorithms.singlefit(ph, name, lo, hi, binsize_ph, approx_dP_dE)[source]

mass.calibration.energy_calibration module

Objects to assist with calibration from pulse heights to absolute energies.

Created on May 16, 2011

class mass.calibration.energy_calibration.EnergyCalibration(nonlinearity=1.1, curvetype='loglog', approximate=False, useGPR=True)[source]

Bases: object

Object to store information relevant to one detector’s absolute energy calibration and to offer conversions between pulse height and energy.

The behavior is governed by the constructor arguments loglog, approximate, and zerozero and by the number of data points. The construction-time arguments can be changed by calling EnergyCalibration.set_use_approximation() and EnergyCalibration.set_curvetype().

curvetype – Either a code number in the range [0,len(self.CURVETYPE)) or a

string from the tuple self.CURVETYPE.

approximate – Whether to construct a smoothing spline (minimal curvature

subject to a condition that chi-squared not be too large). If not, curve will be an exact spline in E vs PH, in log(E) vs log(PH), or as appropriate to the curvetype.

The forward conversion from PH to E uses the callable __call__ method or its synonym, the method ph2energy.

The inverse conversion method energy2ph calls Brent’s method of root-finding. It’s probably quite slow compared to a self.ph2energy for an array of equal length.

All of __call__, ph2energy, and energy2ph should return a scalar when given a scalar input, or a matching numpy array when given any sequence as an input.

CURVETYPE = ('loglog', 'linear', 'linear+0', 'gain', 'invgain', 'loggain')
add_cal_point(pht, energy, name='', pht_error=None, e_error=None, overwrite=True)[source]

Add a single energy calibration point <pht>, <energy>,

<pht> must be in units of the self.ph_field and <energy> is in eV. <pht_error> is the 1-sigma uncertainty on the pulse height. If None (the default), then assign pht_error = <pht>/1000. <e_error> is the 1-sigma uncertainty on the energy itself. If None (the default), then assign e_error=<energy>/10^5 (typically 0.05 eV).

Also, you can call it with <energy> as a string, provided it’s the name of a known feature appearing in the dictionary mass.energy_calibration.STANDARD_FEATURES. Thus the following are equivalent:

cal.add_cal_point(12345.6, 5898.801, “Mn Ka1”) cal.add_cal_point(12456.6, “Mn Ka1”)

Careful! If you give a name that’s already in the list, then this value replaces the previous one. If you do NOT give a name, though, then this will NOT replace but will add to any existing points at the same energy. You can prevent overwriting by setting <overwrite>=False.

property cal_point_energies
property cal_point_names
property cal_point_phs
copy()[source]

Return a deep copy.

curvename()[source]
drop_one_errors()[source]

For each calibration point, calculate the difference between the ‘correct’ energy and the energy predicted by creating a calibration without that point and using ph2energy to calculate the predicted energy, return energies, drop_one_energy_diff

e2dedph(energy)[source]
e2ph(energy)[source]
e2uncertainty(energy)[source]
energy2dedph(energy)[source]

Calculate the slope at energy.

energy2ph(energy)[source]

Convert energy (or array of energies) energy to pulse height in arbs.

Should return a scalar if passed a scalar, and a numpy array if passed a list or array Uses a spline with steps no greater than ~1% in pulse height space. For a Brent’s method root finding (i.e., an actual inversion of the ph->energy function), use method energy2ph_exact.

energy2ph_exact(energy)[source]

Convert energy (or array of energies) energy to pulse height in arbs.

Inverts the _ph2e function by Brent’s method for root finding. Can be fragile! Use method energy2ph for less precise but more generally error-free computation. Should return a scalar if passed a scalar, and a numpy array if passed a list or array.

energy2uncertainty(energies)[source]

Cal uncertainty in eV at the given pulse heights.

classmethod load_from_hdf5(hdf5_group, name)[source]
name2ph(name)[source]

Convert a named energy feature to pulse height. name need not be a calibration point.

ph2dedph(ph)[source]

Calculate the slope at pulse heights ph.

ph2energy(pulse_ht, der=0)[source]

Convert pulse height (or array of pulse heights) <pulse_ht> to energy (in eV). Should return a scalar if passed a scalar, and a numpy array if passed a list or array

Args:

pulse_ht (float or np.array(dtype=float)): pulse heights in an arbitrary unit. der (int): the order of derivative. der should be >= 0.

ph2uncertainty(ph)[source]

Cal uncertainty in eV at the given pulse heights.

plot(axis=None, color='blue', markercolor='red', plottype='linear', ph_rescale_power=0.0, removeslope=False, energy_x=False, showtext=True, showerrors=True, min_energy=None, max_energy=None)[source]
plotgain(**kwargs)[source]
plotinvgain(**kwargs)[source]
plotloggain(**kwargs)[source]
remove_cal_point_energy(energy, de)[source]

Remove cal points at energies with <de> of <energy>

remove_cal_point_name(name)[source]

If you don’t like calibration point named <name>, this removes it.

remove_cal_point_prefix(prefix)[source]

This removes all cal points whose name starts with <prefix>. Return number removed.

save_to_hdf5(hdf5_group, name)[source]
set_GPR(useit)[source]
set_curvetype(curvetype)[source]
set_nonlinearity(powerlaw=1.15)[source]

Update the power law index assumed when there’s 1 data point and a loglog curve type.

set_use_approximation(useit)[source]

Switch to using (or to NOT using) approximating splines with reduced knot count. You can interchange this with adding points, because the actual model computation isn’t done until the cal curve is called.

mass.calibration.energy_calibration.LineEnergies()[source]

A dictionary to know a lot of x-ray fluorescence line energies, based on Deslattes’ database.

It is built on facts from mass.calibration.nist_xray_database module.

It is a dictionary from peak name to energy, with several alternate names for the lines:

E = Energies() print E[“MnKAlpha”] print E[“MnKAlpha”], E[“MnKA”], E[“MnKA1”], E[“MnKL3”]

mass.calibration.fluorescence_lines module

fluorescence_lines.py

Tools for fitting and simulating X-ray fluorescence lines.

mass.calibration.fluorescence_lines.AlKAlphaFitter()
mass.calibration.fluorescence_lines.AlKAlpha_AlOFitter()
mass.calibration.fluorescence_lines.AlKAlpha_metal_v1992Fitter()
mass.calibration.fluorescence_lines.AuLAlphaFitter()
mass.calibration.fluorescence_lines.AuLBeta1Fitter()
mass.calibration.fluorescence_lines.BiLAlphaFitter()
mass.calibration.fluorescence_lines.BiLBeta1Fitter()
mass.calibration.fluorescence_lines.BrKAlphaFitter()
mass.calibration.fluorescence_lines.ClKAlphaFitter()
mass.calibration.fluorescence_lines.CoKAlphaFitter()
mass.calibration.fluorescence_lines.CoKBetaFitter()
mass.calibration.fluorescence_lines.CrKAlphaFitter()
mass.calibration.fluorescence_lines.CrKBetaFitter()
mass.calibration.fluorescence_lines.CuKAlphaFitter()
mass.calibration.fluorescence_lines.CuKBetaFitter()
mass.calibration.fluorescence_lines.DyKAlphaFitter()
mass.calibration.fluorescence_lines.DyKBetaFitter()
mass.calibration.fluorescence_lines.EuKAlphaFitter()
mass.calibration.fluorescence_lines.EuKBetaFitter()
mass.calibration.fluorescence_lines.FeKAlphaFitter()
mass.calibration.fluorescence_lines.FeKBetaFitter()
mass.calibration.fluorescence_lines.FeLAlphaFitter()
mass.calibration.fluorescence_lines.GdKAlphaFitter()
mass.calibration.fluorescence_lines.GdKBetaFitter()
mass.calibration.fluorescence_lines.HoKAlphaFitter()
mass.calibration.fluorescence_lines.HoKBetaFitter()
mass.calibration.fluorescence_lines.IrLAlphaFitter()
mass.calibration.fluorescence_lines.IrLBeta1Fitter()
mass.calibration.fluorescence_lines.KKAlphaFitter()
mass.calibration.fluorescence_lines.MgKAlphaFitter()
mass.calibration.fluorescence_lines.MgKAlpha_metal_v1Fitter()
mass.calibration.fluorescence_lines.MnKAlphaFitter()
mass.calibration.fluorescence_lines.MnKBetaFitter()
mass.calibration.fluorescence_lines.MoKAlphaFitter()
mass.calibration.fluorescence_lines.MoKBetaFitter()
mass.calibration.fluorescence_lines.NbKBeta24Fitter()
mass.calibration.fluorescence_lines.NbKBetaFitter()
mass.calibration.fluorescence_lines.NdKAlphaFitter()
mass.calibration.fluorescence_lines.NdKBetaFitter()
mass.calibration.fluorescence_lines.NiKAlphaFitter()
mass.calibration.fluorescence_lines.NiKBetaFitter()
mass.calibration.fluorescence_lines.PbLAlphaFitter()
mass.calibration.fluorescence_lines.PbLBeta1Fitter()
mass.calibration.fluorescence_lines.PrKAlphaFitter()
mass.calibration.fluorescence_lines.PrKBetaFitter()
mass.calibration.fluorescence_lines.PtLAlphaFitter()
mass.calibration.fluorescence_lines.PtLBeta1Fitter()
mass.calibration.fluorescence_lines.SKAlphaFitter()
mass.calibration.fluorescence_lines.ScKAlphaFitter()
mass.calibration.fluorescence_lines.ScKAlpha_metal_2006Fitter()
mass.calibration.fluorescence_lines.ScKBetaFitter()
mass.calibration.fluorescence_lines.SeKAlphaFitter()
mass.calibration.fluorescence_lines.SeKBetaFitter()
mass.calibration.fluorescence_lines.SiKAlphaFitter()
mass.calibration.fluorescence_lines.SmKAlphaFitter()
mass.calibration.fluorescence_lines.SmKBetaFitter()
class mass.calibration.fluorescence_lines.SpectralLine(element, material, linetype, energies, lorentzian_fwhm, intrinsic_sigma, reference_plot_instrument_gaussian_fwhm, reference_short, reference_amplitude, reference_amplitude_type, normalized_lorentzian_integral_intensity, nominal_peak_energy, fitter_type, position_uncertainty, reference_measurement_type, is_default_material)[source]

Bases: object

An abstract base class for modeling spectral lines as a sum of Voigt profiles (i.e., Gaussian-convolved Lorentzians).

Call addline to create a new subclass properly.

The API follows scipy.stats.stats.rv_continuous and is kind of like rv_frozen. Calling this object with an argument evalutes the pdf at the argument, it does not return an rv_frozen.

But so far we ony define rvs and pdf.

components(x, instrument_gaussian_fwhm)[source]

List of spectrum components as a function of <x>, the energy in eV

fitter()[source]
minimum_fwhm(instrument_gaussian_fwhm)[source]

for the narrowest lorentzian in the line model, calculate the combined fwhm including the lorentzian, intrinstic_sigma, and instrument_gaussian_fwhm

model(has_linear_background=True, has_tails=False, prefix='', qemodel=None)[source]

Generate a LineModel instance from a SpectralLine

pdf(x, instrument_gaussian_fwhm)[source]

Spectrum (units of fraction per eV) as a function of <x>, the energy in eV

property peak_energy
plot(x=None, instrument_gaussian_fwhm=0, axis=None, components=True, label=None, setylim=True)[source]

Plot the spectrum. x - np array of energy in eV to plot at (sensible default) axis - axis to plot on (default creates new figure) components - True plots each voigt component in addition to the spectrum label - a string to label the plot with (optional)

plot_like_reference(axis=None)[source]
classmethod quick_monochromatic_line(name, energy, lorentzian_fwhm, intrinsic_sigma)[source]

Create a quick monochromatic line. Intended for use in calibration when we know a line energy, but not a lineshape model. Returns and instrance of SpectralLine with most fields having contents like “unknown: quick_line”. The line will have a single lorentzian element with the given energy, fwhm, and intrinsic_sigma values.

property reference
rvs(size, instrument_gaussian_fwhm, rng=None)[source]

The CDF and PPF (cumulative distribution and percentile point functions) are hard to compute. But it’s easy enough to generate the random variates themselves, so we override that method.

property shortname
mass.calibration.fluorescence_lines.TbKAlphaFitter()
mass.calibration.fluorescence_lines.TbKBetaFitter()
mass.calibration.fluorescence_lines.TiKAlphaFitter()
mass.calibration.fluorescence_lines.TiKBetaFitter()
mass.calibration.fluorescence_lines.VKAlphaFitter()
mass.calibration.fluorescence_lines.VKBetaFitter()
mass.calibration.fluorescence_lines.WLAlphaFitter()
mass.calibration.fluorescence_lines.WLBeta1Fitter()
mass.calibration.fluorescence_lines.WLBeta2Fitter()
mass.calibration.fluorescence_lines.YKAlphaFitter()
mass.calibration.fluorescence_lines.YKBetaFitter()
mass.calibration.fluorescence_lines.ZnKAlphaFitter()
mass.calibration.fluorescence_lines.ZnKBetaFitter()
mass.calibration.fluorescence_lines.ZrKAlphaFitter()
mass.calibration.fluorescence_lines.ZrKBetaFitter()
mass.calibration.fluorescence_lines.addline(element, linetype, material, reference_short, reference_plot_instrument_gaussian_fwhm, nominal_peak_energy, energies, lorentzian_fwhm, reference_amplitude, reference_amplitude_type, ka12_energy_diff=None, fitter_type=None, position_uncertainty=nan, intrinsic_sigma=0, reference_measurement_type=None, is_default_material=True, allow_replacement=False)[source]
mass.calibration.fluorescence_lines.make_line_fitter(line)[source]

Generate a LineFitter instance from a SpectralLine (deprecated)

mass.calibration.fluorescence_lines.plot_all_spectra(maxplots=10)[source]

Makes plots showing the line shape and component parts for some lines. Intended to replicate plots in the literature giving spectral lineshapes.

mass.calibration.nist_xray_database module

nist_xray_database

Download the NIST x-ray line database from the website, and parse the downloaded data into useable form.

For loading a file (locally, from disk) and plotting some information: * NISTXrayDBFile * plot_line_uncertainties

For updating the data files: * NISTXrayDBRetrieve * GetAllLines

Basic usage (assuming you put the x-ray files in ${MASS_HOME}/mass/calibration/nist_xray_data.dat):

J. Fowler, NIST February 2014

class mass.calibration.nist_xray_database.NISTXrayDBFile(*filenames)[source]

Bases: object

DEFAULT_FILENAMES = ('nist_xray_data.dat', 'low_z_xray_data.dat')
LINE_NICKNAMES = {'KA1': 'KL3', 'KA2': 'KL2', 'KB1': 'KM3', 'KB3': 'KM2', 'KB5': 'KM5', 'LA1': 'L3M5', 'LA2': 'L3M4', 'LB1': 'L2M4', 'LB2': 'L3N5', 'LB3': 'L1M3', 'LG1': 'L2N4', 'Ll': 'L3M1'}
get_lines_by_type(linetype)[source]

Return a tuple containing all lines of a certain type, e.g., “KL3”. See self.LINE_NICKNAMES for some known line “nicknames”.

class mass.calibration.nist_xray_database.NISTXrayLine(textline, column_defs=None)[source]

Bases: object

DEFAULT_COLUMN_DEFS = {'blend': (74, 79), 'element': (1, 4), 'peak': (45, 59), 'peak_unc': (61, 72), 'ref': (81, 91), 'transition': (10, 16)}
mass.calibration.nist_xray_database.plot_line_energies()[source]
mass.calibration.nist_xray_database.plot_line_uncertainties()[source]

Module contents

mass.calibration - Collection of tools related to energy calibration.