forked from Nicolas-Radomski/GenomicBasedRegression
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenomicBasedRegression.py
More file actions
2554 lines (2451 loc) · 132 KB
/
Copy pathGenomicBasedRegression.py
File metadata and controls
2554 lines (2451 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# required librairies
## pip3.12 install --force-reinstall pandas==2.2.2
## pip3.12 install --force-reinstall scipy==1.16.0
## pip3.12 install --force-reinstall scikit-learn==1.5.2
## pip3.12 install --force-reinstall catboost==1.2.8
## pip3.12 install --force-reinstall lightgbm==4.6.0
## pip3.12 install --force-reinstall xgboost==2.1.3
## pip3.12 install --force-reinstall numpy==1.26.4
## pip3.12 install --force-reinstall joblib==1.5.1
## pip3.12 install --force-reinstall tqdm==4.67.1
## pip3.12 install --force-reinstall tqdm-joblib==0.0.4
'''
# examples of commands with parameters
## without feature selection and with the ADA model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph phenotype_dataset.tsv -o MyDirectory -x ADA_FirstAnalysis -da random -sp 80 -q 10 -r ADA -k 5 -pa tuning_parameters_ADA.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/ADA_FirstAnalysis_features.obj -fe MyDirectory/ADA_FirstAnalysis_feature_encoder.obj -cf MyDirectory/ADA_FirstAnalysis_calibration_features.obj -ct MyDirectory/ADA_FirstAnalysis_calibration_targets.obj -t MyDirectory/ADA_FirstAnalysis_model.obj -o MyDirectory -x ADA_SecondAnalysis
## with the SKB feature selection and the BRI model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x BRI_FirstAnalysis -da manual -fs SKB -r BRI -k 5 -pa tuning_parameters_BRI.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/BRI_FirstAnalysis_features.obj -fe MyDirectory/BRI_FirstAnalysis_feature_encoder.obj -cf MyDirectory/BRI_FirstAnalysis_calibration_features.obj -ct MyDirectory/BRI_FirstAnalysis_calibration_targets.obj -t MyDirectory/BRI_FirstAnalysis_model.obj -o MyDirectory -x BRI_SecondAnalysis
## with the laSFM feature selection and the CAT model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x CAT_FirstAnalysis -da manual -fs laSFM -r CAT -k 5 -pa tuning_parameters_CAT.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/CAT_FirstAnalysis_features.obj -fe MyDirectory/CAT_FirstAnalysis_feature_encoder.obj -cf MyDirectory/CAT_FirstAnalysis_calibration_features.obj -ct MyDirectory/CAT_FirstAnalysis_calibration_targets.obj -t MyDirectory/CAT_FirstAnalysis_model.obj -o MyDirectory -x CAT_SecondAnalysis
## with the enSFM feature selection and the DT model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x DT_FirstAnalysis -da manual -fs enSFM -r DT -k 5 -pa tuning_parameters_DT.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/DT_FirstAnalysis_features.obj -fe MyDirectory/DT_FirstAnalysis_feature_encoder.obj -cf MyDirectory/DT_FirstAnalysis_calibration_features.obj -ct MyDirectory/DT_FirstAnalysis_calibration_targets.obj -t MyDirectory/DT_FirstAnalysis_model.obj -o MyDirectory -x DT_SecondAnalysis
## with the riSFM feature selection and the EN model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x EN_FirstAnalysis -da manual -fs riSFM -r EN -k 5 -pa tuning_parameters_EN.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/EN_FirstAnalysis_features.obj -fe MyDirectory/EN_FirstAnalysis_feature_encoder.obj -cf MyDirectory/EN_FirstAnalysis_calibration_features.obj -ct MyDirectory/EN_FirstAnalysis_calibration_targets.obj -t MyDirectory/EN_FirstAnalysis_model.obj -o MyDirectory -x EN_SecondAnalysis
## with the rfSFM feature selection and the ET model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x ET_FirstAnalysis -da manual -fs rfSFM -r ET -k 5 -pa tuning_parameters_ET.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/ET_FirstAnalysis_features.obj -fe MyDirectory/ET_FirstAnalysis_feature_encoder.obj -cf MyDirectory/ET_FirstAnalysis_calibration_features.obj -ct MyDirectory/ET_FirstAnalysis_calibration_targets.obj -t MyDirectory/ET_FirstAnalysis_model.obj -o MyDirectory -x ET_SecondAnalysis
## with the SKB feature selection and the GB model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x GB_FirstAnalysis -da manual -fs SKB -r GB -k 5 -pa tuning_parameters_GB.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/GB_FirstAnalysis_features.obj -fe MyDirectory/GB_FirstAnalysis_feature_encoder.obj -cf MyDirectory/GB_FirstAnalysis_calibration_features.obj -ct MyDirectory/GB_FirstAnalysis_calibration_targets.obj -t MyDirectory/GB_FirstAnalysis_model.obj -o MyDirectory -x GB_SecondAnalysis
## with the SKB feature selection and the HGB model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x HGB_FirstAnalysis -da manual -fs SKB -r HGB -k 5 -pa tuning_parameters_HGB.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/HGB_FirstAnalysis_features.obj -fe MyDirectory/HGB_FirstAnalysis_feature_encoder.obj -cf MyDirectory/HGB_FirstAnalysis_calibration_features.obj -ct MyDirectory/HGB_FirstAnalysis_calibration_targets.obj -t MyDirectory/HGB_FirstAnalysis_model.obj -o MyDirectory -x HGB_SecondAnalysis
## with the SKB feature selection and the HU model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x HU_FirstAnalysis -da manual -fs SKB -r HU -k 5 -pa tuning_parameters_HU.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/HU_FirstAnalysis_features.obj -fe MyDirectory/HU_FirstAnalysis_feature_encoder.obj -cf MyDirectory/HU_FirstAnalysis_calibration_features.obj -ct MyDirectory/HU_FirstAnalysis_calibration_targets.obj -t MyDirectory/HU_FirstAnalysis_model.obj -o MyDirectory -x HU_SecondAnalysis
## with the SKB feature selection and the KNN model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x KNN_FirstAnalysis -da manual -fs SKB -r KNN -k 5 -pa tuning_parameters_KNN.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/KNN_FirstAnalysis_features.obj -fe MyDirectory/KNN_FirstAnalysis_feature_encoder.obj -cf MyDirectory/KNN_FirstAnalysis_calibration_features.obj -ct MyDirectory/KNN_FirstAnalysis_calibration_targets.obj -t MyDirectory/KNN_FirstAnalysis_model.obj -o MyDirectory -x KNN_SecondAnalysis
## with the SKB feature selection and the LA model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x LA_FirstAnalysis -da manual -fs SKB -r LA -k 5 -pa tuning_parameters_LA.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/LA_FirstAnalysis_features.obj -fe MyDirectory/LA_FirstAnalysis_feature_encoder.obj -cf MyDirectory/LA_FirstAnalysis_calibration_features.obj -ct MyDirectory/LA_FirstAnalysis_calibration_targets.obj -t MyDirectory/LA_FirstAnalysis_model.obj -o MyDirectory -x LA_SecondAnalysis
## with the SKB feature selection and the LGBM model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x LGBM_FirstAnalysis -da manual -fs SKB -r LGBM -k 5 -pa tuning_parameters_LGBM.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/LGBM_FirstAnalysis_features.obj -fe MyDirectory/LGBM_FirstAnalysis_feature_encoder.obj -cf MyDirectory/LGBM_FirstAnalysis_calibration_features.obj -ct MyDirectory/LGBM_FirstAnalysis_calibration_targets.obj -t MyDirectory/LGBM_FirstAnalysis_model.obj -o MyDirectory -x LGBM_SecondAnalysis
## with the SKB feature selection and the MLP model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x MLP_FirstAnalysis -da manual -fs SKB -r MLP -k 5 -pa tuning_parameters_MLP.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/MLP_FirstAnalysis_features.obj -fe MyDirectory/MLP_FirstAnalysis_feature_encoder.obj -cf MyDirectory/MLP_FirstAnalysis_calibration_features.obj -ct MyDirectory/MLP_FirstAnalysis_calibration_targets.obj -t MyDirectory/MLP_FirstAnalysis_model.obj -o MyDirectory -x MLP_SecondAnalysis
## with the SKB feature selection and the NSV model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x NSV_FirstAnalysis -da manual -fs SKB -r NSV -k 5 -pa tuning_parameters_NSV.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/NSV_FirstAnalysis_features.obj -fe MyDirectory/NSV_FirstAnalysis_feature_encoder.obj -cf MyDirectory/NSV_FirstAnalysis_calibration_features.obj -ct MyDirectory/NSV_FirstAnalysis_calibration_targets.obj -t MyDirectory/NSV_FirstAnalysis_model.obj -o MyDirectory -x NSV_SecondAnalysis
## with the SKB feature selection and the PN model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x PN_FirstAnalysis -da manual -fs SKB -r PN -k 5 -pa tuning_parameters_PN.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/PN_FirstAnalysis_features.obj -fe MyDirectory/PN_FirstAnalysis_feature_encoder.obj -cf MyDirectory/PN_FirstAnalysis_calibration_features.obj -ct MyDirectory/PN_FirstAnalysis_calibration_targets.obj -t MyDirectory/PN_FirstAnalysis_model.obj -o MyDirectory -x PN_SecondAnalysis
## with the SKB feature selection and the RF model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x RF_FirstAnalysis -da manual -fs SKB -r RF -k 5 -pa tuning_parameters_RF.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/RF_FirstAnalysis_features.obj -fe MyDirectory/RF_FirstAnalysis_feature_encoder.obj -cf MyDirectory/RF_FirstAnalysis_calibration_features.obj -ct MyDirectory/RF_FirstAnalysis_calibration_targets.obj -t MyDirectory/RF_FirstAnalysis_model.obj -o MyDirectory -x RF_SecondAnalysis
## with the SKB feature selection and the RI model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x RI_FirstAnalysis -da manual -fs SKB -r RI -k 5 -pa tuning_parameters_RI.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/RI_FirstAnalysis_features.obj -fe MyDirectory/RI_FirstAnalysis_feature_encoder.obj -cf MyDirectory/RI_FirstAnalysis_calibration_features.obj -ct MyDirectory/RI_FirstAnalysis_calibration_targets.obj -t MyDirectory/RI_FirstAnalysis_model.obj -o MyDirectory -x RI_SecondAnalysis
## with the SKB feature selection and the SVR model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x SVR_FirstAnalysis -da manual -fs SKB -r SVR -k 5 -pa tuning_parameters_SVR.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/SVR_FirstAnalysis_features.obj -fe MyDirectory/SVR_FirstAnalysis_feature_encoder.obj -cf MyDirectory/SVR_FirstAnalysis_calibration_features.obj -ct MyDirectory/SVR_FirstAnalysis_calibration_targets.obj -t MyDirectory/SVR_FirstAnalysis_model.obj -o MyDirectory -x SVR_SecondAnalysis
## with the SKB feature selection and the XGB model regressor
python3.12 GenomicBasedRegression.py modeling -m genomic_profils_for_modeling.tsv -ph MyDirectory/ADA_FirstAnalysis_phenotype_dataset.tsv -o MyDirectory -x XGB_FirstAnalysis -da manual -fs SKB -r XGB -k 5 -pa tuning_parameters_XGB.txt -pi
python3.12 GenomicBasedRegression.py prediction -m genomic_profils_for_prediction.tsv -f MyDirectory/XGB_FirstAnalysis_features.obj -fe MyDirectory/XGB_FirstAnalysis_feature_encoder.obj -cf MyDirectory/XGB_FirstAnalysis_calibration_features.obj -ct MyDirectory/XGB_FirstAnalysis_calibration_targets.obj -t MyDirectory/XGB_FirstAnalysis_model.obj -o MyDirectory -x XGB_SecondAnalysis
'''
# import packages
## standard libraries
import sys as sys # no individual installation because is part of the Python Standard Library (no version)
import os as os # no individual installation because is part of the Python Standard Library (no version)
import datetime as dt # no individual installation because is part of the Python Standard Library (no version)
import argparse as ap # no individual installation because is part of the Python Standard Library (with version)
import pickle as pi # no individual installation because is part of the Python Standard Library (with version)
import warnings as wa # no individual installation because is part of the Python Standard Library (no version)
import re as re # no individual installation because is part of the Python Standard Library (with version)
import threading as th # no individual installation because is part of the Python Standard Library (no version)
import time as ti # no individual installation because is part of the Python Standard Library (no version)
import importlib.metadata as im # no individual installation because is part of the Python Standard Library (no version)
import functools as ft # no individual installation because is part of the Python Standard Library (no version)
import contextlib as ctl # no individual installation because is part of the Python Standard Library (no version)
import io as io # no individual installation because is part of the Python Standard Library (no version)
import threadpoolctl as tpc # no individual installation because is part of the Python Standard Library (no version)
## third-party libraries
import pandas as pd
import sklearn as sk
import numpy as np
import scipy as sp
import xgboost as xgb
import lightgbm as lgbm
import catboost as cb
import joblib as jl
import tqdm as tq
import tqdm.auto as tqa # no version because it corresponds a tqdm module
import tqdm_joblib as tqjl
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin
from sklearn.model_selection import GridSearchCV, StratifiedShuffleSplit, ParameterGrid
from sklearn.linear_model import LinearRegression, ElasticNet, Ridge, BayesianRidge, HuberRegressor, Lasso
from sklearn.preprocessing import OneHotEncoder, PolynomialFeatures, StandardScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, mean_absolute_percentage_error
from sklearn.tree import DecisionTreeRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, HistGradientBoostingRegressor, ExtraTreesRegressor, AdaBoostRegressor
from sklearn.svm import SVR, NuSVR
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest, chi2, f_regression, mutual_info_regression, SelectFromModel
from sklearn import set_config
from sklearn.inspection import permutation_importance
from catboost import CatBoostRegressor, Pool
# compatibility patch: prevent GridSearchCV from injecting random_state into CatBoost
class SafeCatBoostRegressor(CatBoostRegressor):
"""a subclass of CatBoostRegressor that safely ignores sklearn random_state parameter."""
def set_params(self, **params):
# Drop sklearn’s automatic random_state injection to avoid CatBoostError
params.pop("random_state", None)
return super().set_params(**params)
# set static metadata to keep outside the main function
## set workflow repositories
repositories = 'Please cite:\n GitHub (https://github.com/Nicolas-Radomski/GenomicBasedRegression),\n Docker Hub (https://hub.docker.com/r/nicolasradomski/genomicbasedregression),\n and/or Anaconda Hub (https://anaconda.org/nicolasradomski/genomicbasedregression).'
## set the workflow context
context = "The scikit-learn (sklearn)-based Python workflow independently supports both modeling (i.e., training and testing) and prediction (i.e., using a pre-built model), and implements 5 feature selection methods, 19 model regressors, hyperparameter tuning, performance metric computation, feature and permutation importance analyses, prediction interval estimation, execution monitoring via progress bars, and parallel processing."
## set the workflow reference
reference = "An article might potentially be published in the future."
## set the acknowledgement
acknowledgements = "Many thanks to Andrea De Ruvo, Adriano Di Pasquale and ChatGPT for the insightful discussions that helped improve the algorithm."
## set the version and release
__version__ = "1.3.0"
__release__ = "December 2025"
# set global sklearn config early
set_config(transform_output="pandas")
# define functions of interest
def smape(y_true, y_pred, threshold=1e-3):
"""
compute symmetric mean absolute percentage error (SMAPE) with thresholding for near-zero denominators
parameters:
y_true: array-like of true target values
y_pred: array-like of predicted values
threshold: float, default=1e-3, values with average magnitude below this are excluded to avoid instability, override for greater control in sensitive cases
returns:
float: SMAPE as a ratio (e.g., 0.0823), or np.nan if no valid values remain
"""
y_true_nda, y_pred_nda = np.array(y_true).ravel(), np.array(y_pred).ravel() # convert inputs to flattened ndarray to ensure compatibility
denominator = (np.abs(y_true_nda) + np.abs(y_pred_nda)) / 2 # compute denominator: average of the absolute values of true and predicted values
diff = np.abs(y_true_nda - y_pred_nda) # compute numerator: absolute difference between true and predicted values
mask = denominator > threshold # create a boolean mask to select only valid values (denominator > threshold)
if np.sum(mask) == 0: # return NaN if no valid values remain because SMAPE cannot be safely calculated
return np.nan
return np.mean(diff[mask] / denominator[mask]) # calculate SMAPE on the filtered values where denominator is not zero, nor near-zero
def mape(y_true, y_pred, threshold=1e-3):
"""
compute mean absolute percentage error (MAPE), using mean_absolute_percentage_error and excluding near-zero targets to avoid inflation
parameters:
y_true: array-like of true target values
y_pred: array-like of predicted values
threshold: float, default=1e-3, values of |y_true| below this are excluded from the computation
returns:
float: MAPE as a ratio (e.g., 0.0872), or np.nan if no valid targets remain
"""
y_true_nda, y_pred_nda = np.array(y_true).ravel(), np.array(y_pred).ravel() # convert inputs to flattened ndarray to ensure compatibility
mask = np.abs(y_true_nda) > threshold # create a boolean mask to exclude near-zero target values
if np.sum(mask) == 0: # return NaN to indicate MAPE is undefined if no valid values remain after masking
return np.nan
return mean_absolute_percentage_error(y_true_nda[mask], y_pred_nda[mask]) # compute MAPE only on the valid (masked) subset of the data
def adjusted_r2(y_true, y_pred, n_features):
"""
compute adjusted R-squared (aR²), which adjusts the R² score based on the number of predictors used
parameters:
y_true: array-like of true target values
y_pred: array-like of predicted values
n_features: int, number of predictors (independent variables) used in the model
returns:
float: adjusted R-squared, or np.nan if computation is invalid
"""
y_true_nda, y_pred_nda = np.array(y_true).ravel(), np.array(y_pred).ravel() # convert inputs to flattened ndarray to ensure compatibility
n = len(y_true_nda) # number of samples
if n <= n_features + 1: # check for valid degrees of freedom
return np.nan # adjusted R² cannot be computed safely in this case
r2 = r2_score(y_true_nda, y_pred_nda) # compute the regular R-squared score
# compute adjusted R² using the standard formula: adjusted R² = 1 - [(1 - R²) * (n - 1) / (n - p - 1)]
adjusted = 1 - (1 - r2) * ((n - 1) / (n - n_features - 1))
return adjusted # return the adjusted R² value
def count_selected_features(pipeline, encoded_matrix):
"""
robust count of features the pipeline expects
returns the number of columns reaching the final estimator
handles both Pipeline objects and direct estimators
"""
# ensure the object is a pipeline; wrap standalone estimators
if not hasattr(pipeline, "named_steps"):
pipeline = Pipeline([("model", pipeline)])
# ensure encoded_matrix preserves feature names
if not hasattr(encoded_matrix, "columns"):
raise ValueError(
"encoded_matrix must be a pandas DataFrame with feature names "
"to safely count selected features"
)
# check if a feature selection step exists
if "feature_selection" in pipeline.named_steps:
fs = pipeline.named_steps["feature_selection"]
# support_ is the most reliable and warning-free indicator
if hasattr(fs, "get_support"):
try:
support = fs.get_support()
return int(np.sum(support))
except Exception:
pass
# fallback: selector exists but does not expose support_
# assume no dimensionality reduction occurred
return int(encoded_matrix.shape[1])
# no explicit selector → check the estimator directly
est = pipeline.named_steps.get("model", pipeline)
# sklearn 1.3+ compatibility
n_feat = getattr(est, "n_features_in_", None)
if n_feat is None and hasattr(est, "feature_names_in_"):
n_feat = len(est.feature_names_in_)
# CatBoost, XGB, HGB often hide n_features_in_
if n_feat is None or n_feat == 0:
n_feat = encoded_matrix.shape[1]
return int(n_feat)
def restricted_float_split(x: str) -> float:
"""
convert *x* to float and ensure 0 < x < 100
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as float or is not in (0, 100)
"""
try:
x = float(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid float")
if not (0.0 < x < 100.0):
raise ap.ArgumentTypeError("split must be a float in the open interval (0, 100)")
return x
def restricted_int_quantiles(x: str) -> int:
"""
convert *x* to int and ensure x >= 2
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is less than 2
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x < 2:
raise ap.ArgumentTypeError("quantiles must be an integer ≥ 2")
return x
def restricted_int_limit(x: str) -> int:
"""
convert *x* to int and ensure x >= 1
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is less than 1
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x < 1:
raise ap.ArgumentTypeError("limit must be an integer ≥ 1")
return x
def restricted_int_fold(x: str) -> int:
"""
convert *x* to int and ensure x ≥ 2
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is less than 2
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x < 2:
raise ap.ArgumentTypeError("fold must be an integer ≥ 2 for cross-validation")
return x
def restricted_int_jobs(x: str) -> int:
"""
convert *x* to int and ensure x == -1 or x ≥ 1
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is not -1 or ≥ 1
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x != -1 and x < 1:
raise ap.ArgumentTypeError("jobs must be -1 (all CPUs) or an integer ≥ 1")
return x
def restricted_int_nrepeats(x: str) -> int:
"""
convert *x* to int and ensure x ≥ 1
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is less than 1
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x < 1:
raise ap.ArgumentTypeError("nrepeats must be an integer ≥ 1 for permutation importance")
return x
def restricted_float_alpha(x: str) -> float:
"""
convert *x* to float and ensure 0 < x < 1
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as float or is not in (0, 1)
"""
try:
x = float(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid float")
if not (0.0 < x < 1.0):
raise ap.ArgumentTypeError("alpha must be in the open interval (0, 1)")
return x
# ---------- ResidualQuantileWrapper ----------
# import numpy as np # arrays
# from sklearn.base import BaseEstimator, RegressorMixin # Import base classes from Scikit-learn to ensure compatibility with its utilities (e.g., cross-validation, cloning, pipelines)
class ResidualQuantileWrapper(BaseEstimator, RegressorMixin):
"""
wrapper class to compute prediction intervals based on residual quantiles
around a fitted regression estimator
this is a custom implementation similar in spirit to MAPIE's ResidualQuantileWrapper
parameters
----------
estimator : object
a regression estimator implementing fit and predict methods
alpha : float, default=0.05
significance level for prediction intervals (e.g., 0.05 for 95% intervals)
prefit : bool, default=False
if True, assumes that the estimator has already been fitted externally
and skips refitting during wrapper training.
"""
def __init__(self, estimator, alpha=0.05, prefit=False):
self.estimator = estimator # underlying regression model
self.alpha = alpha # confidence level (significance)
self.prefit = prefit # flag to avoid retraining an already fitted model
self.lower_quantile = None # to store residual lower quantile threshold
self.upper_quantile = None # to store residual upper quantile threshold
def fit(self, X, y):
"""
fit the estimator and compute residual quantiles on training (or calibration) data
parameters
----------
X : array-like of shape (n_samples, n_features)
training or calibration features.
y : array-like of shape (n_samples,) or (n_samples, 1)
target values.
returns
-------
self : object
returns self for chaining.
"""
# check that there are enough samples to estimate quantiles
if len(X) < 2:
raise ValueError("ResidualQuantileWrapper requires at least 2 calibration samples to compute prediction intervals.")
# fit the underlying regression model only if not already trained
if not self.prefit:
self.estimator.fit(X, y)
# ensure target is 1D to align with predicted values
y_1d = y.squeeze() if hasattr(y, "squeeze") else np.ravel(y)
# calculate residuals as absolute differences
residuals = np.abs(y_1d - self.estimator.predict(X))
# compute residual quantiles to define interval width
self.lower_quantile = np.quantile(residuals, self.alpha / 2)
self.upper_quantile = np.quantile(residuals, 1 - self.alpha / 2)
# optional print/log for debugging
#print(f"[ResidualQuantileWrapper] Residual quantile bounds set to ±{self.upper_quantile:.4f} for alpha = {self.alpha}")
return self
def predict(self, X, return_prediction_interval=False):
"""
predict point estimates and optionally prediction intervals for new data.
parameters
----------
X : array-like of shape (n_samples, n_features)
input features
return_prediction_interval : bool, default=False
if True, also return prediction intervals (lower and upper bounds)
returns
-------
y_pred : ndarray of shape (n_samples,)
predicted target values
y_pred_intervals : ndarray of shape (n_samples, 2), optional
prediction intervals with columns [lower, upper], returned only if
return_prediction_interval=True.
"""
# compute point predictions using the underlying model
y_pred = self.estimator.predict(X)
if return_prediction_interval:
# construct prediction intervals using stored residual quantiles
lower_bounds = y_pred - self.upper_quantile
upper_bounds = y_pred + self.upper_quantile
prediction_intervals = np.vstack((lower_bounds, upper_bounds)).T
return y_pred, prediction_intervals
return y_pred # point predictions only
def get_params(self, deep=True):
"""
get parameters for this estimator. Required for sklearn compatibility
parameters
----------
deep : bool, default=True
if True, will return the parameters for this estimator and contained subobjects
returns
-------
params : dict
parameter names mapped to their values.
"""
return {
"estimator": self.estimator,
"alpha": self.alpha,
"prefit": self.prefit
}
def set_params(self, **params):
"""
set the parameters of this estimator. Required for sklearn compatibility.
parameters
----------
**params : dict
estimator parameters.
returns
-------
self : object
estimator instance.
"""
for key, value in params.items():
setattr(self, key, value)
return self
def restricted_int_digits(x: str) -> int:
"""
convert *x* to int and ensure x ≥ 0
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is negative.
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x < 0:
raise ap.ArgumentTypeError("digits must be an integer ≥ 0")
return x
def restricted_debug_level(x: str) -> int:
"""
convert *x* to int and ensure x >= 0.
raises
------
argparse.ArgumentTypeError
if *x* cannot be parsed as int or is negative.
"""
try:
x = int(x)
except ValueError:
raise ap.ArgumentTypeError(f"{x!r} is not a valid integer")
if x < 0:
raise ap.ArgumentTypeError("debug must be zero or a positive integer (0, 1, 2, ...)")
return x
# create a main function preventing the global scope from being unintentionally executed on import
def main():
# step control
step1_start = dt.datetime.now()
# create the main parser
parser = ap.ArgumentParser(
prog="GenomicBasedRegression.py",
description="Perform regression-based modeling or prediction from binary (e.g., presence/absence of genes) or categorical (e.g., allele profiles) genomic data.",
epilog=repositories
)
# create subparsers object
subparsers = parser.add_subparsers(dest='subcommand')
# create the parser for the "modeling" subcommand
## get parser arguments
parser_modeling = subparsers.add_parser('modeling', help='Help about the model building.')
## define parser arguments
parser_modeling.add_argument(
'-m', '--mutations',
dest='inputpath_mutations',
action='store',
required=True,
help='Absolute or relative input path of tab-separated values (tsv) file including profiles of mutations. First column: sample identifiers identical to those in the input file of phenotypes and datasets (header: e.g., sample). Other columns: profiles of mutations (header: labels of mutations). [MANDATORY]'
)
parser_modeling.add_argument(
'-ph', '--phenotypes',
dest='inputpath_phenotypes',
action='store',
required=True,
help="Absolute or relative input path of tab-separated values (tsv) file including profiles of phenotypes and datasets. First column: sample identifiers identical to those in the input file of mutations (header: e.g., sample). Second column: categorical phenotype (header: e.g., phenotype). Third column: 'training' or 'testing' dataset (header: e.g., dataset). [MANDATORY]"
)
parser_modeling.add_argument(
'-da', '--dataset',
dest='dataset',
type=str,
action='store',
required=False,
choices=['random', 'manual'],
default='random',
help="Perform random (i.e., 'random') or manual (i.e., 'manual') splitting of training and testing datasets through the holdout method. [OPTIONAL, DEFAULT: 'random']"
)
parser_modeling.add_argument(
'-sp', '--split',
dest='splitting',
type=restricted_float_split, # control (0, 100) open interval
action='store',
required=False,
default=None,
help='Percentage of random splitting when preparing the training dataset using the holdout method. [OPTIONAL, DEFAULT: None]'
)
parser_modeling.add_argument(
'-q', '--quantiles',
dest='quantiles',
type=restricted_int_quantiles, # control >= 2
action='store',
required=False,
default=None,
help='Number of quantiles used to discretize the phenotype values when preparing the training dataset using the holdout method. [OPTIONAL, DEFAULT: None]'
)
parser_modeling.add_argument(
'-l', '--limit',
dest='limit',
type=restricted_int_limit, # control >= 1
action='store',
required=False,
default=10,
help='Recommended minimum number of samples in both the training and testing datasets to reliably estimate performance metrics. [OPTIONAL, DEFAULT: 10]'
)
parser_modeling.add_argument(
'-fs', '--featureselection',
dest='featureselection',
type=str,
action='store',
required=False,
default='None',
help='Acronym of the regression-compatible feature selection method to use: SelectKBest (SKB), SelectFromModel with lasso (laSFM), SelectFromModel with elasticnet (enSFM), or SelectFromModel with ridge (riSFM), or SelectFromModel with random forest (rfSFM). These methods are suitable for high-dimensional binary or categorical-encoded features. [OPTIONAL, DEFAULT: None]'
)
parser_modeling.add_argument(
'-r', '--regressor',
dest='regressor',
type=str,
action='store',
required=False,
default='XGB',
help='Acronym of the regressor to use among adaboost (ADA), bayesian ridge (BRI), catboost (CAT), decision tree (DT), elasticnet (EN), extra trees (ET), gradient boosting (GB), histogram-based gradient boosting (HGB), huber (HU), k-nearest neighbors (KNN), lassa (LA), light gradient boosting machine (LGBM), multi-layer perceptron (MLP), nu support vector (NSV), polynomial (PN), ridge (RI), random forest (RF), support vector regressor (SVR) or extreme gradient boosting (XGB). [OPTIONAL, DEFAULT: XGB]'
)
parser_modeling.add_argument(
'-k', '--fold',
dest='fold',
type=restricted_int_fold, # control >= 2
action='store',
required=False,
default=5,
help='Value defining k-1 groups of samples used to train against one group of validation through the repeated k-fold cross-validation method. [OPTIONAL, DEFAULT: 5]'
)
parser_modeling.add_argument(
'-pa', '--parameters',
dest='parameters',
action='store',
required=False,
help='Absolute or relative input path of a text (txt) file including tuning parameters compatible with the param_grid argument of the GridSearchCV function. (OPTIONAL)'
)
parser_modeling.add_argument(
'-j', '--jobs',
dest='jobs',
type=restricted_int_jobs, # control -1 or >= 1
action='store',
required=False,
default=-1,
help='Value defining the number of jobs to run in parallel compatible with the n_jobs argument of the GridSearchCV function. [OPTIONAL, DEFAULT: -1]'
)
parser_modeling.add_argument(
'-pi', '--permutationimportance',
dest='permutationimportance',
action='store_true',
required=False,
default=False,
help='Compute permutation importance, which can be computationally expensive, especially with many features and/or high repetition counts. [OPTIONAL, DEFAULT: False]'
)
parser_modeling.add_argument(
'-nr', '--nrepeats',
dest='nrepeats',
type=restricted_int_nrepeats, # control >= 1
action='store',
required=False,
default=10,
help='Number of repetitions per feature for permutation importance; higher values provide more stable estimates but increase runtime. [OPTIONAL, DEFAULT: 10]'
)
parser_modeling.add_argument(
'-a', '--alpha',
dest='alpha',
type=restricted_float_alpha, # control (0, 1) open interval
action='store',
required=False,
default=0.05,
help='Significance level alpha (a float between 0 and 1) used to compute prediction intervals corresponding to a [(1 − alpha) × 100]%% coverage. [OPTIONAL, DEFAULT: 0.05]'
)
parser_modeling.add_argument(
'-o', '--output',
dest='outputpath',
action='store',
required=False,
default='.',
help='Output path. [OPTIONAL, DEFAULT: .]'
)
parser_modeling.add_argument(
'-x', '--prefix',
dest='prefix',
action='store',
required=False,
default='output',
help='Prefix of output files. [OPTIONAL, DEFAULT: output]'
)
parser_modeling.add_argument(
'-di', '--digits',
dest='digits',
type=restricted_int_digits, # control >= 0
action='store',
required=False,
default=6,
help='Number of decimal digits to round numerical results (e.g., root mean squared error, importance, metrics). [OPTIONAL, DEFAULT: 6]'
)
parser_modeling.add_argument(
'-de', '--debug',
dest='debug',
type=restricted_debug_level, # control >= 0
action='store',
required=False,
default=0,
help='Traceback level when an error occurs. [OPTIONAL, DEFAULT: 0]'
)
parser_modeling.add_argument(
'-w', '--warnings',
dest='warnings',
action='store_true',
required=False,
default=False,
help='Do not ignore warnings if you want to improve the script. [OPTIONAL, DEFAULT: False]'
)
parser_modeling.add_argument(
'-nc', '--no-check',
dest='nocheck',
action='store_true',
required=False,
default=False,
help='Do not check versions of Python and packages. [OPTIONAL, DEFAULT: False]'
)
# create the parser for the "prediction" subcommand
## get parser arguments
parser_prediction = subparsers.add_parser('prediction', help='Help about the model-based prediction.')
## define parser arguments
parser_prediction.add_argument(
'-m', '--mutations',
dest='inputpath_mutations',
action='store',
required=True,
help='Absolute or relative input path of a tab-separated values (tsv) file including profiles of mutations. First column: sample identifiers identical to those in the input file of phenotypes and datasets (header: e.g., sample). Other columns: profiles of mutations (header: labels of mutations). [MANDATORY]'
)
parser_prediction.add_argument(
'-f', '--features',
dest='inputpath_features',
action='store',
required=True,
help='Absolute or relative input path of an object (obj) file including features from the training dataset (i.e., mutations). [MANDATORY]'
)
parser_prediction.add_argument(
'-fe', '--featureencoder',
dest='inputpath_feature_encoder',
action='store',
required=True,
help='Absolute or relative input path of an object (obj) file including encoder from the training dataset (i.e., mutations). [MANDATORY]'
)
parser_prediction.add_argument(
'-cf', '--calibrationfeatures',
dest='inputpath_calibration_features',
action='store',
required=True,
help='Absolute or relative input path of an object (obj) file including calibration features from the training dataset (i.e., mutations). [MANDATORY]'
)
parser_prediction.add_argument(
'-ct', '--calibrationtargets',
dest='inputpath_calibration_targets',
action='store',
required=True,
help='Absolute or relative input path of an object (obj) file including calibration targets from the training dataset (i.e., mutations). [MANDATORY]'
)
parser_prediction.add_argument(
'-t', '--model',
dest='inputpath_model',
action='store',
required=True,
help='Absolute or relative input path of an object (obj) file including a trained scikit-learn model. [MANDATORY]'
)
parser_prediction.add_argument(
'-a', '--alpha',
dest='alpha',
type=restricted_float_alpha, # control (0, 1) open interval
action='store',
required=False,
default=0.05,
help='Significance level alpha (a float between 0 and 1) used to compute prediction intervals corresponding to a [(1 − alpha) × 100]%% coverage. [OPTIONAL, DEFAULT: 0.05]'
)
parser_prediction.add_argument(
'-o', '--output',
dest='outputpath',
action='store',
required=False,
default='.',
help='Absolute or relative output path. [OPTIONAL, DEFAULT: .]'
)
parser_prediction.add_argument(
'-x', '--prefix',
dest='prefix',
action='store',
required=False,
default='output',
help='Prefix of output files. [OPTIONAL, DEFAULT: output_]'
)
parser_prediction.add_argument(
'-di', '--digits',
dest='digits',
type=restricted_int_digits, # control >= 0
action='store',
required=False,
default=6,
help='Number of decimal digits to round numerical results (e.g., root mean squared error, importance, metrics). [OPTIONAL, DEFAULT: 6]'
)
parser_prediction.add_argument(
'-de', '--debug',
dest='debug',
type=restricted_debug_level, # control >= 0
action='store',
required=False,
default=0,
help='Traceback level when an error occurs. [OPTIONAL, DEFAULT: 0]'
)
parser_prediction.add_argument(
'-w', '--warnings',
dest='warnings',
action='store_true',
required=False,
default=False,
help='Do not ignore warnings if you want to improve the script. [OPTIONAL, DEFAULT: False]'
)
parser_prediction.add_argument(
'-nc', '--no-check',
dest='nocheck',
action='store_true',
required=False,
default=False,
help='Do not check versions of Python and packages. [OPTIONAL, DEFAULT: False]'
)
# print help if there are no arguments in the command
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
# reshape arguments
## parse the arguments
args = parser.parse_args()
## rename arguments
if args.subcommand == 'modeling':
INPUTPATH_MUTATIONS=args.inputpath_mutations
INPUTPATH_PHENOTYPES=args.inputpath_phenotypes
DATASET=args.dataset
SPLITTING=args.splitting
QUANTILES=args.quantiles
LIMIT=args.limit
FEATURESELECTION=args.featureselection
REGRESSOR=args.regressor
FOLD=args.fold
PARAMETERS=args.parameters
JOBS=args.jobs
PERMUTATIONIMPORTANCE=args.permutationimportance
NREPEATS=args.nrepeats
ALPHA=args.alpha
OUTPUTPATH=args.outputpath
PREFIX=args.prefix
DIGITS=args.digits
DEBUG=args.debug
WARNINGS=args.warnings
NOCHECK=args.nocheck
elif args.subcommand == 'prediction':
INPUTPATH_MUTATIONS=args.inputpath_mutations
INPUTPATH_FEATURES=args.inputpath_features
INPUTPATH_FEATURE_ENCODER=args.inputpath_feature_encoder
INPUTPATH_CALIBRATION_FEATURES=args.inputpath_calibration_features
INPUTPATH_CALIBRATION_TARGETS=args.inputpath_calibration_targets
INPUTPATH_MODEL=args.inputpath_model
ALPHA=args.alpha
OUTPUTPATH=args.outputpath
PREFIX=args.prefix
DIGITS=args.digits
DEBUG=args.debug
WARNINGS=args.warnings
NOCHECK=args.nocheck
# print a message about release
message_release = "The GenomicBasedRegression script, version " + __version__ + " (released in " + __release__ + ")," + " was launched"
print(message_release)
# set tracebacklimit
sys.tracebacklimit = DEBUG
message_traceback = "The traceback level was set to " + str(sys.tracebacklimit)
print(message_traceback)
# management of warnings
if WARNINGS == True :
wa.filterwarnings('default')
message_warnings = "The warnings were not ignored"
print(message_warnings)
elif WARNINGS == False :
wa.filterwarnings('ignore')
message_warnings = "The warnings were ignored"
print(message_warnings)
# control versions
if NOCHECK == False :
## control Python version
if sys.version_info[0] != 3 or sys.version_info[1] != 12 :
raise Exception("Python 3.12 version is recommended")
# control versions of packages
if ap.__version__ != "1.1":
raise Exception('argparse 1.1 (1.4.1) version is recommended')
if sp.__version__ != "1.16.0":
raise Exception("scipy 1.16.0 version is recommended")
if pd.__version__ != "2.2.2":
raise Exception('pandas 2.2.2 version is recommended')
if sk.__version__ != "1.5.2":
raise Exception('sklearn 1.5.2 version is recommended')
if pi.format_version != "4.0":
raise Exception('pickle 4.0 version is recommended')
if cb.__version__ != "1.2.8":
raise Exception('catboost 1.2.8 version is recommended')
if lgbm.__version__ != "4.6.0":
raise Exception("lightgbm 4.6.0 version is recommended")
if xgb.__version__ != "2.1.3":
raise Exception("xgboost 2.1.3 version is recommended")
if np.__version__ != "1.26.4":
raise Exception("numpy 1.26.4 version is recommended")
if jl.__version__ != "1.5.1":
raise Exception('joblib 1.5.1 version is recommended')
if tq.__version__ != "4.67.1":
raise Exception('tqdm 4.67.1 version is recommended')
if im.version("tqdm-joblib") != "0.0.4":
raise Exception("tqdm-joblib 0.0.4 version is recommended")
message_versions = 'The recommended versions of Python and packages were properly controlled'
else:
message_versions = 'The recommended versions of Python and packages were not controlled'
# print a message about version control
print(message_versions)
# set rounded digits
digits = DIGITS
# check the subcommand and execute corresponding code
if args.subcommand == 'modeling':
# print a message about subcommand
message_subcommand = "The modeling subcommand was used"
print(message_subcommand)
# manage minimal limits of samples
if LIMIT < 10:
message_limit = (
"The provided sample limit per dataset (i.e., " + str(LIMIT) + ") was below the recommended minimum (i.e., 10) and may lead to unreliable performance metrics"
)
print(message_limit)
else:
message_limit = (
"The provided sample limit per dataset (i.e., " + str(LIMIT) + ") meets or exceeds the recommended minimum (i.e., 10), which is expected to support more reliable performance metrics"
)
print(message_limit)
# define minimal limits of samples (i.e., 2 * LIMIT per dataset)
limit_samples = 2 * LIMIT
# read input files
## mutations
df_mutations = pd.read_csv(INPUTPATH_MUTATIONS, sep='\t', dtype=str)
## phenotypes
df_phenotypes = pd.read_csv(INPUTPATH_PHENOTYPES, sep='\t', dtype=str)
# transform the phenotype as numeric
## make sure the phenotype column exists (i.e., the second column)
if df_phenotypes.shape[1] < 2:
message_phenotype_numeric = ("The presence of phenotype in the input file of phenotypes was improperly controlled (i.e., the second column is missing)")
raise Exception(message_phenotype_numeric)
## extract the phenotype column
phenotype_col = df_phenotypes.iloc[:, 1]
## make sure that the phenotype column can be transformed as numeric
elif_invalid = pd.to_numeric(phenotype_col, errors="coerce").isna().any()
if elif_invalid:
message_phenotype_numeric = ("The phenotype in the input file of phenotypes cannot be transformed as numeric (i.e., the second column contains non-numeric values)")
raise Exception(message_phenotype_numeric)
else:
# convert the phenotype column to numeric
df_phenotypes.iloc[:, 1] = pd.to_numeric(phenotype_col)
message_phenotype_numeric = ("The phenotype in the input file of phenotypes was properly transformed as numeric (i.e., the second column)")
# check the input file of mutations
## calculate the number of rows
rows_mutations = len(df_mutations)
## calculate the number of columns
columns_mutations = len(df_mutations.columns)
## check if more than limit_samples rows and 3 columns
if (rows_mutations >= limit_samples) and (columns_mutations >= 3):
message_input_mutations = "The minimum required number of samples in the training/testing datasets (i.e., >= " + str(limit_samples) + ") and the expected number of columns (i.e., >= 3) in the input file of mutations were properly controlled (i.e., " + str(rows_mutations) + " and " + str(columns_mutations) + ", respectively)"
print(message_input_mutations)
else:
message_input_mutations = "The minimum required number of samples in the training/testing datasets (i.e., >= " + str(limit_samples) + ") and the expected number of columns (i.e., >= 3) in the input file of mutations were not properly controlled (i.e., " + str(rows_mutations) + " and " + str(columns_mutations) + ", respectively)"
raise Exception(message_input_mutations)
# check the input file of phenotypes
## calculate the number of rows
rows_phenotypes = len(df_phenotypes)
## calculate the number of columns
columns_phenotypes = len(df_phenotypes.columns)
## check if more than limit_samples rows and 3 columns
if (rows_phenotypes >= limit_samples) and (columns_phenotypes == 3):
message_input_phenotypes = "The minimum required number of samples in the training/testing datasets (i.e., >= " + str(limit_samples) + ") and the expected number of columns (i.e., = 3) in the input file of phenotypes were properly controlled (i.e., " + str(rows_phenotypes) + " and " + str(columns_phenotypes) + ", respectively)"
print(message_input_phenotypes)
else:
message_input_phenotypes = "The minimum required number of samples in the training/testing datasets (i.e., >= " + str(limit_samples) + ") and the expected number of columns (i.e., = 3) in the input file of phenotypes were not properly controlled (i.e., " + str(rows_phenotypes) + " and " + str(columns_phenotypes) + ", respectively)"
raise Exception(message_input_phenotypes)
## check the absence of missing data in the second column (i.e., phenotype)
missing_phenotypes = pd.Series(df_phenotypes.iloc[:,1]).isnull().values.any()
if missing_phenotypes == False:
message_missing_phenotypes = "The absence of missing phenotypes in the input file of phenotypes was properly controlled (i.e., the second column)"
print(message_missing_phenotypes)
elif missing_phenotypes == True:
message_missing_phenotypes = "The absence of missing phenotypes in the input file of phenotypes was inproperly controlled (i.e., the second column)"
raise Exception(message_missing_phenotypes)
## check the absence of values other than 'training' or 'testing' in the third column (i.e., dataset)
if (DATASET == "manual"):
expected_datasets = all(df_phenotypes.iloc[:,2].isin(["training", "testing"]))
if expected_datasets == True:
message_expected_datasets = "The expected datasets (i.e., 'training' or 'testing') in the input file of phenotypes were properly controlled (i.e., the third column)"
print (message_expected_datasets)
elif expected_datasets == False:
message_expected_datasets = "The expected datasets (i.e., 'training' or 'testing') in the input file of phenotypes were inproperly controlled (i.e., the third column)"
raise Exception(message_expected_datasets)
elif (DATASET == "random"):
message_expected_datasets = "The expected datasets (i.e., 'training' or 'testing') in the input file of phenotypes were not controlled (i.e., the third column)"
print(message_expected_datasets)
# replace missing genomic data by a string
df_mutations = df_mutations.fillna('missing')
# rename variables of headers
## mutations
df_mutations.rename(columns={df_mutations.columns[0]: 'sample'}, inplace=True)
## phenotypes
df_phenotypes.rename(columns={df_phenotypes.columns[0]: 'sample'}, inplace=True)
df_phenotypes.rename(columns={df_phenotypes.columns[1]: 'phenotype'}, inplace=True)
df_phenotypes.rename(columns={df_phenotypes.columns[2]: 'dataset'}, inplace=True)
# sort by samples
## mutations
df_mutations = df_mutations.sort_values(by='sample')
## phenotypes
df_phenotypes = df_phenotypes.sort_values(by='sample')