Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
133 commits
Select commit Hold shift + click to select a range
4dd245d
Add coverage report to GHA
gonzaponte Oct 25, 2024
18f8730
Remove unnecessary checks
gonzaponte May 17, 2024
026f0e7
Check annotations in create_deconvolution_df
gonzaponte May 17, 2024
8489954
Test that beersheba checks dimensions
gonzaponte May 17, 2024
5df4bac
Parametrize sophronia test to run with and without corrections
gonzaponte May 17, 2024
9368b41
Remove deprecated out_of_map variable
gonzaponte May 17, 2024
55616c9
Add tests to check behaviour of reconstruction failures
gonzaponte May 17, 2024
d0aa3ba
Remove unused calibrate components
gonzaponte May 17, 2024
9ac80a7
Check annotations in sensor_data
gonzaponte May 17, 2024
51327e7
Do not ignore missing tables in MC_hits_from_files
gonzaponte May 17, 2024
95757d8
Add test to verify that eutropia doesn't complain about bad files
gonzaponte May 17, 2024
ed2cdf7
Remove unnecessary protections
gonzaponte May 17, 2024
3227556
Test length of failing case
gonzaponte May 18, 2024
abacd3b
Check annotations in get_{pmt,sipm}_wfs
gonzaponte May 18, 2024
bb4e59a
Make get_run_number more robust and test it
gonzaponte May 18, 2024
c659545
Fix type hint
gonzaponte Oct 20, 2024
efb801e
Mark test as xfailed
gonzaponte Oct 20, 2024
647ddff
Delete deprecated test
gonzaponte Oct 20, 2024
8f4f6ba
Refactor `get_run_number`
gonzaponte Jul 23, 2025
422dbff
Protect against empty input pmap file
gonzaponte Oct 20, 2024
e0ed211
Protect against empty input dst file
gonzaponte Oct 20, 2024
8004cbd
Expand dorothea test to catch warning
gonzaponte Oct 20, 2024
4ba5893
Add protection against empty output
gonzaponte Oct 20, 2024
f458604
Extend test to catch warning
gonzaponte Oct 20, 2024
e8a3413
Fix `test_pmap_event_id_selection`
gonzaponte Oct 20, 2024
b786cfa
Rewrite peak selection tests
gonzaponte Oct 21, 2024
3a1c9f2
Move width calculation to fixture
gonzaponte Oct 21, 2024
b65d1fd
Add test_voxels_within_radius and `test_energy_of_voxels_within_radius`
gonzaponte Oct 21, 2024
5afe1c7
Add `test_load_dst_warns_corrupted_file`
gonzaponte Oct 21, 2024
0fd2943
Exclude `celsius` from coverage report
gonzaponte Oct 21, 2024
1b8548f
Remove unreachable if/else branch
gonzaponte Oct 21, 2024
52f0358
Remove unused fixture
gonzaponte Oct 21, 2024
34a8d00
Parametrize `test_create_deconvolution_df` to use both values of `Cut…
gonzaponte Oct 21, 2024
82febfb
Add `test_beersheba_ndim`
gonzaponte Oct 21, 2024
83b64ea
Remove unused function
gonzaponte Oct 21, 2024
4705c4b
Add `test_merge_nn_hits_different_peaks`
gonzaponte Oct 21, 2024
c8e5ff6
Rewrite `test_drop_isolated_sensors`
gonzaponte Oct 21, 2024
1e1c61c
Add `test_read_maps_data_without_time_evolution`
gonzaponte Oct 21, 2024
44d105f
Exclude line from coverage report
gonzaponte Oct 21, 2024
bd629ea
Add `test_get_lt_values_complains_if_input_mismatch`
gonzaponte Oct 21, 2024
eaace7b
Add tests for `pad_safe`
gonzaponte Oct 21, 2024
d726d40
Replace useless statement with `pass`
gonzaponte Oct 21, 2024
12f23b5
Exclude test from coverage report
gonzaponte Oct 21, 2024
bdda95f
Remove unnecessary check
gonzaponte Oct 21, 2024
44fa728
Add tests for diomira's `select_trigger_filter` and `emulate_trigger`
gonzaponte Oct 21, 2024
8c28c33
Exclude function from coverage report
gonzaponte Oct 21, 2024
ca46403
Add tests for `get_actual_sipm_thr`
gonzaponte Oct 21, 2024
fd3cb68
Add and check annotations in `get_actual_sipm_threshold`
gonzaponte Oct 21, 2024
cc9b777
Add `test_copy_mc_info_raises_missing_event`
gonzaponte Oct 21, 2024
ec19aa4
Add tests for `dst_from_files`
gonzaponte Oct 22, 2024
e25af7f
Add warning for empty input in `dhits_from_files`
gonzaponte Oct 22, 2024
0db17e6
Add test for `dhits_from_files`
gonzaponte Oct 22, 2024
6c8a5a2
Replace meaningless checks with TODOs
gonzaponte Oct 22, 2024
e3d99b0
Comment out unused fixture
gonzaponte Oct 22, 2024
0918179
Simplify `test_dropped_voxels_have_nan_energy`
gonzaponte Oct 22, 2024
5eecd8a
Drop unused function
gonzaponte Oct 22, 2024
fd091d2
Remove unused composite
gonzaponte Oct 22, 2024
b8a15c6
Use environment variable in config file
gonzaponte Oct 22, 2024
3194141
Exclude empty lines from coverage report
gonzaponte Oct 22, 2024
372e79f
Fix `test_incorrect_sensor_type_raises_ValueError`
gonzaponte Oct 22, 2024
3127279
Remove unnecessary try/except clauses
gonzaponte Oct 22, 2024
637aff8
Exclude function from coverage report
gonzaponte Oct 22, 2024
33a737e
Add tests for `noise_suppression`
gonzaponte Oct 22, 2024
2ad8764
Protect against non-existing DBs
gonzaponte Oct 22, 2024
444a720
Fix `test_RadioactivityData_get_version`
gonzaponte Oct 22, 2024
34f2d6c
Remove unnecessary else branch
gonzaponte Oct 22, 2024
12ba23a
Remove old MC checks from coverage report
gonzaponte Oct 22, 2024
3b351ff
Exclude specific lines from coverage report
gonzaponte Oct 22, 2024
9113343
Extend test to include another invalid input
gonzaponte Oct 22, 2024
2d6c96c
Add tests for `seeds_and_bounds_with_db`
gonzaponte Oct 22, 2024
08e219d
Add tests for sensor type input
gonzaponte Oct 22, 2024
455de4e
Exclude likely-to-be-deprecated function from coverage report
gonzaponte Oct 22, 2024
9745676
Add tests for S12SelectorOutput
gonzaponte Oct 22, 2024
431df95
Improve tests for `fixed_parameters`
gonzaponte Oct 23, 2024
da55774
Add `test_get_chi2_and_pvalue_auto_errors`
gonzaponte Oct 23, 2024
557f131
Parametrize `test_profileXY`
gonzaponte Oct 23, 2024
b9bec54
Add `test_drop_isolated_sensors_drop_all`
gonzaponte Oct 23, 2024
4040816
Exclude line from coverage report
gonzaponte Oct 23, 2024
b49ce6b
Test convergence in `lucy_richardson`
gonzaponte Oct 23, 2024
1068ac2
Add tests for `tbl.filters`
gonzaponte Oct 24, 2024
3b980ad
Replace useless `dbnew` fixture
gonzaponte Oct 24, 2024
2b4e7ae
Remove unused fixtures and files
gonzaponte Oct 24, 2024
8ae69a2
Remove block from coverage report
gonzaponte Oct 24, 2024
64f839c
Remove functions from coverage report
gonzaponte Oct 24, 2024
b69b7f2
Add more tests to dataflow
gonzaponte Oct 24, 2024
da180ce
Exclude block from coverage report
gonzaponte Oct 24, 2024
2175578
Remove unused function
gonzaponte Oct 24, 2024
26dd2f6
Exclude function from coverage report
gonzaponte Oct 24, 2024
7460d2d
Remove unused function
gonzaponte Oct 24, 2024
eef855e
Cosmetics
gonzaponte Oct 24, 2024
df59ce2
Exclude skipped tests from coverage report
gonzaponte Oct 24, 2024
aa2ba05
Exclude functions from coverage report
gonzaponte Oct 24, 2024
ff33648
Extend tests for `xy`
gonzaponte Oct 24, 2024
2ba71a4
Add test for `minmax` equality
gonzaponte Oct 24, 2024
9666a9b
Add tests for `event_range`
gonzaponte Oct 24, 2024
90648e7
Exclude line from coverage report
gonzaponte Oct 24, 2024
ddc91d0
Add test for `compare_signature_to_values`
gonzaponte Oct 24, 2024
dc5fb1f
Exclude method from coverage report
gonzaponte Oct 24, 2024
6677073
Exclude very slow test from coverage report
gonzaponte Oct 24, 2024
961600d
Exlude skipped test from coverage report
gonzaponte Oct 24, 2024
c08adb0
Exclude exception handling from coverage report
gonzaponte Oct 24, 2024
9ef6212
Drop unused function
gonzaponte Oct 24, 2024
9e7553a
Delete unused TrackCollection
gonzaponte Oct 24, 2024
3ec7bf5
Add test for KrEvent's fill_defaults
gonzaponte Oct 24, 2024
387c483
Fix KrEvent's fill_defaults
gonzaponte Oct 24, 2024
edb0390
Remove unused function/file
gonzaponte Oct 24, 2024
bfeb5f8
Replace exit with raise
gonzaponte Oct 24, 2024
635b12d
Refactor channel_param_io tests
gonzaponte Oct 24, 2024
5c76f4d
Refactor channel_param_io module
gonzaponte Oct 24, 2024
df63f82
Add more tests
gonzaponte Oct 24, 2024
559dc85
Replace skip mark with xfail mark
gonzaponte Oct 24, 2024
591b78c
Fix download db test
gonzaponte Oct 25, 2024
2b7456a
Remove pytest decorator in non-test function
gonzaponte Oct 24, 2024
35825a7
Exclude database folder from coverage report
gonzaponte Oct 24, 2024
f074ebd
Mark some tests as slow
gonzaponte Oct 24, 2024
bc4edf5
Fix typo
gonzaponte Oct 24, 2024
f3ebab7
Refactor peak selection tests
gonzaponte Oct 24, 2024
8c69ce5
Cosmetics
gonzaponte Oct 24, 2024
b6b7579
Extend testing for `copy_cities_configuration`
gonzaponte Oct 24, 2024
f30b77e
Remove unnecessary check
gonzaponte Oct 24, 2024
cfb9e29
Remove unused classes
gonzaponte Oct 24, 2024
45b7772
Exlude block from coverage report
gonzaponte Oct 24, 2024
66d9395
Fix test name
gonzaponte Oct 24, 2024
30eb0af
Refactor `light_tables_c_test`
gonzaponte Oct 30, 2024
8ffaa6a
Exclude line from coverage report
gonzaponte Oct 30, 2024
cb0cbb2
Refactor test to avoid subcases
gonzaponte Oct 30, 2024
20df10e
Split `test_rebin_peak_threshold` test into many
gonzaponte Oct 31, 2024
7f37ec1
Refactor test to avoid skipping if branch
gonzaponte Nov 21, 2024
045fa54
Extract coverage report into its own workflow
gonzaponte Nov 3, 2024
afe4cff
Raise a warning if coverage incomplete
gonzaponte Nov 3, 2024
d1f35b0
Silence warning in regarding no pmaps in input
gonzaponte Nov 20, 2024
1db9443
Silence no config group warning
gonzaponte Nov 20, 2024
5871469
Silence no pmaps warning
gonzaponte Jul 23, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# replace by exclude_also after bumping to >=7.2
# with that, "pragma: no cover" can be removed
[report]
exclude_lines =
def __str__
def __repr__
pragma: no cover

[run]
omit =
invisible_cities/database/*
43 changes: 43 additions & 0 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# This workflow will install IC and run all the tests with pytest

name: Test suite

on:
pull_request:

jobs:
check-coverage:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- name: Get LFS files
run: git lfs pull

- name: Install IC
run: |
source $CONDA/etc/profile.d/conda.sh
source manage.sh work_in_python_version_no_tests 3.8

- name: Produce coverage report
run: |
source $CONDA/etc/profile.d/conda.sh
source manage.sh work_in_python_version_no_tests 3.8
coverage run -m pytest
coverage report -m > coverage_report

- name: Check coverage report
run: |
echo "Showing only files with coverage < 100%"
head -2 coverage_report
incomplete_coverage=$(head -n -2 coverage_report | tail -n +3 | grep -v "100%")

while read line; do
printf '\033[0;31m%s\033[0m\n' "$line" # red color ... reset color
done <<<${incomplete_coverage}

tail -2 coverage_report

if [ ! -z "$incomplete_coverage" ]; then
echo "::warning ::Test suite coverage incomplete"
fi
3 changes: 1 addition & 2 deletions .github/workflows/test_suite.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
pull_request:

jobs:
build:
build-and-test:

strategy:
fail-fast: false
Expand All @@ -30,7 +30,6 @@ jobs:
source $CONDA/etc/profile.d/conda.sh
source manage.sh work_in_python_version_no_tests ${{ matrix.python-version }}


- name: Run tests
run: |
set -o pipefail # necessary for test failure to propagate to `tee`
Expand Down
97 changes: 79 additions & 18 deletions invisible_cities/calib/calib_functions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from .. core import tbl_functions as tbl
from .. core import fit_functions as fitf
from .. core import system_of_units as units
from .. core.core_functions import in_range
from .. core.stat_functions import poisson_sigma
from .. evm.nh5 import SensorTable
from .. types.symbols import SensorType
Expand Down Expand Up @@ -148,9 +149,9 @@ def test_copy_sensor_table(config_tmpdir, sensor_type, sensors):
@mark.parametrize('sensor_type , n_channel, gain_seed, gain_sigma_seed',
((SensorType.SIPM, 1, 16.5622, 2.5),
(SensorType.PMT , 5, 24.9557, 9.55162)))
def test_seeds_db(sensor_type, n_channel, gain_seed, gain_sigma_seed, dbnew):
def test_seeds_db(sensor_type, n_channel, gain_seed, gain_sigma_seed):
run_number = 6217
result = cf.seeds_db(sensor_type, dbnew, run_number, n_channel)
result = cf.seeds_db(sensor_type, "new", run_number, n_channel)
assert result == (gain_seed, gain_sigma_seed)


Expand Down Expand Up @@ -190,14 +191,16 @@ def test_sensor_values(sensor_type, scaler, expected_range, min_b, max_b, half_w
@mark.parametrize('sensor_type, run_number, n_chann, scaler',
(( None, 6217, 1023, _dark_scaler_sipm),
( None, 6217, 0, _dark_scaler_pmt)))
def test_incorrect_sensor_type_raises_ValueError(sensor_type, dbnew, run_number, n_chann, scaler):
def test_incorrect_sensor_type_raises_ValueError(sensor_type, run_number, n_chann, scaler):
bins = np.array([ -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7])
spec = np.array([ 28, 539, 1072, 1845, 2805, 3251, 3626, 3532, 3097, 2172, 1299, 665, 371, 174])
ped_vals = np.array([2.65181178e+04, 1.23743445e-01, 2.63794236e+00])

with raises(ValueError):
cf. seeds_db(sensor_type, dbnew, run_number, n_chann)
cf. seeds_db(sensor_type, "new", run_number, n_chann)
with raises(ValueError):
cf.poisson_mu_seed(sensor_type, scaler, bins, spec, ped_vals)
with raises(ValueError):
cf. sensor_values(sensor_type, scaler, bins, spec, ped_vals)


Expand All @@ -214,6 +217,7 @@ def test_pedestal_values():
assert_approx_equal(ped_values.sigma_min, 0.001)


@mark.slow
def test_compute_seeds_from_spectrum(ICDATADIR):
PATH_IN = os.path.join(ICDATADIR, 'sipmcalspectra_R6358.h5')
# Suppress warnings from division by zero in some bins.
Expand All @@ -227,12 +231,10 @@ def test_compute_seeds_from_spectrum(ICDATADIR):
for ich, (led, dar) in enumerate(zip(specsL, specsD)):
b1 = 0
b2 = len(dar)
try:
valid_bins = np.argwhere(led>=min_stat)
b1 = valid_bins[ 0][0]
b2 = valid_bins[-1][0]
except IndexError:
continue

valid_bins = np.argwhere(led>=min_stat)
b1 = valid_bins[ 0][0]
b2 = valid_bins[-1][0]

peaks_dark = find_peaks_cwt(dar, np.arange(2, 20), min_snr=2)
if len(peaks_dark) == 0:
Expand Down Expand Up @@ -260,7 +262,53 @@ def test_compute_seeds_from_spectrum(ICDATADIR):
assert gain_sigma_seed != 0


def test_seeds_without_using_db(ICDATADIR, dbnew):
@mark.filterwarnings("ignore:Covariance of the parameters could not be estimated")
def test_seeds_and_bounds_with_db():
values = np.array([1, 0.5, .1], dtype=float)
errors = (values + 1) / 20
x = np.arange(-50, 300)
y = fitf.gauss(x, *values)
sel = in_range(x, -5, 5, right_closed=True) # magic
scaler_func = cf.dark_scaler(y[sel])
seeds, bounds = cf.seeds_and_bounds(SensorType.SIPM, 8000, 0,
scaler_func, x, y,
values, "new", errors,
use_db_gain_seeds=True)


# this test doesn't do much, to be improved
assert all(seeds)
assert len(seeds) == 4
assert len(bounds) == 2
assert len(bounds[0]) == 4
assert len(bounds[1]) == 4


@mark.filterwarnings("ignore:Covariance of the parameters could not be estimated")
def test_seeds_and_bounds_with_gau():
values = np.array([1, 0.5, .1], dtype=float)
errors = (values + 1) / 20
x = np.arange(-50, 300)
y = fitf.gauss(x, *values)
sel = in_range(x, -5, 5, right_closed=True) # magic
scaler_func = cf.dark_scaler(y[sel])
seeds, bounds = cf.seeds_and_bounds(SensorType.SIPM, 8000, 0,
scaler_func, x, y,
values, "new", errors,
"gau",
use_db_gain_seeds=True)


# this test doesn't do much, to be improved
assert all(seeds)
assert len(seeds) == 6
assert len(bounds) == 2
assert len(bounds[0]) == 6
assert len(bounds[1]) == 6


@mark.slow
def test_seeds_without_using_db(ICDATADIR):
PATH_IN = os.path.join(ICDATADIR, 'sipmcalspectra_R6358.h5')
# Suppress warnings from division by zero in some bins.
with warnings.catch_warnings(), tb.open_file(PATH_IN) as h5in:
Expand All @@ -275,12 +323,10 @@ def test_seeds_without_using_db(ICDATADIR, dbnew):
for ich, (led, dar) in enumerate(zip(specsL, specsD)):
b1 = 0
b2 = len(dar)
try:
valid_bins = np.argwhere(led>=min_stat)
b1 = valid_bins[ 0][0]
b2 = valid_bins[-1][0]
except IndexError:
continue

valid_bins = np.argwhere(led>=min_stat)
b1 = valid_bins[ 0][0]
b2 = valid_bins[-1][0]

peaks_dark = find_peaks_cwt(dar, np.arange(2, 20), min_snr=2)
if len(peaks_dark) == 0:
Expand All @@ -300,8 +346,23 @@ def test_seeds_without_using_db(ICDATADIR, dbnew):
scaler_func = cf.dark_scaler(dar[p_range][p_bins])
seeds, bounds = cf.seeds_and_bounds(SensorType.SIPM, run_no, ich,
scaler_func, bins[p_range],
led[p_range], ped_vals, dbnew,
led[p_range], ped_vals, "new",
gfitRes.errors,
use_db_gain_seeds=False)
assert all(seeds)
assert bounds == ((0, 0, 0, 0.001), (np.inf, 10000, 10000, 10000))


@mark.parametrize( "f nargs".split()
, ( (cf. seeds_db, 3)
, (cf.poisson_mu_seed, 4)
, (cf. sensor_values, 4)))
def test_sensor_type_input(f, nargs):
"""
Test that if the first argument (sensor_type) is not a symbol, the
functions complain. The rest of the arguments are irrelevant, so
they are just dummy values.
"""
dummy = [None]*nargs
with raises(ValueError): f( "PMT", *dummy)
with raises(ValueError): f("SiPM", *dummy)
4 changes: 0 additions & 4 deletions invisible_cities/calib/calib_sensors_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@
from ..types.symbols import SiPMCalibMode


def mask_sensors(wfs, active):
return wfs * active.astype(wfs.dtype).reshape(active.size, 1)


def scipy_mode(x, axis=0):
"""
Scipy implementation of the mode (runs very slow).
Expand Down
31 changes: 13 additions & 18 deletions invisible_cities/cities/beersheba.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,15 +187,6 @@ def deconvolve_signal(det_db : pd.DataFrame,
**satellite_params,
inter_method = inter_method)

if not isinstance(energy_type , HitEnergy ):
raise ValueError(f'energy_type {energy_type} is not a valid energy type.')
if not isinstance(inter_method, InterpolationMethod):
raise ValueError(f'inter_method {inter_method} is not a valid interpolation method.')
if not isinstance(cut_type , CutType ):
raise ValueError(f'cut_type {cut_type} is not a valid cut type.')
if not isinstance(deconv_mode , DeconvolutionMode ):
raise ValueError(f'deconv_mode {deconv_mode} is not a valid deconvolution mode.')

def deconvolve_hits(df, z):
'''
Given an slice, applies deconvolution using the PSF
Expand Down Expand Up @@ -259,7 +250,14 @@ def apply_deconvolution(df):
return apply_deconvolution


def create_deconvolution_df(hits, deconv_e, pos, cut_type, e_cut, n_dim):
@check_annotations
def create_deconvolution_df( hits : pd.DataFrame
, deconv_e : np.ndarray
, pos : Tuple[np.ndarray, np.ndarray, np.ndarray]
, cut_type : CutType
, e_cut : float
, n_dim : int
) -> pd.DataFrame:
'''
Given the output of the deconvolution, it cuts the low energy voxels and
creates a dataframe object with the resulting output.
Expand All @@ -280,12 +278,8 @@ def create_deconvolution_df(hits, deconv_e, pos, cut_type, e_cut, n_dim):

df = pd.DataFrame(columns=['event', 'npeak', 'X', 'Y', 'Z', 'E'])

if cut_type is CutType.abs:
sel_deconv = deconv_e > e_cut
elif cut_type is CutType.rel:
sel_deconv = deconv_e / deconv_e.max() > e_cut
else:
raise ValueError(f'cut_type {cut_type} is not a valid cut type.')
if cut_type is CutType.abs: sel_deconv = deconv_e > e_cut
else : sel_deconv = deconv_e / deconv_e.max() > e_cut

df['E'] = deconv_e[sel_deconv]
df['event'] = hits.event.unique()[0]
Expand Down Expand Up @@ -497,9 +491,10 @@ def beersheba( files_in : OneOrManyFiles

for p in ['sample_width', 'bin_size', 'diffusion']:
if len(deconv_params[p]) != deconv_params['n_dim']:
raise ValueError (f"Parameter {p} dimensions do not match n_dim parameter")
raise ValueError(f"Parameter {p} dimensions do not match n_dim parameter")

if deconv_params['n_dim'] > 2:
raise NotImplementedError(f"{deconv_params['n_dim']}-dimensional PSF not yet implemented")
raise NotImplementedError(f"{deconv_params['n_dim']}-dimensional PSF not yet implemented")

cut_sensors = fl.map(cut_over_Q (deconv_params.pop("q_cut") , ['E', 'Ec']),
item = 'hits')
Expand Down
57 changes: 40 additions & 17 deletions invisible_cities/cities/beersheba_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,22 @@
from .. types.symbols import CutType


def test_create_deconvolution_df(ICDATADIR):
@mark.parametrize("cut_type", CutType)
def test_create_deconvolution_df(ICDATADIR, cut_type):
true_in = os.path.join(ICDATADIR, "exact_Kr_deconvolution_with_MC.h5")
true_dst = dio.load_dst(true_in, 'DECO', 'Events')
ecut = 1e-2
new_dst = pd.concat([create_deconvolution_df(t, t.E.values, (t.X.values, t.Y.values, t.Z.values),
CutType.abs, ecut, 3) for _, t in true_dst.groupby('event')])
true_dst = true_dst.loc[true_dst.E > ecut, :].reset_index(drop=True)
# compare only existing columns
true_dst = true_dst.loc[:, new_dst.columns.values.tolist()]
assert_dataframes_close(new_dst .reset_index(drop=True), true_dst.reset_index(drop=True))
cut_type, ecut, 3) for _, t in true_dst.groupby('event')])
for event, df in true_dst.groupby("event"):
sel = (df.E > ecut if cut_type is CutType.abs else
df.E > ecut * df.E.max())
df = df.loc[sel].reset_index(drop=True)
# compare only existing columns
df = df.loc[:, new_dst.columns.values.tolist()]


@mark.parametrize("cut_type", CutType.__members__)
def test_create_deconvolution_df_cuttype(ICDATADIR, cut_type):
true_in = os.path.join(ICDATADIR, "exact_Kr_deconvolution_with_MC.h5")
true_dst = dio.load_dst(true_in, 'DECO', 'Events')
ecut = 1e-2

with raises(ValueError):
create_deconvolution_df(true_dst, true_dst.E.values,
(true_dst.X.values, true_dst.Y.values, true_dst.Z.values),
cut_type, ecut, 3)
new_event = new_dst.loc[new_dst.event==event]
assert_dataframes_close(new_event.reset_index(drop=True), df.reset_index(drop=True))


def test_distribute_energy(ICDATADIR):
Expand All @@ -56,6 +50,18 @@ def test_distribute_energy(ICDATADIR):
assert np.isclose (true_dst1.E.sum(), true_dst2.E.sum())


def test_beersheba_ndim(beersheba_config, config_tmpdir):
path_out = os.path.join(config_tmpdir, "beersheba_ndim.h5")
beersheba_config.update(dict(file_out = path_out))
beersheba_config["deconv_params"].update(dict( n_dim = 3
, sample_width = [1]*3
, bin_size = [1]*3
, diffusion = [1]*3 ))

with raises(NotImplementedError):
beersheba(**beersheba_config)


@ignore_warning.no_config_group
@ignore_warning.str_length
@ignore_warning.not_kdst
Expand Down Expand Up @@ -107,6 +113,23 @@ def test_beersheba_exact_result( deco
expected = getattr(true_output_file.root, table)
assert_tables_equality(got, expected, rtol=1e-6)

@mark.parametrize( "updates"
, ( dict(sample_width = [1]), dict(sample_width = [1,1,1])
, dict(bin_size = [1]), dict(bin_size = [1,1,1])
, dict(diffusion = [1]), dict(diffusion = [1,1,1])
))
def test_beersheba_checks_dimensions(config_tmpdir, beersheba_config, updates):
# check that if these quantities do not have the correct number of
# dimensions (2), the city raises an error
par = next(iter(updates))
n = len(updates[par])
path_out = os.path.join(config_tmpdir, f"beersheba_only_check_dims_{par}_{n}.h5")
beersheba_config.update(dict(file_out = path_out))
beersheba_config['deconv_params'].update(updates)

with raises(ValueError, match="Parameter .* dimensions do not match n_dim parameter"):
beersheba(**beersheba_config)


@ignore_warning.no_config_group
@ignore_warning.str_length
Expand Down
Loading
Loading