data-manipulation-utilities 0.2.3__py3-none-any.whl → 0.2.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: data_manipulation_utilities
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Description-Content-Type: text/markdown
5
5
  Requires-Dist: logzero
6
6
  Requires-Dist: PyYAML
@@ -26,7 +26,7 @@ These are tools that can be used for different data analysis tasks.
26
26
 
27
27
  ## Pushing
28
28
 
29
- From the root directory of a version controlled project (i.e. a directory with the `.git` subdirectory)
29
+ From the root directory of a version controlled project (i.e. a directory with the `.git` subdirectory)
30
30
  using a `pyproject.toml` file, run:
31
31
 
32
32
  ```bash
@@ -36,10 +36,10 @@ publish
36
36
  such that:
37
37
 
38
38
  1. The `pyproject.toml` file is checked and the version of the project is extracted.
39
- 1. If a tag named as the version exists move to the steps below.
39
+ 1. If a tag named as the version exists move to the steps below.
40
40
  1. If it does not, make a new tag with the name as the version
41
41
 
42
- Then, for each remote it pushes the tags and the commits.
42
+ Then, for each remote it pushes the tags and the commits.
43
43
 
44
44
  *Why?*
45
45
 
@@ -137,7 +137,17 @@ pdf = mod.get_pdf()
137
137
  ```
138
138
 
139
139
  where the model is a sum of three `CrystallBall` PDFs, one with a right tail and two with a left tail.
140
- The `mu` and `sg` parameters are shared.
140
+ The `mu` and `sg` parameters are shared. The elementary components that can be plugged are:
141
+
142
+ ```
143
+ exp: Exponential
144
+ pol1: Polynomial of degree 1
145
+ pol2: Polynomial of degree 2
146
+ cbr : CrystallBall with right tail
147
+ cbl : CrystallBall with left tail
148
+ gauss : Gaussian
149
+ dscb : Double sided CrystallBall
150
+ ```
141
151
 
142
152
  ### Printing PDFs
143
153
 
@@ -299,7 +309,7 @@ this will:
299
309
  - Try fitting at most 10 times
300
310
  - After each fit, calculate the goodness of fit (in this case the p-value)
301
311
  - Stop when the number of tries has been exhausted or the p-value reached is higher than `0.05`
302
- - If the fit has not succeeded because of convergence, validity or goodness of fit issues,
312
+ - If the fit has not succeeded because of convergence, validity or goodness of fit issues,
303
313
  randomize the parameters and try again.
304
314
  - If the desired goodness of fit has not been achieved, pick the best result.
305
315
  - Return the `FitResult` object and set the PDF to the final fit result.
@@ -337,11 +347,11 @@ bkg = zfit.pdf.Exponential(obs=obs, lam=lm)
337
347
  nbk = zfit.Parameter('nbk', 1000, 0, 10000)
338
348
  ebkg= bkg.create_extended(nbk, name='expo')
339
349
 
340
- # Add them
350
+ # Add them
341
351
  pdf = zfit.pdf.SumPDF([ebkg, esig])
342
352
  sam = pdf.create_sampler()
343
353
 
344
- # Plot them
354
+ # Plot them
345
355
  obj = ZFitPlotter(data=sam, model=pdf)
346
356
  d_leg = {'gauss': 'New Gauss'}
347
357
  obj.plot(nbins=50, d_leg=d_leg, stacked=True, plot_range=(0, 10), ext_text='Extra text here')
@@ -353,7 +363,7 @@ obj.axs[1].plot([0, 10], [0, 0], linestyle='--', color='black')
353
363
  this class supports:
354
364
 
355
365
  - Handling title, legend, plots size.
356
- - Adding pulls.
366
+ - Adding pulls.
357
367
  - Stacking and overlaying of PDFs.
358
368
  - Blinding.
359
369
 
@@ -434,7 +444,7 @@ dataset:
434
444
  nan:
435
445
  x : 0
436
446
  y : 0
437
- z : -999
447
+ z : -999
438
448
  training :
439
449
  nfold : 10
440
450
  features : [x, y, z]
@@ -497,7 +507,7 @@ When training on real data, several things might go wrong and the code will try
497
507
  will end up in different folds. The tool checks for wether a model is evaluated for an entry that was used for training and raise an exception. Thus, repeated
498
508
  entries will be removed before training.
499
509
 
500
- - **NaNs**: Entries with NaNs will break the training with the scikit `GradientBoostClassifier` base class. Thus, we:
510
+ - **NaNs**: Entries with NaNs will break the training with the scikit `GradientBoostClassifier` base class. Thus, we:
501
511
  - Can use the `nan` section shown above to replace `NaN` values with something else
502
512
  - For whatever remains we remove the entries from the training.
503
513
 
@@ -674,6 +684,9 @@ ptr.run()
674
684
  where the config dictionary `cfg_dat` in YAML would look like:
675
685
 
676
686
  ```yaml
687
+ general:
688
+ # This will set the figure size
689
+ size : [20, 10]
677
690
  selection:
678
691
  #Will do at most 50K random entries. Will only happen if the dataset has more than 50K entries
679
692
  max_ran_entries : 50000
@@ -703,6 +716,16 @@ plots:
703
716
  yscale : 'linear'
704
717
  labels : ['x + y', 'Entries']
705
718
  normalized : true #This should normalize to the area
719
+ # Some vertical dashed lines are drawn by default
720
+ # If you see them, you can turn them off with this
721
+ style:
722
+ skip_lines : true
723
+ # This can pass arguments to legend making function `plt.legend()` in matplotlib
724
+ legend:
725
+ # The line below would place the legend outside the figure to avoid ovelaps with the histogram
726
+ bbox_to_anchor : [1.2, 1]
727
+ stats:
728
+ nentries : '{:.2e}' # This will add number of entries in legend box
706
729
  ```
707
730
 
708
731
  it's up to the user to build this dictionary and load it.
