def test_rebin_matrix_Ex(): values = np.array([[10, 20, 30], [10, 20, 30], [10, 20, 30]]).T 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)
def test_rebin_both(): shape = (1001, 1001) Elim = (0, 10000) before = om.Matrix(values=np.ones(shape), Eg=np.linspace(Elim[0], Elim[1], shape[0]), Ex=np.linspace(Elim[0], Elim[1], shape[1])) new_shape = (101, 101) new_Elim = Elim after = before.rebin(axis='both', mids=np.linspace(new_Elim[0], new_Elim[1], new_shape[0]), inplace=False) assert len(after.Eg) != len(before.Eg) assert len(after.Ex) != len(before.Ex) assert_equal(after.Eg, after.Ex) before.rebin(axis='both', mids=np.linspace(new_Elim[0], new_Elim[1], new_shape[0]), inplace=True) assert len(after.Eg) == len(before.Eg) assert len(after.Ex) == len(before.Ex) assert_equal(before.Eg, before.Ex) assert_equal(before.Eg, after.Eg)
def test_negatives(firstgen, Ex, fg_Ex): values = np.ones((5, 5)) values = np.tril(values) mat = om.Matrix(values=values) mat.Ex = Ex mat.verify_integrity() with pytest.raises(ValueError): firstgen.apply(mat)
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_shape(firstgen, Ex, fg_Ex): values = np.ones((5, 5)) values = np.tril(values) mat = om.Matrix(values=values) mat.Ex = Ex mat.verify_integrity() first = firstgen.apply(mat) assert first.Ex.shape == fg_Ex.shape np.testing.assert_allclose(first.Ex, fg_Ex)
def test_numericals(): E = np.array([0, 1, 2]) values1 = np.array([[0, 1, 2.], [-2, 1, 2.], [2, 3, -10.]]) matrix1 = om.Matrix(values=values1, Ex=E, Eg=E) values2 = values1 + 1 matrix2 = om.Matrix(values=values2, Ex=E, Eg=E) factor = 5. for op in ("/", "*", "+", "-"): eval(f"assert_equal((matrix1{op}matrix2).values, values1{op}values2)") eval(f"assert_equal((matrix2{op}matrix1).values, values2{op}values1)") eval(f"assert_equal((matrix1{op}factor).values, values1{op}factor)") eval(f"assert_equal((factor{op}matrix1).values, factor{op}values1)") assert_equal((matrix2 @ matrix1).values, values2 @ values1) assert_equal((matrix1 @ matrix2).values, values1 @ values2)
def test_cut_limit(Emin, Emax, vector): values = np.zeros((5, 3)) values[:, 0] = -1 values[:, 2] = 1 Eg = [-1.2, 0.2, 1.6] mat = om.Matrix(values=values, Eg=Eg) mat.cut('Eg', Emin, Emax) assert mat[0, :].shape == vector.shape assert np.all(mat[0, :] == vector)
def test_Matrix_init(): with pytest.raises(ValueError): matrix = np.zeros((3, 3)) E0_array = np.zeros(2) # Shape mismatch to matrix E1_array = np.zeros(3) mat = ompy.Matrix(matrix=matrix, E0_array=E0_array, E1_array=E1_array) with pytest.raises(ValueError): matrix = np.zeros((5, 3)) E0_array = np.zeros(5) E1_array = np.zeros(5) # Shape mismatch to matrix mat = ompy.Matrix(matrix=matrix, E0_array=E0_array, E1_array=E1_array) with pytest.raises(ValueError): matrix = np.zeros((3, 3)) std = np.zeros((3, 2)) # Shape mismatch to matrix E0_array = np.zeros(3) E1_array = np.zeros(3) mat = ompy.Matrix(matrix=matrix, E0_array=E0_array, E1_array=E1_array, std=std)
def test_Matrix_calibration(): # Set up est array E0_array = np.linspace(-200, 200, 201) E1_array = np.linspace(-100, 300, 101) counts = np.random.normal( loc=0.01 * np.meshgrid(E0_array, E1_array, indexing="ij")[0], size=(len(E0_array), len(E1_array))) mat = ompy.Matrix(counts, E0_array, E1_array) # == mat.calibration() == cal = mat.calibration() assert (cal["a00"] == mat.E0_array[0]) assert (cal["a01"] == (mat.E0_array[1] - mat.E0_array[0])) assert (cal["a10"] == mat.E1_array[0]) assert (cal["a11"] == (mat.E1_array[1] - mat.E1_array[0])) # Test calibration attribute check mat = ompy.Matrix() with pytest.raises(TypeError): mat.calibration()
def test_Matrix_read_write(): # Make a Matrix(), write it to file and read it back # to check that everything looks the same shape = (5, 3) matrix = np.random.uniform(low=-1, high=1, size=shape) E0_array = np.linspace(0, 1, shape[0]) E1_array = np.linspace(-1, 2, shape[1]) mat_out = ompy.Matrix(matrix=matrix, E0_array=E0_array, E1_array=E1_array) fname = "tmp_test_readwrite.m" ompy.mama_write(mat_out, fname) mat_in = ompy.mama_read(fname) tol = 1e-5 assert (np.abs(mat_out.matrix - mat_in.matrix) < tol).all() assert (np.abs(mat_out.E0_array - mat_in.E0_array) < tol).all() assert (np.abs(mat_out.E1_array - mat_in.E1_array) < tol).all()
def test_bin_shift(Ex, Eg): values = np.ones((len(Ex), len(Eg)), dtype="float") mat = om.Matrix(values=values, Ex=Ex, Eg=Eg) assert_almost_equal(Ex, mat.Ex) assert_almost_equal(Eg, mat.Eg) mat.to_lower_bin() mat.to_mid_bin() assert_almost_equal(Ex, mat.Ex) assert_almost_equal(Eg, mat.Eg) mat.to_mid_bin() mat.to_lower_bin() assert_almost_equal(Ex, mat.Ex) assert_almost_equal(Eg, mat.Eg)
def ones(shape: Tuple[int, int]) -> om.Matrix: """ Creates a mock matrix with ones in the upper diagonal A 5×5 looks like this: ░░░░░░░░░░ ░░░░░░░░ ░░░░░░ ░░░░ ░░ Args: shape: The shape of the matrix Returns: The matrix """ mat = np.ones(shape) mat = np.tril(mat) return om.Matrix(values=mat)
def test_save_warning(Ex, Eg): values = np.ones((len(Ex), len(Eg)), dtype="float") mat = om.Matrix(values=values, Ex=Ex, Eg=Eg, std=0.5 * values) with pytest.warns(UserWarning): mat.save("/tmp/mat.npy")
#energy_grid = np.append(energy_grid, [int(1.2e4), int(1.5e4), int(2e4)]) #nevents = np.append(nevents, [int(3e6), int(3e6), int(3e6)]) energy_grid = np.arange(50,2340,10) nevents = np.zeros(len(energy_grid)) nevents.fill(100000) fwhm_pars = np.array([60.6499, 0.458252, 0.000265552]) energy_out = np.arange(energy_grid[0], 21000, 10) energy_out_uncut = np.arange(0, 21000, 10) # response mat. with x: incident energy; y: outgoing respmat = om.Matrix(values=np.zeros((len(energy_grid), len(energy_out))), Ex=energy_grid, Eg=energy_out) eff = pd.DataFrame(columns=["E", "tot>50keV", "tot>200keV", "tot>500keV", "fe", "se", "de", "511"]) 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
def test_save_which_error(Ex, Eg): values = np.ones((len(Ex), len(Eg)), dtype="float") mat = om.Matrix(values=values, Ex=Ex, Eg=Eg, std=0.5 * values) with pytest.raises(NotImplementedError): mat.save("/tmp/mat.npy", which='Im not real')
def test_save_std_exception(Ex, Eg): values = np.ones((len(Ex), len(Eg)), dtype="float") mat = om.Matrix(values=values, Ex=Ex, Eg=Eg) with pytest.raises(RuntimeError): mat.save("/tmp/mat.npy", which='std')
# Energy calibration of resulting response matrix: Eg = raw.Eg # Experimental relative FWHM at 1.33 MeV of resulting array fwhm_abs = 6.8 / 100 * 1330 # load response # logger = om.introspection.get_logger('response_class', 'DEBUG') response = om.Response(folderpath) response.smooth_compton = False R, tab = response.interpolate(Eg, fwhm_abs, return_table=True) plot_low_energy() # plots1 Rmama = om.Matrix(path="../example_data/resp.m") fig, axmat = plt.subplots(1, 2, constrained_layout=True) R.plot(scale="log", ax=axmat[0], vmin=5e-5, vmax=5e-1, midbin_ticks=False, title="ompy") lines, ax, _ = Rmama.plot(scale="log", ax=axmat[1], vmin=5e-5, vmax=5e-1, midbin_ticks=False, title="mama") fig.colorbar(lines, ax=ax, extend='both')
def test_Matrix_warning(): with pytest.warns(UserWarning): shape = (5, 3) matrix = np.random.uniform(low=-1, high=1, size=shape) mat = ompy.Matrix(matrix=matrix) mat.load("mock/Dy164_raw.m")
def test_Matrix_cut_rect(): # Sanity check should fail with pytest.raises(AssertionError): mat = ompy.Matrix().cut_rect(None, [5.001, 5])