forked from rgcgithub/regenie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrdinal.cpp
3023 lines (2509 loc) · 99.3 KB
/
Ordinal.cpp
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
/*
This file is part of the regenie software package.
Copyright (c) 2020-2024 Joelle Mbatchou, Andrey Ziyatdinov & Jonathan Marchini
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "Regenie.hpp"
#include "Files.hpp"
#include "Geno.hpp"
#include "Pheno.hpp"
#include "Ordinal.hpp"
using namespace Eigen;
using namespace std;
//-----------------
// Local functions
//-----------------
Eigen::MatrixXd orth_matrix(const Eigen::MatrixXd & , const MatrixXb &);
void exp_matrix(Eigen::MatrixXd &);
void exp_matrix_ord(Eigen::MatrixXd &);
void exp_vector(Eigen::VectorXd &);
Eigen::VectorXd dlog_vector(const Eigen::VectorXd & );
Eigen::MatrixXd dlog_matrix(const Eigen::MatrixXd & );
bool check_nan(double );
//-------------------
// Class MultiPhen
//-------------------
void MultiPhen::setup_defaults()
{
// settings
cnt_fit = 0;
verbose = 0;
response = "unknown";
optim = "WeightHalving";
firth_binom = false; firth_multinom = false;
firth_mult = 1.0;
reuse_start = false; reset_start = false;
approx_offset = false;
mac_approx_offset = 0;
offset_mode = "offset";
maxit = 150; maxit2 = 10; maxit3 = 10; strict = false;
tol = 1e-4; pseudo_stophalf = 0.0;
check_step = true; max_step = 10.0;
// statuses
set_x = false; set_y = false;
// data dimenstions
N = 0; Neff = 0; // sample size
/* Ncov = 0, Nb = 0, Ncov0 = 0; Ncov1 = 0; // number of covariates */
ncat = 0, ncat1 = 0, ncat1sq = 0; // number of categories
// tests
pval_thr = 0.1;
// model fitting results
executed = false; converged = false;
trace = false;
it = 0; cnt_updates = 0;
}
MultiPhen::MultiPhen()
{
setup_defaults();
test = "none";
}
MultiPhen::MultiPhen(std::string _test)
{
setup_defaults();
test = _test;
}
MultiPhen::MultiPhen(unsigned int test_code)
{
setup_defaults();
std::map<unsigned int, std::string> test_map = { {0, "none"}, {1, "cov_score"} };
test = test_map[test_code];
}
// constructor for FitOrdinal
// - copy model parameters to FitOrdinal object
FitOrdinal MultiPhen::setup_fit(bool inc_cov, bool inc_phen, bool use_offset)
{
FitOrdinal fit;
// copy parameters from Ordinal
fit.verbose = verbose;
fit.response = response; // response type = [binom, multinom]
fit.model = model; // model = [POM: Proportional Odds Model, ACL: Adjacent Category Logit]
fit.optim = optim; // optimization algorithm = [FisherScoring, WeightHalving]
fit.firth_binom = firth_binom; fit.firth_multinom = firth_multinom; // Firth correction
fit.firth_mult = firth_mult;
fit.maxit = maxit; fit.maxit2 = maxit2; fit.maxit3 = maxit3; fit.strict = strict;
fit.tol = tol; fit.pseudo_stophalf = pseudo_stophalf;
fit.check_step = check_step;
fit.max_step = max_step;
fit.N = N; fit.Neff = Neff; // samples size
if(use_offset) {
// use offset
if(inc_cov) {
if(inc_phen) {
fit.Ncov = Ny; fit.Nb = Ny; // number of covariates
} else {
throw std::runtime_error("use offset with covariates only (Ncov = Nb = 0)");
}
} else {
if(inc_phen) {
fit.Ncov = Ny; fit.Nb = Ny; // number of covariates
} else {
throw std::runtime_error("use offset with covariates only (Ncov = Nb = 0)");
}
}
} else {
// no offset
if(inc_cov) {
if(inc_phen) {
fit.Ncov = Nx + Ny; fit.Nb = ncat1 + Nx + Ny; // number of covariates
} else {
fit.Ncov = Nx; fit.Nb = ncat1 + Nx; // number of covariates
}
} else {
if(inc_phen) {
fit.Ncov = Ny; fit.Nb = ncat1 + Ny; // number of covariates
} else {
fit.Ncov = 0; fit.Nb = ncat1; // number of covariates
}
}
}
fit.ncat = ncat; // number of categories
fit.ncat1 = ncat1; fit.ncat1sq = ncat1sq;
fit.Ncat = Ncat;
fit.cur_dev = 0; fit.prev_dev = 0;
fit.trace = trace;
fit.it = 0; fit.it2 = 0; fit.cnt_updates = 0;
fit.cnt_fit = cnt_fit++;
return(fit);
}
void MultiPhen::run(const Eigen::VectorXd & g,
const Eigen::MatrixXd& XYR, unsigned int n_cov, unsigned int n_phen)
{
reset_model();
// check if XYR is set up
if(!set_x) throw std::runtime_error("run: set_x is false");
// set y
setup_y(g); // -> Ym, yb
if(!set_y) return; // early stop (example #cat = 1 for imputed variant due to rounding)
setup_approx_offset(); // approx_offset
// print info
if(verbose) cout << "MultiPhen: Nx = " << Nx << " Ny = " << Ny << endl;
// test
if(test == "none") {
reset_model();
// do nothing
} else if(test == "cov_score_it1") {
maxit = 1; optim = "FisherScoring";
run_test_score(XYR, true); // inc_cov = false
} else if(test == "nocov_score") {
run_test_score(XYR, false); // inc_cov = false
} else if(test == "cov_score") {
run_test_score(XYR, true); // inc_cov = true
} else if(test == "nocov_lrt") {
run_test_lrt(XYR, false); // inc_cov = false
} else if(test == "cov_lrt") {
run_test_lrt(XYR, true); // inc_cov = true
} else if(test == "offset") {
run_test_offset(XYR);
} else if(test == "nocov_score_addcov") {
run_test_addcov(XYR);
} else if(test == "nocov_score_offset") {
run_test_add_offset(XYR);
} else {
throw std::runtime_error("run: unknown test");
}
}
void MultiPhen::run0(const Eigen::VectorXi & g, const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y, bool score_lrt)
{
// set up Ordinal model (no Firth)
Ordinal ord;
ord.optim = optim; ord.tol = tol; ord.pseudo_stophalf = pseudo_stophalf; ord.maxit = maxit; ord.maxit2 = maxit2; ord.maxit3 = maxit3; ord.strict = strict;
ord.check_step = check_step; ord.max_step = max_step;
ord.firth_binom = false;
if(score_lrt) { // Score test
executed = true; converged = false; pval_test = -1.0;
FitOrdinal fit;
// fit null model
fit = ord.fit(g, X);
if(!fit.converged) { return; }
/* // run Score test */
converged = fit.converged;
pval_test = ord.test_score(fit, Y);
} else { // LRT
executed = true; converged = false; pval_test = -1.0;
FitOrdinal fit0, fit1;
// prepare new matrix of covariates X + Y
MatrixXd X1(Y.rows(), X.cols() + Y.cols());
if(X.cols()) X1.leftCols(X.cols()) = X;
X1.rightCols(Y.cols()) = Y;
// fit null model
fit0 = ord.fit(g, X);
if(!fit0.converged) { return; }
// fit alternative model (Firth)
fit1 = ord.fit(g, X1);
if(!fit1.converged) { return; }
converged = fit1.converged;
boost::math::chi_squared dist(Y.cols());
double stat_lrt = 2 * (fit1.loglik - fit0.loglik);
pval_test = boost::math::cdf(boost::math::complement(dist, stat_lrt));
}
}
// XYR = [Intercept, X, Y, Inercept, R]
FitOrdinal MultiPhen::fit(const Eigen::Ref<const Eigen::MatrixXd> & XYR, bool inc_cov, bool inc_phen, bool use_res)
{
if(use_res) throw std::runtime_error("use_res is not implemented yet");
// initialize defaults settings
bool inc_phen_null = false, inc_phen_firth = inc_phen;
bool use_offset = (inc_phen && approx_offset);
bool copy_start = (reuse_start && inc_cov && inc_phen && !approx_offset);
// update settings for Binom: no firth / firth
if(response == "binom") {
inc_phen_null = firth_binom && !inc_phen && !approx_offset;
inc_phen_firth = inc_phen_null ? true : inc_phen;
}
// update settings for Multinom: no firth / firth
if(response == "multinom") {
inc_phen_null = firth_multinom && !inc_phen && !approx_offset;
inc_phen_firth = inc_phen_null ? true : inc_phen;
}
// create a fit object
FitOrdinal fit = setup_fit(inc_cov, inc_phen_firth, use_offset);
/* cout << "done MultiPhen setup_fit: response = " << response */
/* << " Nx = " << Nx << " Ny = " << Ny */
/* << " inc_cov = " << inc_cov << " inc_phen_firth = " << inc_phen_firth */
/* << " use_offset = " << use_offset << " fit.Nb = " << fit.Nb << " fit.Ncov = " << fit.Ncov << endl; */
// reuse starting par. values
if(copy_start) fit.setup_restart(b0);
// refine fit for Binom only
if(response == "binom") {
// constraint some par. to zero?
bool reverse_last = firth_binom && !inc_cov && inc_phen_firth;
bool last0 = !reverse_last;
if(inc_phen_null) fit.setup_ncov0(Ny, last0, false); // preproc_cov = false
}
// refine fit for Multinom only
if(response == "multinom") {
// constraint some par. to zero?
bool reverse_last = firth_multinom && !inc_cov && inc_phen_firth;
bool last0 = !reverse_last;
if(inc_phen_null) fit.setup_ncov0(Ny, last0, false); // preproc_cov = false
}
// store offset?
if(!inc_phen && approx_offset) fit.store_offset = true;
// apply offset?
if(use_offset) {
if(response == "binom") fit.setup_offset_binom(yo, false); // decrement_Nb = false
else if (response == "multinom") fit.setup_offset_multinom_pom(yo, yo_int);
else throw std::runtime_error("unknown response");
}
// do model fitting & control the columns in XYR passed
if(response == "binom") {
if(use_offset) {
if(inc_phen_firth) {
/* fit.fit_binom(Mask, Ym, XYR.rightCols(Ny21).leftCols(Ny)); // matrix of phenotypes Y */
fit.fit_binom(Mask, Ym, Yres0); // matrix of phenotypes Y
} else throw std::runtime_error("use offset for the null model");
} else {
if(inc_cov) {
if(inc_phen_firth) fit.fit_binom(Mask, Ym, XYR.leftCols(Nx1 + Ny)); // X + Y + Intercept
else fit.fit_binom(Mask, Ym, XYR.leftCols(Nx1)); // X + Intercept
} else {
if(inc_phen_firth) fit.fit_binom(Mask, Ym, XYR.rightCols(Ny21).leftCols(Ny1)); // matrix of phenotypes Y + Intercept
else fit.fit_binom(Mask, Ym, XYR.leftCols(1)); // Intercept
}
}
} else if(response == "multinom") {
if(use_offset) {
if(inc_phen_firth) fit.fit_multinom_pom(Mask, Ym, XYR.rightCols(Ny21).leftCols(Ny)); // matrix of phenotypes Y
else throw std::runtime_error("use offset for the null model");
} else {
if(inc_cov) {
if(inc_phen_firth) fit.fit_multinom_pom(Mask, Ym, XYR.leftCols(Nx1 + Ny).rightCols(Nx + Ny)); // X + Y
else fit.fit_multinom_pom(Mask, Ym, XYR.leftCols(Nx1).rightCols(Nx)); // X
} else {
if(inc_phen_firth) fit.fit_multinom_pom(Mask, Ym, XYR.rightCols(Ny1).leftCols(Ny)); // matrix of phenotypes Y
else fit.fit_multinom_pom(Mask, Ym, XYR.leftCols(0)); // 0 columns
}
}
} else {
throw std::runtime_error("unknown response");
}
if(trace) {
cnt_updates += fit.cnt_updates;
it += fit.it;
}
return(fit);
}
void MultiPhen::run_test_addcov(const Eigen::Ref<const Eigen::MatrixXd> & XYR)
{
run_test_score(XYR, false); // inc_cov = false
if(pval_test < pval_thr) {
run_test_lrt(XYR, true); // inc_cov = true
}
}
void MultiPhen::run_test_add_offset(const Eigen::Ref<const Eigen::MatrixXd> & XYR)
{
run_test_score(XYR, false); // inc_cov = false
if(pval_test < pval_thr) {
run_test_offset(XYR);
}
}
void MultiPhen::run_test_offset(const Eigen::Ref<const Eigen::MatrixXd> & XYR)
{
FitOrdinal null0, null, full;
VectorXd b0_fit;
double ll_null, ll_full;
boost::math::chi_squared dist(Ny);
double stat_lrt;
unsigned int i;
reset_model(); // reset model fit results
if(response == "binom") {
executed = true;
// fit null model
null0 = setup_fit(true, false, false); // inc_cov = true, inc_phen = false, use_offset = false
null0.store_offset = true;
null0.fit_binom(Mask, Ym, XYR.leftCols(Nx1)); // covariates X + Intercept
if(trace) { cnt_updates += null0.cnt_updates; it += null0.it; }
if(!null0.converged) return;
// store offset/weights from the null model
yo = null0.yo;
yo_int = null0.yo;
yo_int.array() -= null0.bhat(0); // substract intercept bhat
w0 = null0.wb;
// residualize phenotypes
Yres0 = XYR.rightCols(Ny21).leftCols(Ny); // matrix of phenotypes Y
ColPivHouseholderQR<MatrixXd> qrXw;
qrXw.compute(MatrixXd(Nx1, Nx1).setZero().selfadjointView<Lower>().rankUpdate((XYR.leftCols(Nx1).array().colwise() * w0.array().sqrt()).matrix().adjoint()));
Yres0 -= XYR.leftCols(Nx1).matrix() * qrXw.solve((XYR.leftCols(Nx1).array().colwise() * w0.array()).matrix().transpose() * Yres0);
for(i = 0; i < Yres0.cols(); i++) {
Yres0.col(i) = Mask.select(Yres0.col(i), 0.0);
}
// extract quantities from null model
VectorXd mub0 = yo;
exp_vector(mub0);
mub0.array() /= (1.0 + mub0.array());
// fit full model
if(offset_mode == "offset") {
// full model: logit(g) = offset + Y beta
full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
full.Ncov = Ny; full.Nb = Ny; // overwrite Ncov, Nb
full.setup_offset_binom(yo, false); // decrement_Nb = false
full.fit_binom(Mask, Ym, Yres0); // Logistic phenotype residuals
if(!full.converged) return;
converged = true;
/* ll_null = 0.0; */
/* ll_null += Ym.col(0).select((1.0 - mub0.array()).log(), 0.0).array().sum(); // controls */
/* ll_null += Ym.col(1).select(mub0.array().log(), 0.0).array().sum(); // cases */
ll_null = null.loglik_multinom(Mask, Ym); // depends on Y, P, Pk, Mask
if(firth_binom) {
MatrixXd null_Info = Yres0.transpose() * (Yres0.array().colwise() * w0.array()).matrix();
LLT<MatrixXd> llt_null(null_Info);
ll_null += llt_null.matrixL().toDenseMatrix().diagonal().array().log().sum();
}
ll_full = full.loglik;
stat_lrt = 2 * (ll_full - ll_null);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else if(offset_mode == "offsetcov") {
if(!firth_binom) throw std::runtime_error("offsetcov for firth_binom only");
// null model: logit(g) = [offsetcov; Y] [beta0, betaY] wrt betaY = 0
MatrixXd Yres0_Int(N, Ny1);
Yres0_Int.leftCols(1) = Mask.select(yo_int, 0.0);
Yres0_Int.rightCols(Ny) = Yres0;
null = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
null.Ncov = Ny1; null.Nb = Ny1; // overwrite Ncov, Nb
null.setup_ncov0(Ny, true, false); // last0 = true, preproc_cov = false
null.fit_binom(Mask, Ym, Yres0_Int); // Logistic phenotype residuals
if(trace) { cnt_updates += null.cnt_updates; it += null.it; }
if(!null.converged) return;
// full model: logit(g) = [offset; Y] beta
full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
full.Ncov = Ny1; full.Nb = Ny1; // overwrite Ncov, Nb
full.fit_binom(Mask, Ym, Yres0_Int); // Logistic phenotype residuals
if(trace) { cnt_updates += full.cnt_updates; it += full.it; }
if(!full.converged) return;
converged = true;
stat_lrt = 2 * (full.loglik - null.loglik);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else if(offset_mode == "offsetcov_int") {
if(!firth_binom) throw std::runtime_error("offsetcov_int for firth_binom only");
b0_fit.resize(2);
b0_fit << null0.bhat(0), 1.0;
// null model: logit(g) = [1, offsetcov; Y] [beta0, betaY] wrt betaY = 0
MatrixXd Yres0_Int(N, Ny1 + 1);
Yres0_Int.leftCols(1) = XYR.leftCols(1);
Yres0_Int.leftCols(2).rightCols(1) = Mask.select(yo_int, 0.0);
Yres0_Int.rightCols(Ny) = Yres0;
null = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
null.Ncov = Ny1 + 1; null.Nb = Ny1 + 1; // overwrite Ncov, Nb
null.setup_ncov0(Ny, true, false); // last0 = true, preproc_cov = false
null.setup_restart(b0_fit);
null.fit_binom(Mask, Ym, Yres0_Int); // Logistic phenotype residuals
if(trace) { cnt_updates += null.cnt_updates; it += null.it; }
if(!null.converged) return;
// full model: logit(g) = [1, offset; Y] beta
full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
full.Ncov = Ny1 + 1; full.Nb = Ny1; // overwrite Ncov, Nb
null.setup_restart(b0_fit);
full.fit_binom(Mask, Ym, Yres0_Int); // Logistic phenotype residuals
if(trace) { cnt_updates += full.cnt_updates; it += full.it; }
if(!full.converged) return;
converged = true;
stat_lrt = 2 * (full.loglik - null.loglik);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else if(offset_mode == "offset_int") {
if(!firth_binom) throw std::runtime_error("offset_int for firth_binom only");
// null model: logit(g) = offset + [1; Y] [beta0, betaY] wrt betaY = 0
MatrixXd Yres0_Int(N, Ny1);
Yres0_Int.leftCols(1) = XYR.leftCols(1);
Yres0_Int.rightCols(Ny) = Yres0;
null = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
null.Ncov = Ny1; null.Nb = Ny1; // overwrite Ncov, Nb
null.setup_offset_binom(yo_int, false); // decrement_Nb = false
null.setup_ncov0(Ny, true, false); // last0 = true, preproc_cov = false
null.fit_binom(Mask, Ym, Yres0_Int); // Logistic phenotype residuals
if(trace) { cnt_updates += null.cnt_updates; it += null.it; }
if(!null.converged) return;
// full model: logit(g) = offset + [1; Y] beta
full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
full.Ncov = Ny1; full.Nb = Ny1; // overwrite Ncov, Nb
full.setup_offset_binom(yo_int, false); // decrement_Nb = false
full.fit_binom(Mask, Ym, Yres0_Int); // Logistic phenotype residuals
if(trace) { cnt_updates += full.cnt_updates; it += full.it; }
if(!full.converged) return;
converged = true;
stat_lrt = 2 * (full.loglik - null.loglik);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else {
throw std::runtime_error("unknown offset mode");
}
} else if(response == "multinom") {
executed = true;
// fit null model
if(verbose) cout << "fitting initial null model" << endl;
null = setup_fit(true, false, false); // inc_cov = true, inc_phen = false, use_offset = false
null.store_offset = true;
null.fit_multinom_pom(Mask, Ym, XYR.leftCols(Nx1).rightCols(Nx)); // covariates X without Intercept
if(trace) { cnt_updates += null.cnt_updates; it += null.it; }
if(!null.converged) return;
if(verbose) cout << "initial null converged" << endl;
// store offset/weights from the null model
yo = null.yo;
yo_int = null.yo_int;
// !NB! not residuals
MatrixXd Yres0 = XYR.rightCols(Ny21).leftCols(Ny); // Phenotypes
if(offset_mode == "offset") {
// full model: logit(gamma) = offset + Y betaY
full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
full.Ncov = Ny; full.Nb = Ny; // overwrite Ncov, Nb
full.setup_offset_multinom_pom(yo, yo_int); // manually set up offset
full.exclude_intercepts = true; full.exclude_intercepts_offset = false;
full.fit_multinom_pom(Mask, Ym, Yres0);
if(trace) { cnt_updates += full.cnt_updates; it += full.it; }
if(!full.converged) return;
converged = true;
ll_null = null.loglik_multinom(Mask, Ym); // depends on Y, P, Pk, Mask
if(firth_multinom) {
MatrixXd null_Info = MatrixXd(Ny, Ny).setZero().selfadjointView<Lower>().
rankUpdate((Yres0.array().colwise() * null.WSS1.array()).matrix().adjoint());
LLT<MatrixXd> llt_null(null_Info);
ll_null += llt_null.matrixL().toDenseMatrix().diagonal().array().log().sum();
}
stat_lrt = 2 * (full.loglik - ll_null);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else if(offset_mode == "offset_int") {
if(!firth_multinom) throw std::runtime_error("offset_int for firth_multinom only");
b0_fit.resize(2);
b0_fit << yo_int;
// null model: logit(gamma) = offset + Y betaY wrt betaY = 0
null = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
null.Ncov = Ny; null.Nb = Ny + ncat1; // overwrite Ncov, Nb
null.setup_offset_multinom_pom(yo, yo_int); // manually set up offset
null.exclude_intercepts = false; null.exclude_intercepts_offset = true;
null.setup_ncov0(Ny, true, false); // last0 = true, preproc_cov = false
null.setup_restart(b0_fit);
null.fit_multinom_pom(Mask, Ym, Yres0);
if(trace) { cnt_updates += null.cnt_updates; it += null.it; }
if(!null.converged) return;
if(verbose) cout << "null converged" << endl;
// full model: logit(gamma) = offset + Y betaY
full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true
full.Ncov = Ny; full.Nb = Ny + ncat1; // overwrite Ncov, Nb
full.setup_offset_multinom_pom(yo, yo_int); // manually set up offset
full.exclude_intercepts = false; full.exclude_intercepts_offset = true;
full.setup_restart(b0_fit);
full.fit_multinom_pom(Mask, Ym, Yres0);
if(trace) { cnt_updates += full.cnt_updates; it += full.it; }
if(!full.converged) return;
converged = true;
if(verbose) cout << "full converged" << endl;
stat_lrt = 2 * (full.loglik - null.loglik);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
if(verbose) cout << "pval_test = " << pval_test << endl;
} else {
throw std::runtime_error("unknown offset mode");
/* // residualize phenotypes */
/* // !NB! not implemented yet */
/* // full model */
/* full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true */
/* full.setup_offset_multinom_pom(yo, yo_int); // manually set up offset */
/* full.exclude_intercepts = true; */
/* full.Ncov = Ny; full.Nb = Ny; // overwrite Ncov, Nb */
/* full.fit_multinom_pom(Mask, Ym, XYR.rightCols(Ny21).leftCols(Ny)); // Phenotypes */
/* /1* if(offset_mode == "offset") { *1/ */
/* /1* full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true *1/ */
/* /1* full.setup_offset_multinom_pom(yo, yo_int); // manually set up offset *1/ */
/* /1* full.exclude_intercepts = true; *1/ */
/* /1* full.Ncov = Ny; full.Nb = Ny; // overwrite Ncov, Nb *1/ */
/* /1* full.fit_multinom_pom(Mask, Ym, XYR.rightCols(Ny21).leftCols(Ny)); // Phenotypes *1/ */
/* /1* } else if(offset_mode == "offset_int") { *1/ */
/* /1* full = setup_fit(false, true, true); // inc_cov = false, inc_phen = true, use_offset = true *1/ */
/* /1* full.setup_offset_multinom_pom(yo, yo_int); // manually set up offset *1/ */
/* /1* full.exclude_intercepts = false; *1/ */
/* /1* full.Ncov = Ny; full.Nb = ncat1 + Ny; // overwrite Ncov, Nb *1/ */
/* /1* full.fit_multinom_pom(Mask, Ym, XYR.rightCols(Ny21).leftCols(Ny)); // Phenotypes *1/ */
/* /1* } else { *1/ */
/* /1* throw std::runtime_error("unknown offset mode"); *1/ */
/* /1* } *1/ */
/* if(trace) { cnt_updates += full.cnt_updates; it += full.it; } */
/* if(!full.converged) return; */
/* converged = true; */
/* stat_lrt = 2 * (full.loglik - null.loglik); */
/* pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt)); */
}
} else {
throw std::runtime_error("unknown response");
}
// store results
if(converged) {
bhat_y = full.bhat.tail(Ny);
}
}
void MultiPhen::run_test_qt(const Eigen::Ref<const Eigen::MatrixXd> & XYR)
{
reset_model(); // reset model fit results
if(response == "binom") {
executed = true;
converged = true;
VectorXd beta_qt = XYR.leftCols(Nx1).transpose() * yb;
// residualize
VectorXd y_qt = yb - XYR.leftCols(Nx1) * beta_qt;
VectorXd x_qt = XYR.leftCols(Nx1 + 1).rightCols(1);
// regression
/* VectorXd bhat_qt = (y_qt.transpose() * x_qt) / x2; */
/* bhat = (Y.col(i).transpose() * G).array().rowwise() / G2.array().transpose(); */
/* /1* B.row(i) = bhat; *1/ */
/* // residuals, s2 */
/* s2 = (((G.array().rowwise() * bhat.array().transpose()). // predicted yp = X bhat */
/* colwise() - Y.col(i).array()). // residuals = y - yp */
/* matrix().colwise().squaredNorm()). // residuals^2 */
/* array() / (N_data - 1.0); // s2 = residuals^2 / (N - 1) */
/* Z.row(i) = bhat.array() * (G2.array() / s2.array()).sqrt(); */
/* // regression */
/* bhat = (Y.col(i).transpose() * G).array().rowwise() / G2.array().transpose(); */
/* /1* B.row(i) = bhat; *1/ */
/* // residuals, s2 */
/* s2 = (((G.array().rowwise() * bhat.array().transpose()). // predicted yp = X bhat */
/* colwise() - Y.col(i).array()). // residuals = y - yp */
/* matrix().colwise().squaredNorm()). // residuals^2 */
/* array() / (N_data - 1.0); // s2 = residuals^2 / (N - 1) */
/* Z.row(i) = bhat.array() * (G2.array() / s2.array()).sqrt(); */
/* yb */
/* pval_test = test_score(null, Mask, Ym, yb, XYR, inc_cov); */
} else {
return;
}
}
void MultiPhen::run_test_lrt(const Eigen::Ref<const Eigen::MatrixXd> & XYR, bool inc_cov)
{
reset_model(); // reset MultiPhen model fit results
executed = true;
FitOrdinal null, full;
if(reuse_start & !approx_offset) {
if(!inc_cov) throw std::runtime_error("reuse_start in not available for inc_cov = false");
/* if(approx_offset) throw std::runtime_error("reuse_start is not compatible with approx_offset"); */
// null model: logit(g) = X alpha
null = fit(XYR, inc_cov, false); // inc_cov, inc_phen = false
if(!null.converged) return;
b0 = null.bhat;
// full model: logit(g) = X alpha + Y beta
full = fit(XYR, inc_cov, true); // inc_cov, inc_phen = true
// give another chance if reuse_start & reset_start
if(reset_start) {
reuse_start = false;
full = fit(XYR, inc_cov, true); // inc_cov, inc_phen = true
}
if(!full.converged) return;
converged = true;
boost::math::chi_squared dist(Ny);
double stat_lrt = 2 * (full.loglik - null.loglik);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else if(approx_offset && response == "binom") {
// null model: logit(g) = X alpha
null = fit(XYR, inc_cov, false); // inc_cov, inc_phen = false
if(!null.converged) return;
// store offset/weights from the null mode
yo = null.yo;
w0 = null.wb;
Yres0 = XYR.rightCols(Ny21).leftCols(Ny); // matrix of phenotypes Y
ColPivHouseholderQR<MatrixXd> qrXw;
qrXw.compute(MatrixXd(Nx1, Nx1).setZero().selfadjointView<Lower>().rankUpdate((XYR.leftCols(Nx1).array().colwise() * w0.array().sqrt()).matrix().adjoint()));
Yres0 -= XYR.leftCols(Nx1).matrix() * qrXw.solve((XYR.leftCols(Nx1).array().colwise() * w0.array()).matrix().transpose() * Yres0);
// full model: logit(g) = X alpha + Y beta
full = fit(XYR, inc_cov, true); // inc_cov, inc_phen = true
if(!full.converged) return;
converged = true;
// problem: null.mub is not at scale [0, 1]
/* cout << "null.mub = " << null.mub.head(5).transpose() << endl; */
VectorXd mub = null.yo;
exp_vector(mub); // mub <- exp(mub)
mub.array() /= (1.0 + mub.array()); // mub <- exp(mub) / (1 + exp(mub))
//
double ll_null = null.loglik_binom(Mask, Ym);
/* double ll_null = 0.0; */
/* ll_null += Ym.col(0).select((1.0 - mub.array()).log(), 0.0).array().sum(); // controls */
/* ll_null += Ym.col(1).select(mub.array().log(), 0.0).array().sum(); // cases */
if(firth_binom) {
MatrixXd null_Info = Yres0.transpose() * (Yres0.array().colwise() * w0.array()).matrix();
LLT<MatrixXd> llt_null(null_Info);
ll_null += llt_null.matrixL().toDenseMatrix().diagonal().array().log().sum();
}
double ll_full;
if(full.firth_binom) {
LLT<MatrixXd> llt_full(full.Info);
ll_full = full.loglik_binom_firth(Mask, Ym, llt_full);
} else {
ll_full = full.loglik_binom(Mask, Ym);
}
boost::math::chi_squared dist(Ny);
/* double stat_lrt = 2 * (full.loglik - null.loglik); */
double stat_lrt = 2 * (ll_full - ll_null);
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else if(approx_offset && response == "multinom") {
// null model
null = fit(XYR, inc_cov, false); // inc_cov, inc_phen = false
if(!null.converged) return;
// store offset vectors
yo = null.yo;
yo_int = null.yo_int;
// full model: logit(g) = X alpha + Y beta
full = fit(XYR, inc_cov, true); // inc_cov, inc_phen = true
if(!full.converged) return;
converged = true;
boost::math::chi_squared dist(Ny);
double stat_lrt = 2 * (full.loglik - null.loglik);
/* cout << "stat_lrt = " << stat_lrt << " full.loglik = " << full.loglik << " null.loglik = " << null.loglik << endl; */
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else {
// null model: logit(g) = X alpha
null = fit(XYR, inc_cov, false); // inc_cov, inc_phen = false
if(!null.converged) return;
// full model: logit(g) = X alpha + Y beta
full = fit(XYR, inc_cov, true); // inc_cov, inc_phen = true
if(!full.converged) return;
converged = true;
boost::math::chi_squared dist(Ny);
double stat_lrt = 2 * (full.loglik - null.loglik);
/* cout << " lrt = " << stat_lrt << " = " << full.loglik << " - " << null.loglik << endl; */
pval_test = (stat_lrt < 0) ? 1 : boost::math::cdf(boost::math::complement(dist, stat_lrt));
}
// store results
if(converged) {
bhat_y = full.bhat.tail(Ny);
}
}
void MultiPhen::run_test_score(const Eigen::Ref<const Eigen::MatrixXd> & XYR, bool inc_cov)
{
bool _firth_binom = firth_binom, _firth_multinom = firth_multinom, _approx_offset = approx_offset;
firth_binom = false; firth_multinom = false; approx_offset = false;
reset_model(); // reset model fit results
executed = true;
FitOrdinal null = fit(XYR, inc_cov, false); // inc_cov, inc_phen = false
if(!null.converged) { return; }
converged = true;
if(trace) { cnt_updates += null.cnt_updates; it += null.it; }
pval_test = test_score(null, Mask, Ym, yb, XYR, inc_cov);
firth_binom = _firth_binom; firth_multinom = _firth_multinom; approx_offset = _approx_offset;
}
void MultiPhen::setup_x(const VectorXb & _Mask, const Eigen::MatrixXd& XYR, unsigned int n_cov, unsigned int n_phen,
bool _pos_intercept_first, bool _pos_phen_first)
{
// check
if(XYR.cols() != 2 + n_cov + 2*n_phen) throw std::runtime_error("setup_x: dimensions XYR");
if(XYR.rows() != _Mask.size()) throw std::runtime_error("setup_x: dimensions XYR and Mask");
// extract dimensions from XYR
N = XYR.rows();
/* Ncov = n_cov; // Nb = ncat1 + Ncov, where ncat1 depend on g */
Nx = n_cov; Nx1 = n_cov + 1; Ny = n_phen; Ny1 = n_phen + 1; Ny21 = Ny1 + n_phen;
pos_intercept_first = _pos_intercept_first;
pos_phen_first = _pos_phen_first;
// Mask
Mask = _Mask; // VectorXb::Constant(N, true);
Neff = Mask.array().cast<double>().sum();
// update status
set_x = true;
}
void MultiPhen::reset_model()
{
executed = false; converged = false;
pval_test = -1.0;
it = 0; cnt_updates = 0;
}
void MultiPhen::setup_approx_offset()
{
if(!set_y) throw std::runtime_error("setup_approx_offset: set_y is false");
if(mac_approx_offset == 0) {
approx_offset = false;
} else if(mac_approx_offset == 1) {
approx_offset = true;
} else if(mac_approx_offset > 1) {
if(Ncat_minor <= mac_approx_offset) approx_offset = false;
else approx_offset = true;
}
}
void MultiPhen::setup_y(const Eigen::VectorXd & _g)
{
// Eigen::VectorXi g = _g.cast<int>(); // 1.6 -> 1
Eigen::VectorXi g = _g.array().round().cast<int>(); // 1.6 -> 2
unsigned int i;
std::set<int> genotypes; // ordered (!) set of category levels
set<int>::iterator it_set;
// checks
if(N == 0) throw std::runtime_error("setup_y: N == 0");
if(g.size() != N) throw std::runtime_error("setup_y: g.size() != N");
// assign category levels
for(i = 0; i < g.size(); i++) if(Mask(i)) genotypes.insert(g[i]);
// check genotypes levels: 0/1 or 0/1/2
/* for(i = 0, it_set = genotypes.begin(); i < genotypes.size(); i++, it_set++) cout << "genotypes " << i << " = " << *it_set << endl; */
/* cout << "genotypes.size() = " << genotypes.size() << endl; */
if(genotypes.size() == 1) {
/* cerr << "WARNING: number of genotype categories is 1" << endl; */
return;
}
if(!(genotypes.size() == 2 || genotypes.size() == 3)) throw std::runtime_error("setup_y: number of genotype categories must be 2 or 3");
// assign ncat, ncat1
ncat = genotypes.size();
ncat1 = ncat - 1; ncat1sq = ncat1 * ncat1;
// assign response
if(ncat == 2) response = "binom";
else if(ncat == 3) response = "multinom";
else throw std::runtime_error("setup_y: unexpected number of genotype categories");
// assign Ncov, Nb
/* Nb = ncat1 + Ncov; */
// assign Ym
Ym.resize(N, ncat);
Ncat = VectorXi::Constant(ncat, 0);
Ncat_minor = 0;
int Ncat_max = 0;
// loop over a a few genotype categories
for(i = 0, it_set = genotypes.begin(); i < ncat; i++, it_set++) {
Ym.col(i) = Mask.select(g.array() == *it_set, false);
/* Ym.col(i) = (g.array() == *it_set); */
/* Ym.col(i) = Mask.select(Ym.col(i), false); */
Ncat(i) = Ym.col(i).cast<int>().sum();
// get the maximum value in Ncat & minor counts in Ncat (all except the maximum)
if(Ncat(i) > Ncat_max) Ncat_max = Ncat(i);
Ncat_minor += Ncat(i);
}
Ncat_minor -= Ncat_max;
// assign yb if binomial
if(response == "binom") {
yb = Ym.col(1).cast<double>(); // booleans -> 0/1
}
// update status
set_y = true;
}
void MultiPhen::test0(const Eigen::VectorXi & g, const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y,
bool firth_binom,
std::string optim, double tol, unsigned int maxit, bool check_step, double max_step)
{
executed = true;
converged = false;
pval_test = -1.0;
FitOrdinal fit, fit1;
// set up Ordinal model (no Firth)
Ordinal ord;
ord.optim = optim; ord.tol = tol; ord.pseudo_stophalf = pseudo_stophalf; ord.maxit = maxit;
ord.check_step = check_step; ord.max_step = max_step;
ord.firth_binom = false;
// fit null model
fit = ord.fit(g, X);
if(!fit.converged) { return; }
// run Score test
converged = fit.converged;
pval_test = ord.test_score(fit, Y);
// run LRT test (if needed)
if(pval_test < pval_thr) {
pval_test = -1.0;
converged = false;
// prepare new matrix of covariates X + Y
MatrixXd X1(Y.rows(), X.cols() + Y.cols());
if(X.cols()) {
X1.leftCols(X.cols()) = X;
}
X1.rightCols(Y.cols()) = Y;
if(firth_binom & (ord.response == "binom")) {
ord.firth_binom = firth_binom;
// fit null model (Firth) for LRT
fit = ord.fit(g, X1, Y.cols());
if(!fit.converged) { return; }
// fit alternative model (Firth)
fit1 = ord.fit(g, X1);
if(!fit1.converged) { return; }
converged = fit1.converged;
boost::math::chi_squared dist(Y.cols());
double stat_lrt = 2 * (fit1.loglik - fit.loglik);
pval_test = boost::math::cdf(boost::math::complement(dist, stat_lrt));
} else {
// fit alternative model (no Firth)
fit1 = ord.fit(g, X1);
if(!fit1.converged) { return; }
converged = fit1.converged;
boost::math::chi_squared dist(Y.cols());
double stat_lrt = 2 * (fit1.loglik - fit.loglik);
pval_test = boost::math::cdf(boost::math::complement(dist, stat_lrt));
}
}
}
void MultiPhen::test_addcov(const Eigen::VectorXi & g, const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y,
bool firth_binom,
std::string optim, double tol, unsigned int maxit, bool check_step, double max_step)
{
executed = true;
converged = false;