@@ -724,14 +747,19 @@ The config would look like:
724
747
  ```yaml
725
748
  saving:
726
749
  plt_dir : tests/plotting/2d
750
+ selection:
751
+ cuts:
752
+ xlow : x > -1.5
727
753
  general:
728
754
  size : [20, 10]
729
755
  plots_2d:
730
756
  # Column x and y
731
757
  # Name of column where weights are, null for not weights
732
758
  # Name of output plot, e.g. xy_x.png
733
- - [x, y, weights, 'xy_w']
734
- - [x, y, null, 'xy_r']
759
+ # Book signaling to use log scale for z axis
760
+ - [x, y, weights, 'xy_w', false]
761
+ - [x, y, null, 'xy_r', false]
762
+ - [x, y, null, 'xy_l', true]
735
763
  axes:
736
764
  x :
737
765
  binning : [-5.0, 8.0, 40]
@@ -823,7 +851,7 @@ Directory/Treename
823
851
  B_ENDVERTEX_CHI2DOF Double_t
824
852
  ```
825
853
 
826
- ## Comparing ROOT files
854
+ ## Comparing ROOT files
827
855
 
828
856
  Given two ROOT files the command below:
829
857
 
@@ -856,6 +884,40 @@ Trees only in file_2.root:
856
884
  - Hlt2RD_BsToPhiMuMu_MVA/DecayTree
