def test_rebin_vector_non_equidistant(before, after): before = om.Vector(values=[10, 20, 30], E=[10., 20, 30]) after = om.Vector(values=[10-2*2.5, 2.5+5, 20-2*5, 30], E=[10., 15, 20, 30]) rebinned = before.rebin(mids=after.E, inplace=False) assert_equal(rebinned.E, after.E) assert_allclose(rebinned.values, after.values)
def test_rebin_vector(): before = om.Vector(values=[10, 20, 30], E=[10., 20, 30]) after = om.Vector(values=vals_rebinned, E=[10., 15, 20, 25]) rebinned = before.rebin(mids=after.E, inplace=False) assert_equal(rebinned.E, after.E) assert_allclose(rebinned.values, after.values)
def plot_compare(response, R, Rmama, raw_base_folder): """ Plots and compares the first N interpolations to raw/simulated spectra """ fig, axmat = plt.subplots(3, 3) fig_diff, axmat_diff = plt.subplots(3, 3) fig.suptitle("compare response functions") fig_diff.suptitle("(interp.-raw)/raw in %") Eresp = response.resp['Eg'] for i, E in enumerate(Eresp): if i == len(axmat.flatten()): break ax = axmat.flatten()[i] axdiff = axmat_diff.flatten()[i] E_ = R.Ex[R.index_Ex(E)] values, Eg = R.projection(axis="Eg", Emin=E_, Emax=E_) ompy = om.Vector(values, Eg) E_ = Rmama.Ex[Rmama.index_Ex(E)] values, Eg = Rmama.projection(axis="Eg", Emin=E_, Emax=E_) mama = om.Vector(values, Eg) ompy.plot(ax=ax, linestyle="--", label=f"ompy {E_:.0f}") mama.plot(ax=ax, linestyle=":", label=f"mama {E_:.0f}") try: raw = om.Vector(path=raw_base_folder + f"/raw{E:.0f}") raw.values = om.rebin_1D(raw.values, raw.E, response.Eout) raw.values /= raw.values.sum() raw.E = response.Eout raw.plot(ax=ax, label="raw", linestyle="-", alpha=0.5) ompy_diff = ((ompy - raw) / raw) * 100 mama_diff = ((mama - raw) / raw) * 100 ompy_diff.plot(ax=axdiff, linestyle="--", label=f"ompy {E_:.0f}") mama_diff.plot(ax=axdiff, linestyle=":", label=f"mama {E_:.0f}") except: print("didn't find raw") pass ax.legend() ax.set_yscale("log") ax.set_xlim(0, E + 2 * response.f_fwhm_abs(E)) ax.set_ylim(1e-3, None) axdiff.axhline(0, color="r", alpha=0.3) axdiff.legend() axdiff.set_xlim(0, E + 2 * response.f_fwhm_abs(E)) axdiff.set_ylim(-30, 30) return fig, fig_diff, axmat, axmat_diff
def test_save_load_csv_with_kwargs(): E = np.linspace(0, 1, 100) vals = np.linspace(2, 3.4, 100) std = np.random.randn(100) * 0.1 vec = om.Vector(values=vals, E=E, std=std) vec.save('/tmp/test_csv.csv', sep="\t") vec_from_file = om.Vector(path='/tmp/test_csv.csv', sep='\t') assert_allclose(vec_from_file.E, vec.E) assert_allclose(vec_from_file.values, vec.values) assert_allclose(vec_from_file.std, vec.std)
def test_save_load_no_std(): E = np.linspace(0, 1, 100) vals = np.linspace(2, 3.4, 100) vec = om.Vector(values=vals, E=E) formats = ['.npy', '.txt', '.tar', '.m', '.csv'] for form in formats: print(form) vec.save('/tmp/no_std' + form) vec_from_file = om.Vector(path='/tmp/no_std' + form) assert_allclose(vec_from_file.E, E) assert_allclose(vec_from_file.values, vals)
def test_save_units(): E = np.arange(0, 5010, 10) vals = np.random.random(len(E)) vec = om.Vector(values=vals, E=E) vec.save("/tmp/units.txt", units='MeV') vec_from_file = om.Vector(path="/tmp/units.txt", units='MeV') assert_allclose(vec_from_file.E, E / 1000.) assert_allclose(vec_from_file.values, vals) vec_from_file.to_keV() assert_allclose(vec_from_file.E, vec.E)
def test_save_load(): E = np.linspace(0, 1, 100) vals = np.linspace(2, 3.4, 100) std = np.random.randn(100) * 0.1 vec = om.Vector(values=vals, E=E, std=std) formats = ['.npy', '.txt', '.tar', '.csv'] for form in formats: vec.save('/tmp/std' + form) vec_from_file = om.Vector(path='/tmp/std' + form) assert_allclose(vec_from_file.E, vec.E) assert_allclose(vec_from_file.values, vec.values) assert_allclose(vec_from_file.std, vec.std)
def test_closest(): E = np.array([0., 1., 2., 3., 4.]) values = np.array([10., 9., 8., 7., 6.]) std = 0.1 * values E_new = np.array([0.5, 1.5, 3.]) values_new = np.array([10., 9., 7.]) std_new = 0.1 * values_new vector = om.Vector(values=values, E=E) vector_res = vector.closest(E_new) assert_equal(vector_res.E, E_new) assert_equal(vector_res.values, values_new) vector = om.Vector(values=values, E=E, std=std) vector_res = vector.closest(E_new) assert_equal(vector_res.E, E_new) assert_equal(vector_res.values, values_new) assert_equal(vector_res.std, std_new) # Make sure the change is inplace. assert vector.closest(E_new, inplace=True) is None assert_equal(vector.E, E_new) assert_equal(vector.values, values_new) assert_equal(vector.std, std_new) # Make sure that x-values outside the # range gives zero E_new = [-1.5, 1.5, 3.5] vector_res = vector.closest(E_new) assert vector_res.values[0] == 0 assert vector_res.std[0] == 0 E_new = np.array([0.5, 1.5, 3., 6.]) vector_res = vector.closest(E_new) assert vector_res.values[-1] == 0 assert vector_res.std[-1] == 0 # Make sure that RuntimeError is raised E = np.array([0., 1., 2., 4., 3.]) values = np.array([10., 9., 8., 7., 6.]) std = 0.1 * values vector = om.Vector(values=values, E=E, std=std) with pytest.raises(RuntimeError): vector_res = vector.closest(E_new)
def test_init(): E = np.linspace(0, 1, 100) vals = np.linspace(2, 3.4, 100) vec = om.Vector(values=vals, E=E) assert_equal(E, vec.E) assert_equal(vals, vec.values) # Provide values only with pytest.raises(AssertionError): vec = om.Vector(vals) # No values defaults to zeros vec = om.Vector(E=E) assert_equal(np.zeros_like(E), vec.values) with pytest.raises(ValueError): om.Vector(vals, [1, 2, 3, 4, 5])
def test_save_load_tar(): E = np.linspace(0, 1, 100) vals = np.random.random((100, 100)) mat = om.Matrix(values=vals, Ex=E, Eg=E) mat.save('/tmp/mat.tar') with pytest.raises(ValueError): vec = om.Vector(path='/tmp/mat.tar')
def test_numericals(): E = np.array([0, 1, 2]) values1 = np.array([0, 1, -2.]) vector1 = om.Vector(values=values1, E=E) values2 = values1 + 1 vector2 = om.Vector(values=values2, E=E) factor = 5. for op in ("/", "*", "+", "-"): eval(f"assert_equal((vector1{op}vector2).values, values1{op}values2)") eval(f"assert_equal((vector2{op}vector1).values, values2{op}values1)") eval(f"assert_equal((vector1{op}factor).values, values1{op}factor)") eval(f"assert_equal((factor{op}vector1).values, factor{op}values1)") assert_equal((vector2 @ vector1).values, values2 @ values1) assert_equal((vector1 @ vector2).values, values1 @ values2)
def test_save_std_warning(): E = np.linspace(0, 1, 100) vals = np.linspace(2, 3.4, 100) std = np.random.randn(100) * 0.1 vec = om.Vector(values=vals, E=E, std=std) with pytest.warns(UserWarning): vec.save('/tmp/error.m')
def test_init(): E = np.linspace(0, 1, 100) vals = np.linspace(2, 3.4, 100) vec = om.Vector(values=vals, E=E) assert_equal(E, vec.E) assert_equal(vals, vec.values) # No energy defaults to midbin vec = om.Vector(vals) assert_equal(np.arange(0.5, 100.5, 1), vec.E) assert_equal(vals, vec.values) # No values defaults to zeros vec = om.Vector(E=E) assert_equal(np.zeros_like(E), vec.values) with pytest.raises(ValueError): om.Vector(vals, [1, 2, 3, 4, 5])
def test_cumsum(): E = np.array([0., 1.5, 3., 4.5, 6., 7.5]) values = np.array([0., 0., 1., 2., 3., 4.]) std = 0.1 * values expect = np.cumsum(values) expect_std = np.sqrt(np.cumsum(std**2)) vec = om.Vector(values=values, E=E, std=std) vec_cum = vec.cumulative(factor=None, inplace=False) assert_equal(vec_cum.E, E) assert_equal(vec_cum.values, expect) assert_equal(vec_cum.std, expect_std) vec_cum = vec.cumulative(factor=2., inplace=False) assert_equal(vec_cum.E, E) assert_equal(vec_cum.values, 2. * expect) assert_equal(vec_cum.std, 2. * expect_std) vec_cum = vec.cumulative(factor='de', inplace=False) assert_equal(vec_cum.E, E) assert_equal(vec_cum.values, (E[1] - E[0]) * expect) assert_equal(vec_cum.std, (E[1] - E[0]) * expect_std) assert vec.cumulative(factor=None, inplace=True) is None assert_equal(vec.E, E) assert_equal(vec.values, expect) assert_equal(vec.std, expect_std) with pytest.raises(AssertionError): assert_equal(vec.values, values) with pytest.raises(ValueError): vec.cumulative(factor='dx', inplace=True) E = np.array([0., 1.5, 3., 4.5, 6., 7.5, 8.5]) values = np.array([0., 0., 1., 2., 3., 4., 5.]) vec = om.Vector(values=values, E=E) with pytest.raises(RuntimeError): vec.cumulative(factor='de', inplace=True)
def test_cut(): E = np.arange(-1, 10, 1) values = np.linspace(33, 43, 11) vector = om.Vector(values=values, E=E) vector.cut(Emin=0, Emax=8) Ecut = np.arange(0, 9, 1) valcut = np.arange(34, 43) assert_equal(vector.E, Ecut) assert_equal(vector.values, valcut)
def plot_low_energy(): fig, axmat = plt.subplots(3, 3) fig.suptitle("Interpolation in the low energies") Eresp = np.linspace(0, 800, 9) for i, E in enumerate(Eresp): if i == len(axmat.flatten()): break ax = axmat.flatten()[i] E_ = R.Ex[R.index_Ex(E)] values, Eg = R.projection(axis="Eg", Emin=E_, Emax=E_) ompy = om.Vector(values, Eg) ompy.plot(ax=ax, linestyle="--", label=f"ompy {E_:.0f}") ax.legend() ax.set_yscale("log") ax.set_xlim(0, E + 2 * response.f_fwhm_abs(E)) ax.set_ylim(1e-3, None)
eff["E"] = energy_grid specdir = Path("mama_spectra") # fig, ax = plt.subplots() # fig_plain, ax_plain = plt.subplots() for i, (energy, nevent) in enumerate(zip(tqdm(energy_grid), nevents)): # if energy > 1000: # just for testing # break fn = specdir / f"grid_{energy}keV_n{nevent}.root.m" if not fn.exists(): continue vec = om.Vector(path=fn, units="MeV") vec.to_keV() eff.loc[i] = get_efficiencies(vec, eff["E"][i]) # rebin and smooth; rebin first to same time smoothing vec.rebin(mids=energy_out_uncut) vec.values = om.gauss_smoothing(vec.values, vec.E, fFWHM(vec.E, fwhm_pars)) vec.rebin(mids=energy_out) respmat.values[i, :] = vec.values # # get before smoothing, not after -> large effect # # eff_photo = get_area(vec, energy-10, energy+10) / nevent # # print(eff_photo)
import matplotlib.pyplot as plt import ompy as om from pathlib import Path basedir = Path("mama_spectra") files = [file for file in basedir.iterdir()] files.sort() # files = [files[0], # "mama_spectra/grid_2700_run_60Co.root.m", # "mama_spectra/grid_2701_run_60Co.root.m", # "mama_spectra/grid_1585_run_60Co.root.m", ] data = [om.Vector(path=file) for file in files] Nrows = int((len(files) / 5) / 2 + 0.5) if Nrows < 2: Nrows = 2 fig, ax = plt.subplots(Nrows, 2, sharex=True) ax = ax.flatten() for i, vec in enumerate(data): # vec.save(str(files[i]) + ".txt") vec.rebin(factor=10) print(f"{vec.values.sum():.2e}") vec.values /= vec.values.sum() vec.plot(ax=ax[0]) axdiff = ax[i % (Nrows * 2 - 1) + 1] if i == 0: vec0 = vec
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)
before = om.Matrix(values=values, Eg=[10., 20, 30], Ex=[10., 20, 30]) values = np.array([vals_rebinned, vals_rebinned, vals_rebinned]).T after = om.Matrix(values=values, Eg=[10, 20, 30], Ex=[10., 15, 20, 25]) rebinned = before.rebin(axis="Ex", mids=after.Ex, inplace=False) assert_equal(rebinned.Eg, after.Eg) assert_equal(rebinned.Ex, after.Ex) assert_allclose(rebinned.values, after.values) np.random.seed(678456456) vec1 = om.Vector(values=[1., 1, 1, 1], E=[2., 3, 4, 5]) vec2 = om.Vector(values=[0.2, 1, 4, 1], E=[2., 2.5, 4, 5]) vec3 = om.Vector(values=np.random.uniform(size=50), E=np.linspace(-10, 10, num=50)) @pytest.mark.parametrize( "vec, factor", [(vec1, 1), (vec2, 1.5), (vec2, 2.), (vec3, 5), # (vec2, 3), pytest.param(vec1, 1/4, marks=pytest.mark.xfail(reason="see issue #122")) ],) def test_rebin_factor_preserve_counts(vec, factor): sum_before = vec.values.sum()
import numpy as np import matplotlib.pyplot as plt from scipy.signal import find_peaks, peak_prominences import ompy as om data = om.Vector(path="mama_spectra/root_files/grid_-1_run_152Eu.root.m") x = data.values peaks, properties = find_peaks(x, prominence=200) # plt.plot(data.E[peaks], x[peaks], "xr") # plt.plot(x) # plt.legend(['distance']) prominences = peak_prominences(x, peaks)[0] contour_heights = x[peaks] - prominences plt.plot(data.E, x) plt.plot(data.E[peaks], x[peaks], "x") plt.vlines(x=data.E[peaks], ymin=contour_heights, ymax=x[peaks]) # plt.show() print(np.c_[data.E[peaks]*1000, prominences]) plt.show()