857
885
  ```
858
886
 
887
+ # File system
888
+
889
+ ## Versions
890
+
891
+ The utilities below allow the user to deal with versioned files and directories
892
+
893
+ ```python
894
+ from dmu.generic.version_management import get_last_version
895
+ from dmu.generic.version_management import get_next_version
896
+ from dmu.generic.version_management import get_latest_file
897
+
898
+ # get_next_version will take a version and provide the next one, e.g.
899
+ get_next_version('v1') # -> 'v2'
900
+ get_next_version('v1.1') # -> 'v2.1'
901
+ get_next_version('v10.1') # -> 'v11.1'
902
+
903
+ get_next_version('/a/b/c/v1') # -> '/a/b/c/v2'
904
+ get_next_version('/a/b/c/v1.1') # -> '/a/b/c/v2.1'
905
+ get_next_version('/a/b/c/v10.1') # -> '/a/b/c/v11.1'
906
+
907
+ # `get_latest_file` will return the path to the file with the highest version
908
+ # in the `dir_path` directory that matches a wildcard, e.g.:
909
+
910
+ last_file = get_latest_file(dir_path = file_dir, wc='name_*.txt')
911
+
912
+ # `get_last_version` will return the string with the latest version
913
+ # of directories in `dir_path`, e.g.:
914
+
915
+ oversion=get_last_version(dir_path=dir_path, version_only=True) # This will return only the version, e.g. v3.2
916
+ oversion=get_last_version(dir_path=dir_path, version_only=False) # This will return full path, e.g. /a/b/c/v3.2
917
+ ```
918
+
919
+ The function above should work for numeric (e.g. `v1.2`) and non-numeric (e.g. `va`, `vb`) versions.
920
+
859
921
  # Text manipulation
860
922
 
861
923
  ## Transformations
@@ -1,16 +1,17 @@
1
- data_manipulation_utilities-0.2.3.data/scripts/publish,sha256=-3K_Y2_4CfWCV50rPB8CRuhjxDu7xMGswinRwPovgLs,1976
1
+ data_manipulation_utilities-0.2.5.data/scripts/publish,sha256=-3K_Y2_4CfWCV50rPB8CRuhjxDu7xMGswinRwPovgLs,1976
2
2
  dmu/arrays/utilities.py,sha256=PKoYyybPptA2aU-V3KLnJXBudWxTXu4x1uGdIMQ49HY,1722
3
3
  dmu/generic/utilities.py,sha256=0Xnq9t35wuebAqKxbyAiMk1ISB7IcXK4cFH25MT1fgw,1741
4
+ dmu/generic/version_management.py,sha256=G_HjGY-hu8lotZuTdVAg0B8yD0AltE866q2vJxvTg1g,3749
4
5
  dmu/logging/log_store.py,sha256=umdvjNDuV3LdezbG26b0AiyTglbvkxST19CQu9QATbA,4184
5
- dmu/ml/cv_classifier.py,sha256=8Jwx6xMhJaRLktlRdq0tFl32v6t8i63KmpxrlnXlomU,3759
6
- dmu/ml/cv_predict.py,sha256=4G7F_1yOvnLftsDC6zUpdvkxuHXGkPemhj0RsYySYDM,6708
7
- dmu/ml/train_mva.py,sha256=SZ5cQHl7HBxn0c5Hh4HlN1aqMZaJUAlNmsfjnUSQrTg,16894
8
- dmu/ml/utilities.py,sha256=l348bufD95CuSYdIrHScQThIy2nKwGKXZn-FQg3CEwg,3930
6
+ dmu/ml/cv_classifier.py,sha256=ZbzEm_jW9yoTC7k_xBA7hFpc1bDNayiVR3tbaj1_ieE,4228
7
+ dmu/ml/cv_predict.py,sha256=4wwYL_jcUExDqLJVfClxEUWSd_QAx8yKHO3rX-mx4vw,6711
8
+ dmu/ml/train_mva.py,sha256=XzXE92PzyF3cjlx5yMhtp5h4t7wzisRAyO1fBArssvc,17282
9
+ dmu/ml/utilities.py,sha256=PK_61fW7gBV9aGZyez3PI8zAT7_Fc6IlQzDB7f8iBTM,4133
9
10
  dmu/pdataframe/utilities.py,sha256=ypvLiFfJ82ga94qlW3t5dXnvEFwYOXnbtJb2zHwsbqk,987
10
11
  dmu/plotting/matrix.py,sha256=pXuUJn-LgOvrI9qGkZQw16BzLjOjeikYQ_ll2VIcIXU,4978
11
- dmu/plotting/plotter.py,sha256=ytMxtzHEY8ZFU0ZKEBE-ROjMszXl5kHTMnQnWe173nU,7208
12
- dmu/plotting/plotter_1d.py,sha256=g6H2xAgsL9a6vRkpbqHICb3qwV_qMiQPZxxw_oOSf9M,5115
13
- dmu/plotting/plotter_2d.py,sha256=J-gKnagoHGfJFU7HBrhDFpGYH5Rxy0_zF5l8eE_7ZHE,2944
12
+ dmu/plotting/plotter.py,sha256=3WRbNOrFBWgI3iW5TbEgT4w_eF7-XUPs_32JL1AW3yY,7359
13
+ dmu/plotting/plotter_1d.py,sha256=2AnVxulyhKtwN-2Srhfm6fqdEREZNhcpJolBsJrWcsc,5745
14
+ dmu/plotting/plotter_2d.py,sha256=mZhp3D5I-JodOnFTEF1NqHtcLtuI-2WNpCQsrsoXNtw,3017
14
15
  dmu/plotting/utilities.py,sha256=SI9dvtZq2gr-PXVz71KE4o0i09rZOKgqJKD1jzf6KXk,1167
15
16
  dmu/rdataframe/atr_mgr.py,sha256=FdhaQWVpsm4OOe1IRbm7rfrq8VenTNdORyI-lZ2Bs1M,2386
16
17
  dmu/rdataframe/utilities.py,sha256=pNcQARMP7txMhy6k27UnDcYf0buNy5U2fshaJDl_h8o,3661
@@ -20,20 +21,22 @@ dmu/stats/fitter.py,sha256=vHNZ16U3apoQyeyM8evq-if49doF48sKB3q9wmA96Fw,18387
20
21
  dmu/stats/function.py,sha256=yzi_Fvp_ASsFzbWFivIf-comquy21WoeY7is6dgY0Go,9491
21
22
  dmu/stats/gof_calculator.py,sha256=4EN6OhULcztFvsAZ00rxgohJemnjtDNB5o0IBcv6kbk,4657
22
23
  dmu/stats/minimizers.py,sha256=f9cilFY9Kp9UvbSIUsKBGFzOOg7EEWZJLPod-4k-LAQ,6216
23
- dmu/stats/model_factory.py,sha256=LyDOf0f9I5dNUTS0MXHtSivD8aAcTLIagvMPtoXtThk,7426
24
+ dmu/stats/model_factory.py,sha256=ixWnhE8gPiOYW5pCb3eoVIaSvbUopEx4ldkZ3xL54Xg,7714
24
25
  dmu/stats/utilities.py,sha256=LQy4kd3xSXqpApcWuYfZxkGQyjowaXv2Wr1c4Bj-4ys,4523
25
26
  dmu/stats/zfit_plotter.py,sha256=Xs6kisNEmNQXhYRCcjowxO6xHuyAyrfyQIFhGAR61U4,19719
26
- dmu/testing/utilities.py,sha256=WbMM4e9Cn3-B-12Vr64mB5qTKkV32joStlRkD-48lG0,3460
27
+ dmu/testing/utilities.py,sha256=moImLqGX9LAt5zJtE5j0gHHkUJ5kpbodryhiVswOsyM,3696
27
28
  dmu/text/transformer.py,sha256=4lrGknbAWRm0-rxbvgzOO-eR1-9bkYk61boJUEV3cQ0,6100
28
29
  dmu_data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
- dmu_data/ml/tests/train_mva.yaml,sha256=k5H4Gu9Gj57B9iqabhcTQEFN674Cv_uJ2Xcumb02zF4,1279
30
- dmu_data/plotting/tests/2d.yaml,sha256=VApcAfJFbjNcjMCTBSRm2P37MQlGavMZv6msbZwLSgw,402
30
+ dmu_data/ml/tests/train_mva.yaml,sha256=o0ZIe43qPC-KwLT9y1qfYYw2bbOLlJIKRkCMUnM5sBo,1177
31
+ dmu_data/plotting/tests/2d.yaml,sha256=HSAtER-8CEqIGBY_jdcIdSVOHMfYPYhmgeZghTpVYh8,516
31
32
  dmu_data/plotting/tests/fig_size.yaml,sha256=7ROq49nwZ1A2EbPiySmu6n3G-Jq6YAOkc3d2X3YNZv0,294
32
33
  dmu_data/plotting/tests/high_stat.yaml,sha256=bLglBLCZK6ft0xMhQ5OltxE76cWsBMPMjO6GG0OkDr8,522
34
+ dmu_data/plotting/tests/legend.yaml,sha256=wGpj58ig-GOlqbWoN894zrCet2Fj9f5QtY0rig_UC-c,213
33
35
  dmu_data/plotting/tests/name.yaml,sha256=mkcPAVg8wBAmlSbSRQ1bcaMl4vOS6LXMtpqQeDrrtO4,312
34
36
  dmu_data/plotting/tests/no_bounds.yaml,sha256=8e1QdphBjz-suDr857DoeUC2DXiy6SE-gvkORJQYv80,257
35
37
  dmu_data/plotting/tests/normalized.yaml,sha256=Y0eKtyV5pvlSxvqfsLjytYtv8xYF3HZ5WEdCJdeHGQI,193
36
38
  dmu_data/plotting/tests/simple.yaml,sha256=N_TvNBh_2dU0-VYgu_LMrtY0kV_hg2HxVuEoDlr1HX8,138
39
+ dmu_data/plotting/tests/stats.yaml,sha256=fSZjoV-xPnukpCH2OAXsz_SNPjI113qzDg8Ln3spaaA,165
37
40
  dmu_data/plotting/tests/title.yaml,sha256=bawKp9aGpeRrHzv69BOCbFX8sq9bb3Es9tdsPTE7jIk,333
38
41
  dmu_data/plotting/tests/weights.yaml,sha256=RWQ1KxbCq-uO62WJ2AoY4h5Umc37zG35s-TpKnNMABI,312
39
42
  dmu_data/text/transform.toml,sha256=R-832BZalzHZ6c5gD6jtT_Hj8BCsM5vxa1v6oeiwaP4,94
@@ -47,8 +50,8 @@ dmu_scripts/rfile/compare_root_files.py,sha256=T8lDnQxsRNMr37x1Y7YvWD8ySHrJOWZki
47
50
  dmu_scripts/rfile/print_trees.py,sha256=Ze4Ccl_iUldl4eVEDVnYBoe4amqBT1fSBR1zN5WSztk,941
48
51
  dmu_scripts/ssh/coned.py,sha256=lhilYNHWRCGxC-jtyJ3LQ4oUgWW33B2l1tYCcyHHsR0,4858
49
52
  dmu_scripts/text/transform_text.py,sha256=9akj1LB0HAyopOvkLjNOJiptZw5XoOQLe17SlcrGMD0,1456
50
- data_manipulation_utilities-0.2.3.dist-info/METADATA,sha256=STJ7vYfcSIM9dtMRzywGLwDzH1sUBE5DL9FqvskMcxo,27923
51
- data_manipulation_utilities-0.2.3.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
52
- data_manipulation_utilities-0.2.3.dist-info/entry_points.txt,sha256=1TIZDed651KuOH-DgaN5AoBdirKmrKE_oM1b6b7zTUU,270
53
- data_manipulation_utilities-0.2.3.dist-info/top_level.txt,sha256=n_x5J6uWtSqy9mRImKtdA2V2NJNyU8Kn3u8DTOKJix0,25
54
- data_manipulation_utilities-0.2.3.dist-info/RECORD,,
53
+ data_manipulation_utilities-0.2.5.dist-info/METADATA,sha256=d8rJbrtHEg_fOma5NA5qL4ox8bP4MaIV0mbyl6uRiJs,30104
54
+ data_manipulation_utilities-0.2.5.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
55
+ data_manipulation_utilities-0.2.5.dist-info/entry_points.txt,sha256=1TIZDed651KuOH-DgaN5AoBdirKmrKE_oM1b6b7zTUU,270
56
+ data_manipulation_utilities-0.2.5.dist-info/top_level.txt,sha256=n_x5J6uWtSqy9mRImKtdA2V2NJNyU8Kn3u8DTOKJix0,25
57
+ data_manipulation_utilities-0.2.5.dist-info/RECORD,,
@@ -0,0 +1,132 @@
1
+ '''
2
+ Module containing functions used to find latest, next version, etc of a path.
3
+ '''
4
+
5
+ import glob
6
+ import os
7
+ import re
8
+
9
+ from dmu.logging.log_store import LogStore
10
+
11
+ log=LogStore.add_logger('dmu:version_management')
12
+ #---------------------------------------
13
+ def _get_numeric_version(version : str) -> int:
14
+ '''
15
+ Takes string with numbers at the end (padded or not)
16
+ Returns integer version of numbers
17
+ '''
18
+ #Skip these directories
19
+ if version in ['__pycache__']:
20
+ return -1
21
+
22
+ regex=r'[a-z]+(\d+)'
23
+ mtch =re.match(regex, version)
24
+ if not mtch:
25
+ log.debug(f'Cannot extract numeric version from: {version}')
26
+ return -1
27
+
28
+ str_val = mtch.group(1)
29
+ val = int(str_val)
30
+
31
+ return val
32
+ #---------------------------------------
33
+ def get_last_version(dir_path : str, version_only : bool = True, main_only : bool = False):
34
+ '''Returns path or just version associated to latest version found in given path
35
+
36
+ Parameters
37
+ ---------------------
38
+ dir_path (str) : Path to directory where versioned subdirectories exist
39
+ version_only (bool): Returns only vxxxx if True, otherwise, full path to directory
40
+ main_only (bool): Returns vX where X is a number. Otherwise it will return vx.y in case version has subversion
41
+ '''
42
+ l_obj = glob.glob(f'{dir_path}/*')
43
+
44
+ if len(l_obj) == 0:
45
+ log.error(f'Nothing found in {dir_path}')
46
+ raise ValueError
47
+
48
+ d_dir_org = { os.path.basename(obj).replace('.', '') : obj for obj in l_obj if os.path.isdir(obj) }
49
+ d_dir_num = { _get_numeric_version(name) : dir_path for name, dir_path in d_dir_org.items() }
50
+
51
+ c_dir = sorted(d_dir_num.items())
52
+
53
+ try:
54
+ _, path = c_dir[-1]
55
+ except:
56
+ log.error(f'Cannot find path in: {dir_path}')
57
+ raise
58
+
59
+ name = os.path.basename(path)
60
+ dirn = os.path.dirname(path)
61
+
62
+ if main_only and '.' in name:
63
+ ind = name.index('.')
64
+ name= name[:ind]
65
+
66
+ if version_only:
67
+ return name
68
+
69
+ return f'{dirn}/{name}'
70
+ #---------------------------------------
71
+ def get_latest_file(dir_path : str, wc : str) -> str:
72
+ '''Will find latest file in a given directory
73
+
74
+ Parameters
75
+ --------------------
76
+ dir_path (str): Directory where files are found
77
+ wc (str): Wildcard associated to files, e.g. file_*.txt
78
+
79
+ Returns
80
+ --------------------
81
+ Path to latest file, according to version
82
+ '''
83
+ l_path = glob.glob(f'{dir_path}/{wc}')
84
+ if len(l_path) == 0:
85
+ log.error(f'Cannot find files in: {dir_path}/{wc}')
86
+ raise ValueError
87
+
88
+ l_path.sort()
89
+
90
+ return l_path[-1]
91
+ #---------------------------------------
92
+ def get_next_version(version : str) -> str:
93
+ '''Pick up string symbolizing version and return next version
94
+ Parameters
95
+ -------------------------
96
+ version (str) : Of the form vx.y or vx where x and y are integers. It can also be a full path
97
+
98
+ Returns
99
+ -------------------------
100
+ String equal to the argument, but with the main version augmented by 1, e.g. vx+1.y
101
+
102
+ Examples:
103
+ -------------------------
104
+
105
+ get_next_version('v1.1') = 'v2.1'
106
+ get_next_version('v1' ) = 'v2'
107
+ '''
108
+ if '/' in version:
109
+ path = version
110
+ dirname = os.path.dirname(path)
111
+ version = os.path.basename(path)
112
+ else:
113
+ dirname = None
114
+
115
+ rgx = r'v(\d+)(\.\d+)?'
116
+
117
+ mtch = re.match(rgx, version)
118
+ if not mtch:
119
+ log.error(f'Cannot match {version} with {rgx}')
120
+ raise ValueError
121
+
122
+ ver_org = mtch.group(1)
123
+ ver_nxt = int(ver_org) + 1
124
+ ver_nxt = str(ver_nxt)
125
+
126
+ version = version.replace(f'v{ver_org}', f'v{ver_nxt}')
127
+
128
+ if dirname is not None:
129
+ version = f'{dirname}/{version}'
130
+
131
+ return version
132
+ #---------------------------------------
dmu/ml/cv_classifier.py CHANGED
@@ -1,15 +1,15 @@
1
1
  '''
2
2
  Module holding cv_classifier class
3
3
  '''
4
-
4
+ import os
5
5
  from typing import Union
6
6
  from sklearn.ensemble import GradientBoostingClassifier
7
7
 
8
+ import yaml
8
9
  from dmu.logging.log_store import LogStore
9
10
  import dmu.ml.utilities as ut
10
11
 
11
12
  log = LogStore.add_logger('dmu:ml:CVClassifier')
12
-
13
13
  # ---------------------------------------
14
14
  class CVSameData(Exception):
15
15
  '''
@@ -61,6 +61,20 @@ class CVClassifier(GradientBoostingClassifier):
61
61
 
62
62
  return self._cfg
63
63
  # ----------------------------------
64
+ def save_cfg(self, path : str):
65
+ '''
66
+ Will save configuration used to train this classifier to YAML
67
+
68
+ path: Path to YAML file
69
+ '''
70
+ dir_name = os.path.dirname(path)
71
+ os.makedirs(dir_name, exist_ok=True)
72
+
73
+ with open(path, 'w', encoding='utf-8') as ofile:
74
+ yaml.safe_dump(self._cfg, ofile, indent=2)
75
+
76
+ log.info(f'Saved config to: {path}')
77
+ # ----------------------------------
64
78
  def __str__(self):
65
79
  nhash = len(self._s_hash)
66
80
 
dmu/ml/cv_predict.py CHANGED
@@ -73,11 +73,11 @@ class CVPredict:
73
73
  log.debug('Not doing any NaN replacement')
74
74
  return df
75
75
 
76
- log.debug(60 * '-')
76
+ log.info(60 * '-')
77
77
  log.info('Doing NaN replacements')
78
- log.debug(60 * '-')
78
+ log.info(60 * '-')
79
79
  for var, val in self._d_nan_rep.items():
80
- log.debug(f'{var:<20}{"--->":20}{val:<20.3f}')
80
+ log.info(f'{var:<20}{"--->":20}{val:<20.3f}')
81
81
  df[var] = df[var].fillna(val)
82
82
 
83
83
  return df
@@ -155,7 +155,7 @@ class CVPredict:
155
155
  ndif = len(s_dif_hash)
156
156
  ndat = len(s_dat_hash)
157
157
  nmod = len(s_mod_hash)
158
- log.debug(f'{ndif:<20}{"=":10}{ndat:<20}{"-":10}{nmod:<20}')
158
+ log.debug(f'{ndif:<10}{"=":5}{ndat:<10}{"-":5}{nmod:<10}')
159
159
 
160
160
  df_ft_group= df_ft.loc[df_ft.index.isin(s_dif_hash)]
161
161
 
@@ -173,7 +173,7 @@ class CVPredict:
173
173
  return arr_prb
174
174
 
175
175
  nentries = len(self._arr_patch)
176
- log.warning(f'Patching {nentries} probabilities')
176
+ log.warning(f'Patching {nentries} probabilities with -1')
177
177
  arr_prb[self._arr_patch] = -1
178
178
 
179
179
  return arr_prb
dmu/ml/train_mva.py CHANGED
@@ -69,14 +69,20 @@ class TrainMva:
69
69
  return df, arr_lab
70
70
  # ---------------------------------------------
71
71
  def _pre_process_nans(self, df : pnd.DataFrame) -> pnd.DataFrame:
72
+ if 'dataset' not in self._cfg:
73
+ return df
74
+
72
75
  if 'nan' not in self._cfg['dataset']:
73
76
  log.debug('dataset/nan section not found, not pre-processing NaNs')
74
77
  return df
75
78
 
76
79
  d_name_val = self._cfg['dataset']['nan']
77
- for name, val in d_name_val.items():
78
- log.debug(f'{val:<20}{"<---":<10}{name:<100}')
79
- df[name] = df[name].fillna(val)
80
+ log.info(60 * '-')
81
+ log.info('Doing NaN replacements')
82
+ log.info(60 * '-')
83
+ for var, val in d_name_val.items():
84
+ log.info(f'{var:<20}{"--->":20}{val:<20.3f}')
85
+ df[var] = df[var].fillna(val)
80
86
 
81
87
  return df
82
88
  # ---------------------------------------------
@@ -406,6 +412,9 @@ class TrainMva:
406
412
  self._save_hyperparameters_to_tex()
407
413
  # ---------------------------------------------
408
414
  def _save_nan_conversion(self) -> None:
415
+ if 'dataset' not in self._cfg:
416
+ return
417
+
409
418
  if 'nan' not in self._cfg['dataset']:
410
419
  log.debug('NaN section not found, not saving it')
411
420
  return
@@ -434,13 +443,18 @@ class TrainMva:
434
443
  os.makedirs(val_dir, exist_ok=True)
435
444
  put.df_to_tex(df, f'{val_dir}/hyperparameters.tex')
436
445
  # ---------------------------------------------
437
- def run(self):
446
+ def run(self, skip_fit : bool = False) -> None:
438
447
  '''
439
448
  Will do the training
449
+
450
+ skip_fit: By default false, if True, it will only do the plots of features and save tables
440
451
  '''
441
452
  self._save_settings_to_tex()
442
453
  self._plot_features()
443
454
 
455
+ if skip_fit:
456
+ return
457
+
444
458
  l_mod = self._get_models()
445
459
  for ifold, mod in enumerate(l_mod):
446
460
  self._save_model(mod, ifold)
dmu/ml/utilities.py CHANGED
@@ -16,7 +16,7 @@ log = LogStore.add_logger('dmu:ml:utilities')
16
16
  # ---------------------------------------------
17
17
  def patch_and_tag(df : pnd.DataFrame, value : float = 0) -> pnd.DataFrame:
18
18
  '''
19
- Takes panda dataframe, replaces NaNs with value introduced, by default 0
19
+ Takes pandas dataframe, replaces NaNs with value introduced, by default 0
20
20
  Returns array of indices where the replacement happened
21
21
  '''
22
22
  l_nan = df.index[df.isna().any(axis=1)].tolist()
@@ -25,7 +25,13 @@ def patch_and_tag(df : pnd.DataFrame, value : float = 0) -> pnd.DataFrame:
25
25
  log.debug('No NaNs found')
26
26
  return df
27
27
 
28
- log.warning(f'Found {nnan} NaNs, patching them with {value}')
28
+ log.warning(f'Found {nnan} NaNs')
29
+
30
+ df_nan_frq = df.isna().sum()
31
+ df_nan_frq = df_nan_frq[df_nan_frq > 0]
32
+ print(df_nan_frq)
33
+
34
+ log.warning(f'Attaching array with NaN {nnan} indexes and removing NaNs from dataframe')
29
35
 
30
36
  df_pa = df.fillna(value)
31
37
 
@@ -57,7 +63,7 @@ def _remove_nans(df : pnd.DataFrame) -> pnd.DataFrame:
57
63
  log.info('Found columns with NaNs')
58
64
  for name in l_na_name:
59
65
  nan_count = df[name].isna().sum()
60
- log.info(f'{nan_count:<10}{name:<100}')
66
+ log.info(f'{nan_count:<10}{name}')
61
67
 
62
68
  ninit = len(df)
63
69
  df = df.dropna()
@@ -75,10 +81,10 @@ def _remove_repeated(df : pnd.DataFrame) -> pnd.DataFrame:
75
81
  nfinl = len(s_hash)
76
82
 
77
83
  if ninit == nfinl:
78
- log.debug('No cleaning needed for dataframe')
84
+ log.debug('No overlap between training and application found')
79
85
  return df
80
86
 
81
- log.warning(f'Repeated entries found, cleaning up: {ninit} -> {nfinl}')
87
+ log.warning(f'Overlap between training and application found, cleaning up: {ninit} -> {nfinl}')
82
88
 
83
89
  df['hash_index'] = l_hash
84
90
  df = df.set_index('hash_index', drop=True)
dmu/plotting/plotter.py CHANGED
@@ -107,7 +107,7 @@ class Plotter:
107
107
 
108
108
  d_cut = self._d_cfg['selection']['cuts']
109
109
 
110
- log.info('Applying cuts')
110
+ log.debug('Applying cuts')
111
111
  for name, cut in d_cut.items():
112
112
  log.debug(f'{name:<50}{cut:<150}')
113
113
  rdf = rdf.Filter(cut, name)
@@ -212,7 +212,11 @@ class Plotter:
212
212
 
213
213
  var (str) : Name of variable, needed for plot name
214
214
  '''
215
- plt.legend()
215
+ d_leg = {}
216
+ if 'style' in self._d_cfg and 'legend' in self._d_cfg['style']:
217
+ d_leg = self._d_cfg['style']['legend']
218
+
219
+ plt.legend(**d_leg)
216
220
 
217
221
  plt_dir = self._d_cfg['saving']['plt_dir']
218
222
  os.makedirs(plt_dir, exist_ok=True)
@@ -77,17 +77,33 @@ class Plotter1D(Plotter):
77
77
 
78
78
  l_bc_all = []
79
79
  for name, arr_val in d_data.items():
80
+ label = self._label_from_name(name, arr_val)
80
81
  arr_wgt = d_wgt[name] if d_wgt is not None else numpy.ones_like(arr_val)
81
82
  arr_wgt = self._normalize_weights(arr_wgt, var)
82
- hst = Hist.new.Reg(bins=bins, start=minx, stop=maxx, name='x', label=name).Weight()
83
+ hst = Hist.new.Reg(bins=bins, start=minx, stop=maxx, name='x').Weight()
83
84
  hst.fill(x=arr_val, weight=arr_wgt)
84
- hst.plot(label=name)
85
+ hst.plot(label=label)
85
86
  l_bc_all += hst.values().tolist()
86
87
 
87
88
  max_y = max(l_bc_all)
88
89
 
89
90
  return max_y
90
91
  # --------------------------------------------
92
+ def _label_from_name(self, name : str, arr_val : numpy.ndarray) -> str:
93
+ if 'stats' not in self._d_cfg:
94
+ return name
95
+
96
+ d_stat = self._d_cfg['stats']
97
+ if 'nentries' not in d_stat:
98
+ return name
99
+
100
+ form = d_stat['nentries']
101
+
102
+ nentries = len(arr_val)
103
+ nentries = form.format(nentries)
104
+
105
+ return f'{name}{nentries}'
106
+ # --------------------------------------------
91
107
  def _normalize_weights(self, arr_wgt : numpy.ndarray, var : str) -> numpy.ndarray:
92
108
  cfg_var = self._d_cfg['plots'][var]
93
109
  if 'normalized' not in cfg_var:
@@ -104,7 +120,6 @@ class Plotter1D(Plotter):
104
120
 
105
121
  return arr_wgt
106
122
  # --------------------------------------------
107
-
108
123
  def _style_plot(self, var : str, max_y : float) -> None:
109
124
  d_cfg = self._d_cfg['plots'][var]
110
125
  yscale = d_cfg['yscale' ] if 'yscale' in d_cfg else 'linear'
@@ -124,12 +139,15 @@ class Plotter1D(Plotter):
124
139
  plt.legend()
125
140
  plt.title(title)
126
141
  # --------------------------------------------
127
- def _plot_lines(self, var : str):
142
+ def _plot_lines(self, var : str) -> None:
128
143
  '''
129
144
  Will plot vertical lines for some variables
130
145
 
131
146
  var (str) : name of variable
132
147
  '''
148
+ if 'style' in self._d_cfg and 'skip_lines' in self._d_cfg['style'] and self._d_cfg['style']['skip_lines']:
149
+ return
150
+
133
151
  if var in ['B_const_mass_M', 'B_M']:
134
152
  plt.axvline(x=5280, color='r', label=r'$B^+$' , linestyle=':')
135
153
  elif var == 'Jpsi_M':
@@ -10,6 +10,7 @@ import matplotlib.pyplot as plt
10
10
 
11
11
  from hist import Hist
12
12
  from ROOT import RDataFrame
13
+ from matplotlib.colors import LogNorm
13
14
  from dmu.logging.log_store import LogStore
14
15
  from dmu.plotting.plotter import Plotter
15
16
 
@@ -28,11 +29,8 @@ class Plotter2D(Plotter):
28
29
  cfg (dict): Dictionary with configuration, e.g. binning, ranges, etc
29
30
  '''
30
31
 
31
- if not isinstance(cfg, dict):
32
- raise ValueError('Config dictionary not passed')
33
-
34
- self._d_cfg : dict = cfg
35
- self._rdf : RDataFrame = super()._preprocess_rdf(rdf)
32
+ super().__init__({'single_rdf' : rdf}, cfg)
33
+ self._rdf : RDataFrame = self._d_rdf['single_rdf']
36
34
 
37
35
  self._wgt : numpy.ndarray
38
36
  # --------------------------------------------
@@ -61,7 +59,7 @@ class Plotter2D(Plotter):
61
59
 
62
60
  return arr_wgt
63
61
  # --------------------------------------------
64
- def _plot_vars(self, varx : str, vary : str, wgt_name : str) -> None:
62
+ def _plot_vars(self, varx : str, vary : str, wgt_name : str, use_log : bool) -> None:
65
63
  log.info(f'Plotting {varx} vs {vary} with weights {wgt_name}')
66
64
 
67
65
  ax_x = self._get_axis(varx)
@@ -72,7 +70,10 @@ class Plotter2D(Plotter):
72
70
  hst = Hist(ax_x, ax_y)
73
71
  hst.fill(arr_x, arr_y, weight=arr_w)
74
72
 
75
- mplhep.hist2dplot(hst)
73
+ if use_log:
74
+ mplhep.hist2dplot(hst, norm=LogNorm())
75
+ else:
76
+ mplhep.hist2dplot(hst)
76
77
  # --------------------------------------------
77
78
  def run(self):
78
79
  '''
@@ -80,8 +81,8 @@ class Plotter2D(Plotter):
80
81
  '''
81
82
 
82
83
  fig_size = self._get_fig_size()
83
- for [varx, vary, wgt_name, plot_name] in self._d_cfg['plots_2d']:
84
+ for [varx, vary, wgt_name, plot_name, use_log] in self._d_cfg['plots_2d']:
84
85
  plt.figure(plot_name, figsize=fig_size)
85
- self._plot_vars(varx, vary, wgt_name)
86
+ self._plot_vars(varx, vary, wgt_name, use_log)
86
87
  self._save_plot(plot_name)
87
88
  # --------------------------------------------
@@ -1,7 +1,7 @@
1
1
  '''
2
2
  Module storing ZModel class
3
3
  '''
4
- # pylint: disable=too-many-lines, import-error
4
+ # pylint: disable=too-many-lines, import-error, too-many-positional-arguments, too-many-arguments
5
5
 
6
6
  from typing import Callable, Union
7
7
 
@@ -69,12 +69,18 @@ class ModelFactory:
69
69
 
70
70
  self._d_par : dict[str,zpar] = {}
71
71
  #-----------------------------------------
72
+ def _fltname_from_name(self, name : str) -> str:
73
+ if name in ['mu', 'sg']:
74
+ return f'{name}_flt'
75
+
76
+ return name
77
+ #-----------------------------------------
72
78
  def _get_name(self, name : str, suffix : str) -> str:
73
79
  for can_be_shared in self._l_can_be_shared:
74
80
  if name.startswith(f'{can_be_shared}_') and can_be_shared in self._l_shr:
75
- return can_be_shared
81
+ return self._fltname_from_name(can_be_shared)
76
82
 
77
- return f'{name}{suffix}'
83
+ return self._fltname_from_name(f'{name}{suffix}')
78
84
  #-----------------------------------------
79
85
  def _get_parameter(self,
80
86
  name : str,
@@ -129,8 +135,8 @@ class ModelFactory:
129
135
  def _get_cbl(self, suffix : str = '') -> zpdf:
130
136
  mu = self._get_parameter('mu_cbl', suffix, 5300, 5250, 5350)
131
137
  sg = self._get_parameter('sg_cbl', suffix, 10, 2, 300)
132
- al = self._get_parameter('ac_cbl', suffix, 2, 1., 4.)
133
- nl = self._get_parameter('nc_cbl', suffix, 1, 0.5, 5.0)
138
+ al = self._get_parameter('ac_cbl', suffix, 2, 1., 14.)
139
+ nl = self._get_parameter('nc_cbl', suffix, 1, 0.5, 15.)
134
140
 
135
141
  pdf = zfit.pdf.CrystalBall(mu, sg, al, nl, self._obs)
136
142
 
@@ -151,8 +157,8 @@ class ModelFactory:
151
157
  sg = self._get_parameter('sg_dscb', suffix, 10, 2, 30)
152
158
  ar = self._get_parameter('ar_dscb', suffix, 1, 0, 5)
153
159
  al = self._get_parameter('al_dscb', suffix, 1, 0, 5)
154
- nr = self._get_parameter('nr_dscb', suffix, 2, 1, 5)
155
- nl = self._get_parameter('nl_dscb', suffix, 2, 0, 5)
160
+ nr = self._get_parameter('nr_dscb', suffix, 2, 1, 15)
161
+ nl = self._get_parameter('nl_dscb', suffix, 2, 0, 15)
156
162
 
157
163
  pdf = zfit.pdf.DoubleCB(mu, sg, al, nl, ar, nr, self._obs)
158
164
 
dmu/testing/utilities.py CHANGED
@@ -2,6 +2,7 @@
2
2
  Module containing utility functions needed by unit tests
3
3
  '''
4
4
  import os
5
+ import math
5
6
  from typing import Union
6
7
  from dataclasses import dataclass
7
8
  from importlib.resources import files
@@ -21,56 +22,64 @@ class Data:
21
22
  '''
22
23
  Class storing shared data
23
24
  '''
24
- nentries = 3000
25
25
  # -------------------------------
26
- def _double_data(d_data : dict) -> dict:
27
- df_1 = pnd.DataFrame(d_data)
28
- df_2 = pnd.DataFrame(d_data)
29
-
26
+ def _double_data(df_1 : pnd.DataFrame) -> pnd.DataFrame:
27
+ df_2 = df_1.copy()
30
28
  df = pnd.concat([df_1, df_2], axis=0)
31
29
 
32
- d_data = { name : df[name].to_numpy() for name in df.columns }
33
-
34
- return d_data
30
+ return df
35
31
  # -------------------------------
36
- def _add_nans(d_data : dict) -> dict:
37
- df_good = pnd.DataFrame(d_data)
38
- df_bad = pnd.DataFrame(d_data)
39
- df_bad[:] = numpy.nan
32
+ def _add_nans(df : pnd.DataFrame, columns : list[str]) -> pnd.DataFrame:
33
+ size = len(df) * 0.2
34
+ size = math.floor(size)
35
+
36
+ l_col = df.columns.tolist()
37
+ if columns is None:
38
+ l_col_index = range(len(l_col))
39
+ else:
40
+ l_col_index = [ l_col.index(column) for column in columns ]
40
41
 
41
- df = pnd.concat([df_good, df_bad])
42
- d_data = { name : df[name].to_numpy() for name in df.columns }
42
+ log.debug('Replacing randomly with {size} NaNs')
43
+ for _ in range(size):
44
+ irow = numpy.random.randint(0, df.shape[0]) # Random row index
45
+ icol = numpy.random.choice(l_col_index) # Random column index
43
46
 
44
- return d_data
47
+ df.iat[irow, icol] = numpy.nan
48
+
49
+ return df
45
50
  # -------------------------------
46
51
  def get_rdf(kind : Union[str,None] = None,
47
52
  repeated : bool = False,
48
- add_nans : bool = False):
53
+ nentries : int = 3_000,
54
+ add_nans : list[str] = None):
49
55
  '''
50
56
  Return ROOT dataframe with toy data
51
57
  '''
58
+
52
59
  d_data = {}
53
60
  if kind == 'sig':
54
- d_data['w'] = numpy.random.normal(0, 1, size=Data.nentries)
55
- d_data['x'] = numpy.random.normal(0, 1, size=Data.nentries)
56
- d_data['y'] = numpy.random.normal(0, 1, size=Data.nentries)
57
- d_data['z'] = numpy.random.normal(0, 1, size=Data.nentries)
61
+ d_data['w'] = numpy.random.normal(0, 1, size=nentries)
62
+ d_data['x'] = numpy.random.normal(0, 1, size=nentries)
63
+ d_data['y'] = numpy.random.normal(0, 1, size=nentries)
64
+ d_data['z'] = numpy.random.normal(0, 1, size=nentries)
58
65
  elif kind == 'bkg':
59
- d_data['w'] = numpy.random.normal(1, 1, size=Data.nentries)
60
- d_data['x'] = numpy.random.normal(1, 1, size=Data.nentries)
61
- d_data['y'] = numpy.random.normal(1, 1, size=Data.nentries)
62
- d_data['z'] = numpy.random.normal(1, 1, size=Data.nentries)
66
+ d_data['w'] = numpy.random.normal(1, 1, size=nentries)
67
+ d_data['x'] = numpy.random.normal(1, 1, size=nentries)
68
+ d_data['y'] = numpy.random.normal(1, 1, size=nentries)
69
+ d_data['z'] = numpy.random.normal(1, 1, size=nentries)
63
70
  else:
64
71
  log.error(f'Invalid kind: {kind}')
65
72
  raise ValueError
66
73
 
74
+ df = pnd.DataFrame(d_data)
75
+
67
76
  if repeated:
68
- d_data = _double_data(d_data)
77
+ df = _double_data(df)
69
78
 
70
79
  if add_nans:
71
- d_data = _add_nans(d_data)
80
+ df = _add_nans(df, columns=add_nans)
72
81
 
73
- rdf = RDF.FromNumpy(d_data)
82
+ rdf = RDF.FromPandas(df)
74
83
 
75
84
  return rdf
76
85
  # -------------------------------
@@ -1,6 +1,7 @@
1
1
  dataset:
2
2
  nan :
3
- x : 0
3
+ x : 1
4
+ y : 2
4
5
  training :
5
6
  nfold : 3
6
7
  features : [x, y, z]
@@ -33,10 +34,6 @@ plotting:
33
34
  saving:
34
35
  plt_dir : '/tmp/dmu/ml/tests/train_mva/features'
35
36
  plots:
36
- w :
37
- binning : [-4, 4, 100]
38
- yscale : 'linear'
39
- labels : ['w', '']
40
37
  x :
41
38
  binning : [-4, 4, 100]
42
39
  yscale : 'linear'
@@ -1,13 +1,17 @@
1
1
  saving:
2
- plt_dir : tests/plotting/2d_weighted
2
+ plt_dir : /tmp/dmu/tests/plotting/2d_weighted
3
+ selection:
4
+ cuts:
5
+ xlow : x > -1.5
3
6
  definitions:
4
7
  z : x + y
5
8
  general:
6
9
  size : [20, 10]
7
10
  plots_2d:
8
- - [x, y, weights, 'xy_w']
9
- - [x, y, null, 'xy_r']
10
- - [x, z, null, 'xz_r']
11
+ - [x, y, weights, 'xy_wgt', false]
12
+ - [x, y, null, 'xy_raw', false]
13
+ - [x, z, null, 'xz_raw', false]
14
+ - [x, z, null, 'xz_log', true]
11
15
  axes:
12
16
  x :
13
17
  binning : [-3.0, 3.0, 40]
@@ -0,0 +1,12 @@
1
+ saving:
2
+ plt_dir : tests/plotting/legend
3
+ general:
4
+ size : [20, 10]
5
+ plots:
6
+ x :
7
+ binning : [-5.0, 8.0, 40]
8
+ y :
9
+ binning : [-5.0, 8.0, 40]
10
+ style:
11
+ legend:
12
+ bbox_to_anchor : [1.2, 1]
@@ -0,0 +1,9 @@
1
+ saving:
2
+ plt_dir : tests/plotting/stats
3
+ plots:
4
+ x :
5
+ binning : [-5.0, 8.0, 40]
6
+ y :
7
+ binning : [-5.0, 8.0, 40]
8
+ stats:
9
+ nentries : '{:.2e}'