-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulticlust.c
1985 lines (1802 loc) · 54.2 KB
/
multiclust.c
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
/**
* @file multiclust.c
* @author Karin Dorman, kdorman@iastate.edu
* @date Wed Dec 5 09:20:48 CST 2012
*
* User interface to multiclust.
*
* TODOS
* [TODO] write the results of parametric bootstrap to a permanent output file
* [TODO] run matrix of hypothesis tests and control FDR (as per Maitra &
* Melnykov) to auto-estimate K
* [TODO] add hypothesis test for H0: mixture vs. HA: admixture
* [TODO] add code to run variable number of initializations, perhaps until the
* current best log likelihood has been observed X times
*/
#include <math.h>
#include "cline.h" /* command line */
#include "multiclust.h"
#define MAKE_1ARRAY MAKE_1ARRAY_RETURN
/* create structures for options, data, and model */
int make_options(options** opt);
int make_data(data** dat);
int make_model(model**);
/* set/parse options and model; verify integrity */
int parse_options(options* opt, data* dat, int argc, const char** argv);
int allocate_model_for_k(options* opt, model* mod, data* dat);
int synchronize(options* opt, data* dat, model* mod);
int simulate_data(data *dat, options *opt, model *mod);
/* do the data fitting or bootstrap */
int timed_model_estimation(options*, data*, model*);
int estimate_model(options* opt, data* dat, model* mod, int bootstrap);
int maximize_likelihood(options* opt, data* dat, model* mod, int bootstrap);
int run_bootstrap(options* opt, data* dat, model* mod);
void print_model_state(options* opt, data* dat, model* mod, int diff, int newline);
double adj_rand(int n, int k1, int k2, int* cl1, int* cl2, int type);
/* cleanup all allocated memory */
void free_options(options* opt);
void free_data(data* dat);
void free_model(model* mod, options* opt);
void free_model_mles(model* mod);
void free_model_data(model* mod, options* opt);
const char* accel_method_abbreviations[NUM_ACCELERATION_METHODS] = {
"EM",
"S1",
"S2",
"S3",
"Q",
};
const char* accel_method_names[NUM_ACCELERATION_METHODS] = {
"No acceleration",
"SQUAREM version 1",
"SQUAREM version 2",
"SQUAREM version 3",
"Quasi Newton",
};
int main(int argc, const char** argv)
{
options* opt = NULL; /* run options */
data* dat = NULL; /* genetic data */
model* mod = NULL; /* model parameters */
int err = NO_ERROR; /* error code */
/*
for (int i=0; i<argc; i++)
fprintf(stderr, " %s", argv[i]);
fprintf(stderr, "\n\n");
exit(0);
*/
#ifdef OLDWAY
fprintf(stdout, "Using OLDWAY code\n");
#endif
/* make various structures to store run information */
if ((err = make_options(&opt)))
goto FREE_AND_EXIT;
/* set up data structure */
if ((err = make_data(&dat)))
goto FREE_AND_EXIT;
/* set up model structure */
if ((err = make_model(&mod)))
goto FREE_AND_EXIT;
/* parse command-line options */
if ((err = parse_options(opt, dat, argc, argv)))
goto FREE_AND_EXIT;
if (opt->simulate) {
if ((err = read_admixture_qfile(dat, mod, opt->admix_qfile)))
goto FREE_AND_EXIT;
if ((err = read_admixture_pfile(dat, mod, opt->admix_pfile)))
goto FREE_AND_EXIT;
if ((err = simulate_data(dat, opt, mod)))
goto FREE_AND_EXIT;
if ((err = write_data(opt, dat, opt->simulate_outfile, 0)))
goto FREE_AND_EXIT;
// force exit, as we are not set up to run yet if (!opt->n_init)
goto FREE_AND_EXIT;
} else {
/* read data */
if ((err = read_file(opt, dat)))
goto FREE_AND_EXIT;
if (opt->verbosity >= TALKATIVE)
mmessage(INFO_MSG, NO_ERROR, "Finished reading data: %u "
"%u-ploid individuals at %u loci.\n", dat->I,
dat->ploidy, dat->L);
}
/* finalize settings that refer to data; check settings */
if ((err = synchronize(opt, dat, mod)))
goto FREE_AND_EXIT;
if (opt->verbosity >= TALKATIVE)
mmessage(INFO_MSG, NO_ERROR, "Finished checking settings: using"
" %s.\n", opt->accel_name);
/* estimate the model(s) using the observed data */
if (opt->n_repeat > 1 && (err = timed_model_estimation(opt, dat, mod)))
goto FREE_AND_EXIT;
if (opt->n_repeat == 1 && (err = estimate_model(opt, dat, mod, 0)))
goto FREE_AND_EXIT;
/* set up parallelization mode */
if (opt->parallel)
printf("%f\n", mod->max_logL);
/* optionally run a bootstrap */
if (opt->n_bootstrap) {
if ((err = run_bootstrap(opt, dat, mod)))
goto FREE_AND_EXIT;
/* TODO write this result to some file! */
fprintf(stdout, "p-value to reject H0: K=%d is %f\n",
mod->null_K, mod->pvalue);
}
FREE_AND_EXIT:
free_model(mod, opt);
free_options(opt);
free_data(dat);
return err;
} /* main */
int simulate_data(data *dat, options *opt, model *mod)
{
MAKE_2ARRAY(dat->IL, dat->I * dat->ploidy, dat->L);
MAKE_1ARRAY(dat->I_K, dat->I);
if (opt->admixture)
MAKE_2ARRAY(dat->IL_K, dat->I * dat->ploidy, dat->L);
for (int i = 0; i < dat->I; i += dat->ploidy)
for (int j = 0; j < dat->ploidy; ++j)
for (int l = 0; l < dat->L; ++l) {
dat->IL_K[i + j][l] = (int) (rand() % mod->K); /* [KSD,TODO] This is not uniform unless RAND_MAX % mod->K == 0. */
if (rand() / (RAND_MAX + 1.) < mod->vpklm[0][dat->IL_K[i + j][l]][l][0])
dat->IL[i + j][l] = 0;
else
dat->IL[i + j][l] = 1;
}
return NO_ERROR;
} /* simulate_data */
/**
* Time model estimation by repeating multiple times. Repeat model-fitting
* process chosen by user _options:n_repeat, compute the total time, and report
* the average time. The purpose of this code is to produce better timing
* information by replication. It is not useful for model fitting, as one
* would normally not want to repeat the same model fit! Currently, this
* function cannot be used to time the bootstrap process.
*
* @param opt options object
* @param dat data object
* @param mod model object
* @return error status
*/
int timed_model_estimation(options* opt, data* dat, model* mod)
{
int err = NO_ERROR;
clock_t start;
int enough_time = opt->repeat_seconds ? 0 : 1;
double esec = 0;
int max_iter = 0;
int max_init = 0;
double sum_init = 0;
double sum_init2 = 0;
double sum_iter = 0;
double sum_iter2 = 0;
double sum_aic_K = 0;
double sum_aic_K2 = 0;
double sum_bic_K = 0;
double sum_bic_K2 = 0;
double sum_ll = 0;
double sum_ll2 = 0;
double sum_ar = 0;
double sum_ar2 = 0;
double max_ll = -INFINITY;
double min_aic = 0, min_bic = 0;
double max_ar = -1;
double first_ll = -INFINITY;
double max_ll_rand = 0;
int first_hit_index = 0;
int converged_repeats = 0;
int n_repeats = 0;
int target_reached = 0;
/* time multiple runs */
start = clock();
for (; n_repeats < opt->n_repeat || !enough_time;) {
if ((err = estimate_model(opt, dat, mod, 0)))
return err;
if (mod->n_init > max_init)
max_init = mod->n_init;
if (mod->n_max_iter > max_iter)
max_iter = mod->n_max_iter;
/* [TODO] assumes no repetitions inside estimate_mode() */
if (mod->max_logL > max_ll) {
max_ll = mod->max_logL;
min_aic = mod->aic;
min_bic = mod->bic;
max_ll_rand = mod->arand;
if (!converged(opt, mod, first_ll)) {
first_ll = mod->max_logL;
first_hit_index = n_repeats;
}
}
if (mod->arand > max_ar)
max_ar = mod->arand;
sum_init += mod->n_init;
sum_init2 += mod->n_init * mod->n_init;
sum_iter += mod->n_total_iter;
sum_iter2 += mod->n_total_iter * mod->n_total_iter;
sum_aic_K += mod->aic_K;
sum_aic_K2 += mod->aic_K * mod->aic_K;
sum_bic_K += mod->bic_K;
sum_bic_K2 += mod->bic_K * mod->bic_K;
sum_ll += mod->max_logL;
sum_ll2 += mod->max_logL * mod->max_logL;
if (opt->afile) {
sum_ar += mod->arand;
sum_ar2 += mod->arand * mod->arand;
}
n_repeats++;
if (mod->ever_converged)
converged_repeats++;
if (mod->n_targetll_times)
target_reached++;
esec = ((double)clock() - start) / CLOCKS_PER_SEC;
if (opt->verbosity > SILENT) {
print_model_state(opt, dat, mod,
((double)clock() - start) / CLOCKS_PER_SEC, 0);
fprintf(stdout, " %f %f %d %d", esec, esec / n_repeats,
target_reached, converged_repeats);
fprintf(stdout, " %f", max_ll);
if (opt->target_ll)
fprintf(stdout, " %f", opt->desired_ll);
else
fprintf(stdout, " NA");
fprintf(stdout, " %d %d %d %d", opt->target_revisit,
n_repeats, opt->n_repeat, opt->repeat_seconds);
fprintf(stdout, "\n");
}
/* check time spent against required min and max*/
if (!enough_time || opt->max_repeat_seconds) {
if (!enough_time && esec > opt->repeat_seconds)
enough_time = 1;
if (opt->max_repeat_seconds && esec > opt->max_repeat_seconds)
break;
}
}
if (opt->verbosity >= SILENT) {
fprintf(stdout, "Data, Method, Model: %s, %s, %s\n", opt->filename,
opt->accel_abbreviation,
opt->admixture && opt->eta_constrained
? "admix constrained" : opt->admixture ? "admix" : "mix");
fprintf(stdout, "Run: %e %e %e %e n=%d i=%d u=(%f,%d) w=(%d,%d)\n",
opt->abs_error, opt->rel_error, opt->eta_lower_bound,
opt->p_lower_bound, opt->n_init, opt->n_init_iter, opt->desired_ll,
opt->target_revisit, opt->n_repeat, opt->repeat_seconds);
fprintf(stdout, "Number of repetitions: %d of %d requested, %d converged, %d reach target\n",
n_repeats, opt->n_repeat, converged_repeats, target_reached);
fprintf(stdout, "Average time: %fs (total: %fs; target: %d)\n",
esec / n_repeats, esec, opt->repeat_seconds);
fprintf(stdout, "Average log likelihood: %f (+/- %f)\n",
sum_ll / n_repeats, sqrt((sum_ll2 - sum_ll * sum_ll / n_repeats)
/ (n_repeats - 1)));
fprintf(stdout, "Maximum log likelihood: %f first hit at run %d (AIC %f; BIC %f; RAND: %f)\n",
max_ll, first_hit_index, min_aic, min_bic, max_ll_rand);
fprintf(stdout, "Adjusted RAND: avg = %f +/- %f; max = %f\n",
sum_ar / n_repeats, sqrt((sum_ar2 - sum_ar * sum_ar / n_repeats)
/ (n_repeats - 1)), max_ar);
if (opt->max_K != opt->min_K) {
fprintf(stdout, "Average K (AIC): %f (+/- %f)\n",
sum_aic_K / n_repeats, sqrt((sum_aic_K2 -
sum_aic_K * sum_aic_K / n_repeats) / (n_repeats - 1)));
fprintf(stdout, "Average K (BIC): %f (+/- %f)\n",
sum_bic_K / n_repeats, sqrt((sum_bic_K2 - sum_bic_K
* sum_bic_K / n_repeats) / (n_repeats - 1)));
}
else {
fprintf(stdout, "Total initializations, iterations: %d, %d\n",
(int)sum_init, (int)sum_iter);
fprintf(stdout, "Average initializations: %f (+/- %f)"
" [%e, %e]\n", sum_init / n_repeats, sqrt((sum_init2
- sum_init * sum_init / n_repeats) / (n_repeats - 1)),
sum_init2, sum_init);
fprintf(stdout, "Average iterations: %f (+/- %f) [%e %e]\n",
sum_iter / sum_init, sqrt((sum_iter2 - sum_iter
* sum_iter / sum_init) / (sum_init - 1)),
sum_iter2, sum_iter);
fprintf(stdout, "Maximum initializations: %d\n",
max_init);
fprintf(stdout, "Maximum iterations: %d\n", max_iter);
}
}
return err;
} /* timed_model_estimation */
/**
* Estimate model(s) using maximum likelihood. For each model, the function
* allocates the model (parameters), maximizes the likelihood (probably using
* multiple initializations), extracts relevant statistics (mles, log
* likelihood), and frees the model. Currently, the code either tests H0
* against HA (and aborts if the HA log likelihood does not exceed the H0 log
* likelihood) or fits a series of models from K=_options:min_K to K=_options::max_K.
* Importantly, when hypothesis testing, it fits H0 //before// HA. One could
* modify this code to select other models for fitting.
*
* @param opt options object
* @param dat data object
* @param mod model object
* @param bootstrap indicate if bootstrap run
* @return error status
*/
int estimate_model(options* opt, data* dat, model* mod, int bootstrap)
{
int total_iter = 0;
int err = NO_ERROR;
clock_t start;
double min_bic, min_aic;
start = clock();
/* initialize: if bootstrap, comparing H0: K = mod->null_K vs.
* Ha: K = mod->alt_K; otherwise running for 1, 2, ..., opt->max_K
* so log likelihood will increase as progress through models */
mod->max_logL = -INFINITY;
mod->max_logL_H0 = -INFINITY;
mod->K = opt->n_bootstrap ? mod->null_K : opt->min_K;
dat->max_M = dat->M;
min_aic = min_bic = INFINITY;
//if(opt->block_relax == 1)
// mod->K = 2;
do {
/* Setting the largest size of the U and V arrays to be the larger of K and max_M */
if (dat->max_M < mod->K)
dat->max_M = mod->K;
/* knowing K, can allocate space for parameters */
if ((err = allocate_model_for_k(opt, mod, dat)))
return err;
/* maximize the likelihood; involves multiple initializations */
/* also stores mles in mod->mle_* parameters */
if ((err = maximize_likelihood(opt, dat, mod, bootstrap)))
return err;
/* final output for this model */
if (opt->n_repeat == 1 && opt->verbosity) /* || opt->verbosity > SILENT) */
print_model_state(opt, dat, mod,
((double)clock() - start) / CLOCKS_PER_SEC, 1);
total_iter += mod->n_total_iter;
/* possibly store maximum likelihood under H0 */
if (opt->n_bootstrap && mod->K == mod->null_K)
mod->max_logL_H0 = mod->max_logL;
if (min_aic > mod->aic) {
min_aic = mod->aic;
mod->aic_K = mod->K;
}
if (min_bic > mod->bic) {
min_bic = mod->bic;
mod->bic_K = mod->K;
}
/* free parameters */
free_model_data(mod, opt);
/* choose next K */
if (opt->n_bootstrap && mod->K == mod->null_K)
mod->K = mod->alt_K;
else if (!opt->n_bootstrap && mod->K < opt->max_K)
mod->K++;
else
break;
} while (1);
/* if running bootstrap, record test statistic */
if (opt->n_bootstrap) {
double diff = mod->max_logL - mod->max_logL_H0;
if (diff <= 0) /* == OK, but prob. convergence error */
return message(stderr, __FILE__, __func__, __LINE__,
ERROR_MSG, INTERNAL_ERROR, "Null hypothesis "
"likelihood exceeds alternative hypothesis "
"likelihood. Try increasing number of "
"initializations (command-line option -n)\n");
if (!bootstrap)
mod->ts_obs = diff;
else
mod->ts_bs = diff;
}
return err;
} /* estimate_model */
/**
* Maximize the log likelihood. Given a particular model (admixture/mixture
* and _model::K), initialize the model _options::n_init initializations times,
* maximize the likelihood, and record the result if a better solution is
* found. The best log likelihood is stored in _model::max_logL. The mle
* parameter estimates are stored in _model::mle_pKLM and _model::mle_etak (or
* _model::mle_etaik), but only if the observed data is being fit to H0. In
* addition, if fitting the observed data, the best fitting solution is written
* to file.
*
* @param opt options object
* @param dat data object
* @param mod model object
* @param bootstrap is this a bootstrap run
* @return error status
*/
int maximize_likelihood(options* opt, data* dat, model* mod, int bootstrap)
{
int i;
int err = NO_ERROR;
/* resetting statistics recorded across multiple initializations */
mod->first_max_logL = -INFINITY;
mod->n_init = 0;
mod->n_total_iter = 0;
mod->n_maxll_times = 0;
mod->n_maxll_init = -1;
mod->n_targetll_times = 0;
mod->n_max_iter = 0;
mod->time_stop = 0;
mod->ever_converged = 0;
mod->start = clock();
/* Madeline's simpler version */
if (opt->test_run){
for (i = 0; opt->target_revisit || opt->target_ll /* targeting */
|| opt->n_seconds || i < opt->n_init; i++) { /* timing */
mod->logL = 0.0;
mod->converged = 0;
/* initialize parameters */
if ((err = initialize_model(opt, dat, mod)))
return err;
/* maximize likelihood */
em(opt, dat, mod);
/* !_model::converged b/c _model::iter_stop || _model::time_stop */
if (mod->converged)
mod->ever_converged = 1;
/* record any better solution than previously seen */
if (mod->logL > mod->max_logL) {
mod->max_logL = mod->logL;
mod->aic = aic(mod);
mod->bic = bic(dat, mod);
}
}
} else {
for (i = 0; opt->target_revisit || opt->target_ll /* targeting */
|| opt->n_seconds || i < opt->n_init; i++) { /* timing */
mod->current_i = 0;
mod->current_l = 0;
mod->current_k = 0;
mod->logL = 0.0;
mod->converged = 0;
mod->stopped = 0;
mod->iter_stop = 0;
/* initialize parameters */
if ((err = initialize_model(opt, dat, mod)))
return err;
/* maximize likelihood */
em(opt, dat, mod);
/* !_model::converged b/c _model::iter_stop || _model::time_stop */
if (mod->converged)
mod->ever_converged = 1;
/* add iter/init statistics if converged or timed out */
if (mod->converged || (!mod->n_init && mod->time_stop)) {
mod->n_total_iter += mod->n_iter;
if (mod->n_max_iter < mod->n_iter)
mod->n_max_iter = mod->n_iter;
mod->n_init++;
}
/* solution already seen (up to convergence precision) */
if (mod->converged && converged(opt, mod, mod->first_max_logL)) {
mod->n_maxll_times++;
/* first occurrence of better solution */
}
else if (mod->converged && mod->logL > mod->first_max_logL) {
mod->n_maxll_times = 1;
mod->first_max_logL = mod->logL;
mod->n_maxll_init = mod->n_init;
}
/* record any better solution than previously seen */
if (mod->logL > mod->max_logL) {
mod->max_logL = mod->logL;
mod->aic = aic(mod);
mod->bic = bic(dat, mod);
/* save mles if not bootstrap run and this is H0 */
if (!bootstrap && opt->n_bootstrap && mod->K == mod->null_K) {
#ifndef OLDWAY
COPY_3JAGGED_ARRAY(mod->mle_pKLM, mod->vpklm[mod->pindex], dat->uniquealleles);
#else
COPY_3JAGGED_ARRAY(mod->mle_pKLM, mod->pKLM, dat->uniquealleles);
#endif
if (!opt->admixture || opt->eta_constrained)
#ifndef OLDWAY
COPY_1ARRAY(mod->mle_etak, mod->vetak[mod->pindex], mod->K);
#else
COPY_1ARRAY(mod->mle_etak, mod->etak, mod->K);
#endif
else
#ifndef OLDWAY
COPY_2ARRAY(mod->mle_etaik, mod->vetaik[mod->pindex], mod->K);
#else
COPY_2ARRAY(mod->mle_etaik, mod->etaik, mod->K);
#endif
}
/* write results to file if not bootstrap run */
if (!bootstrap && opt->write_files) {
/* TODO [KSD]: overwriting potentially many
* times for big data bad, but convenient!
*/
if (opt->admixture) {
partition_admixture(dat, mod);
write_file_detail(opt, dat, mod);
popq_admix(opt, dat, mod);
indivq_admix(opt, dat, mod);
} else {
partition_mixture(dat, mod);
write_file_detail(opt, dat, mod);
popq_mix(opt, dat, mod);
indivq_mix(opt, dat, mod);
}
}
if (opt->afile) {
if (!opt->write_files) {
if (opt->admixture)
partition_admixture(dat, mod);
else
partition_mixture(dat, mod);
}
mod->arand = adj_rand(dat->I, opt->pK, mod->K,
opt->partition_from_file, dat->I_K,
ADJUSTED_RAND_INDEX);
}
}
//print_param(opt, dat, mod, mod->tindex);
/* output information if sufficiently verbose and not -w */
if (!bootstrap && opt->verbosity > QUIET && opt->write_files)
fprintf(stdout, "K = %d, initialization = %d: %f "
"(%s) in %3d iterations, %02d:%02d:%02d (%f; %d), seed: %u\n",
mod->K, i, mod->logL,
mod->converged ? "converged" : "not converged",
mod->n_iter,
(int)(mod->seconds_run / 3600),
(int)((((int)mod->seconds_run) % 3600) / 60),
(((int)mod->seconds_run) % 60), mod->max_logL,
mod->n_maxll_times, opt->seed);
/* global mle if K=1; no need for multiple initializations */
if (mod->K == 1)
break;
/* stop if used too much time */
if (mod->time_stop)
break;
/* stop if sufficient repeat of same best solution */
if (opt->target_revisit
&& mod->n_maxll_times >= opt->target_revisit)
break;
/* stop if reach (sufficient times) target log likelihood */
if (opt->target_ll && (mod->logL > opt->desired_ll
|| converged(opt, mod, opt->desired_ll))) {
if (!mod->n_targetll_times)
mod->n_targetll_init = mod->n_init;
mod->n_targetll_times++;
if (!opt->target_revisit)
break;
else if (opt->target_revisit <= mod->n_targetll_times)
break;
}
}
}
return err;
} /* End of maximize_likelihood(). */
/**
* Parametric bootstrap. For __options::n_bootstrap times, simulate bootstrap
* dataset using parameter estimates stored in _model::mle_etak or
* _model::mle_etaik and _model::mle_pKLM. Fit the H0 and HA models using
* exactly the same procedure used to fit the observed data to the same models.
* Record the number of times the test statistic, stored in _model::ts_bs,
* exceeds the observed test statistic, stored in _model::ts_obs. Store the
* resulting estimated p-value in _model::pvalue. While running, this function
* doubles the amount of memory required to store the data, but it clears the
* memory when done.
*
* @param opt options object
* @param dat data object
* @param mod model object
* @return error status
*/
int run_bootstrap(options* opt, data* dat, model* mod)
{
int i;
int ntime = 0;
int err = NO_ERROR;
for (i = 0; i < opt->n_bootstrap; i++) {
fprintf(stdout, "Bootstrap dataset %d (of %d):", i + 1,
opt->n_bootstrap);
/* generate bootstrap dataset under H0 */
if ((err = parametric_bootstrap(opt, dat, mod)))
return err;
/* temporary : if you want to generate some simulation data to play with
write_data(opt, dat, NULL, 1);
*/
/* fit models H0 and HA */
if ((err = estimate_model(opt, dat, mod, 1)))
return err;
/* mod->max_logL is maximum log likelihood under HA */
if (mod->ts_bs >= mod->ts_obs)
ntime++;
fprintf(stdout, " test statistics bs=%f obs=%f (%f)\n",
mod->ts_bs, mod->ts_obs, (double)ntime / (i + 1));
}
mod->pvalue = ntime / opt->n_bootstrap;
cleanup_parametric_bootstrap(dat);
return err;
} /* run_bootstrap */
/**
* Print state of model after maximize_likelihood().
*
* @param opt options object pointer
* @param dat data object pointer
* @param mod model object pointer
* @param diff output of difftime()
*/
void print_model_state(options* opt, data* dat, model* mod, int diff, int newline)
{
if (opt->compact) {
fprintf(stdout, "%s %s %s %d %u %e %e %e %e %f %f %f ",
opt->filename,
opt->accel_abbreviation,
opt->admixture ? "admix" : "mix", mod->K, opt->seed,
opt->eta_lower_bound, opt->p_lower_bound,
opt->abs_error, opt->rel_error,
mod->max_logL, aic(mod), bic(dat, mod));
if (opt->afile)
fprintf(stdout, "%f ", mod->arand);
else
fprintf(stdout, "ND ");
fprintf(stdout, "%s %02d:%02d:%02d %d %d %d %d",
mod->ever_converged ? "converged" : "not",
(int)(diff / 3600),
(int)((diff % 3600) / 60), (diff % 60),
mod->n_total_iter,
mod->n_init, mod->n_maxll_init,
mod->n_maxll_times);
if (opt->target_ll)
fprintf(stdout, " %f %d %d", opt->desired_ll,
mod->n_targetll_init,
mod->n_targetll_times);
if (mod->time_stop)
fprintf(stdout, " time");
if (newline)
fprintf(stdout, "\n");
}
else {
fprintf(stdout, "Dataset: %s\n", opt->filename);
fprintf(stdout, "Method/Model: %s, %s, K=%d\n",
opt->accel_abbreviation,
opt->admixture ? "admix" : "mix", mod->K);
fprintf(stdout, "Convergence: ae=%e, re=%e\n",
opt->abs_error, opt->rel_error);
fprintf(stdout, "Bounds: e=%e, p=%e\n",
opt->eta_lower_bound, opt->p_lower_bound);
fprintf(stdout, "Total number of iterations: %d\n",
mod->n_total_iter);
fprintf(stdout, "Total time: %02d:%02d:%02d\n",
(int)(diff / 3600), (int)((diff % 3600) / 60),
(diff % 60));
fprintf(stdout, "Iteration of max log likelihood: %d "
"of %d\n", mod->n_maxll_init, mod->n_init);
fprintf(stdout, "Number of times reach max log "
"likelihood: %d\n", mod->n_maxll_times);
fprintf(stdout, "Maximum log likelihood: %f\n",
mod->max_logL);
fprintf(stdout, "AIC: %f\n", aic(mod));
fprintf(stdout, "BIC: %f\n", bic(dat, mod));
fprintf(stdout, "Converged: %s\n",
mod->ever_converged ? "yes" : "no");
if (opt->target_ll && mod->n_targetll_times) {
fprintf(stdout, "Iteration of target log "
"likelihood (%f): %d\n",
opt->desired_ll,
mod->n_targetll_init);
fprintf(stdout, "Number of times reach target "
"log likelihood (%f): %d\n",
opt->desired_ll,
mod->n_targetll_times);
}
else if (opt->target_ll && !opt->target_revisit)
fprintf(stdout, "WARNING: Did not reach target log likelihood (%f).\n", opt->desired_ll);
if (opt->target_revisit && opt->target_ll && mod->n_targetll_times < opt->target_revisit)
fprintf(stdout, "WARNING: Did not reach target log likelihood (%f) %d times\n", opt->desired_ll, opt->target_revisit);
else if (opt->target_revisit && !opt->target_ll && mod->n_maxll_times < opt->target_revisit)
fprintf(stdout, "WARNING: Did not reach max. log likelihood %d times\n", opt->target_revisit);
if (mod->time_stop)
fprintf(stdout, "WARNING: Fitting stopped because ran out of time\n");
}
} /* print_model_state */
/**
* Synchronize options, data, and model. This function checks to make sure
* that the user has made self-consistent choices. The user cannot fit K
* subpopulations when there are fewer than K observations. The current
* bootstrap hypothesis testing procedure reads -k <k> from the command line
* and tests H0: K = <k> - 1 vs. HA: K = <k>. This choice is checked and set
* up here.
*
* @param opt options object
* @param dat data object
* @param mod model object
* @return error status
*/
int synchronize(options* opt, data* dat, model* mod)
{
int err = NO_ERROR;
/* [KSD TODO: there is really not much thinking in this...] */
opt->lower_bound = MIN(opt->lower_bound,
1.0 / dat->I / dat->ploidy - 0.5 / dat->I / dat->ploidy);
opt->eta_lower_bound = opt->lower_bound;
opt->p_lower_bound = opt->lower_bound;
/* no backtracking for quasi-Newton acceleration scheme */
if (opt->accel_scheme >= QN) {
opt->adjust_step = 0;
opt->q = opt->accel_scheme - SQS3;
if (opt->accel_abbreviation)
free(opt->accel_abbreviation);
if (opt->accel_name)
free(opt->accel_name);
MAKE_1ARRAY(opt->accel_abbreviation, 4 + (int)log10(opt->q));
MAKE_1ARRAY(opt->accel_name, strlen(accel_method_names[QN])
+ 7 + (int)log10(opt->q));
sprintf(opt->accel_abbreviation, "Q%d", opt->q);
sprintf(opt->accel_name, "%s (q=%d)", accel_method_names[QN],
opt->q);
if (mod->Ainv)
FREE_1ARRAY(mod->Ainv);
if (mod->cutu)
FREE_1ARRAY(mod->cutu);
MAKE_1ARRAY(mod->Ainv, opt->q * opt->q);
MAKE_1ARRAY(mod->cutu, opt->q);
#ifdef LAPACK
if (opt->q > 3) {
MAKE_1ARRAY(mod->ipiv, opt->q + 1);
MAKE_1ARRAY(mod->work, opt->q * opt->q);
}
else
MAKE_1ARRAY(mod->A, opt->q * opt->q);
#else
if (mod->A)
FREE_1ARRAY(mod->A);
if (opt->q > 3)
return message(stderr, __FILE__, __func__, __LINE__,
ERROR_MSG, INVALID_USER_SETUP, "Cannot use "
"acceleration methods greater than 6 (QN3) "
"without linking to lapack.\n");
MAKE_1ARRAY(mod->A, opt->q * opt->q);
#endif
} else {
MAKE_1ARRAY(opt->accel_abbreviation, strlen(
accel_method_abbreviations[opt->accel_scheme]) + 1);
MAKE_1ARRAY(opt->accel_name,
strlen(accel_method_names[opt->accel_scheme]) + 1);
strcpy(opt->accel_abbreviation,
accel_method_abbreviations[opt->accel_scheme]);
strcpy(opt->accel_name, accel_method_names[opt->accel_scheme]);
}
if (dat->I < opt->max_K)
return message(stderr, __FILE__, __func__, __LINE__, ERROR_MSG,
INVALID_USER_SETUP, "Maximum number of clusters (%d) "
"(set with command-line argument -k) cannot exceed "
"the number of individuals (%d)\n", opt->max_K, dat->I);
if (opt->n_bootstrap && opt->max_K <= 1)
return message(stderr, __FILE__, __func__, __LINE__, ERROR_MSG,
INVALID_USER_SETUP, "When bootstrapping, maximum K (%d) "
"(set with command-line argument -k) must exceed 1.",
opt->max_K);
if (opt->n_bootstrap) {
mod->null_K = opt->max_K - 1;
mod->alt_K = opt->max_K;
}
/* if not timed or target seeking, then run once */
if (!opt->target_ll && !opt->target_revisit && !opt->n_seconds
&& !opt->n_init)
opt->n_init = 1;
if (opt->min_K > opt->max_K)
return message(stderr, __FILE__, __func__, __LINE__, ERROR_MSG,
INVALID_USER_SETUP, "Minimum K (%d) must not exceed "
"maximum K (%d).", opt->min_K, opt->max_K);
if (opt->afile)
err = read_afile(opt, dat);
return err;
} /* synchronize */
/**
* Allocate options object and initialize.
*
* @param opt options object pointer reference
* @return error status
*/
int make_options(options** opt)
{
*opt = malloc(sizeof * *opt);
if (*opt == NULL)
return message(stderr, __FILE__, __func__, __LINE__, ERROR_MSG,
MEMORY_ALLOCATION, "options object");
(*opt)->filename = NULL;
(*opt)->filename_file = NULL;
(*opt)->path = "./";
(*opt)->interleaved = 0;
(*opt)->missing_value = MISSING;
(*opt)->imputation_method = 0;
(*opt)->imputed_outfile = NULL;
(*opt)->R_format = 0;
(*opt)->alleles_are_indices = 0;
(*opt)->one_plus = 0;
(*opt)->write_plus_one = 0;
(*opt)->seed = 1234567;
(*opt)->n_init = 50;
/* convergence criterion set to match Lange's definition */
(*opt)->max_iter = 0; /*2000;*/
(*opt)->rel_error = 0; /*1e-6;*/
(*opt)->abs_error = 1e-4;
/* default tests K=6 */
(*opt)->min_K = 6;
(*opt)->max_K = 6;
/* default initialization method: */
(*opt)->initialization_method = RANDOM_CENTERS; // TESTING;
(*opt)->initialization_procedure = NOTHING;/*RAND_EM;*/
(*opt)->n_rand_em_init = 50;
(*opt)->lower_bound = 1e-8;
(*opt)->eta_lower_bound = 1e-8;
(*opt)->p_lower_bound = 1e-8;
/* run settings */
(*opt)->do_projection = 1;
(*opt)->admixture = 0;
(*opt)->eta_constrained = 0;
(*opt)->n_bootstrap = 0;
(*opt)->block_relax = 0;
(*opt)->accel_scheme = 0;
(*opt)->accel_name = NULL;
(*opt)->accel_abbreviation = NULL;
(*opt)->q = 1;
(*opt)->n_init_iter = 0;
(*opt)->n_seconds = 0;
(*opt)->adjust_step = 0;//1000; /* Varadhan2008: \infty */
(*opt)->verbosity = MINIMAL;
(*opt)->compact = 1;
(*opt)->qfile = NULL;
(*opt)->pfile = NULL;
(*opt)->afile = NULL;
(*opt)->target_ll = 0;
(*opt)->desired_ll = 0;
(*opt)->target_revisit = 0;
(*opt)->n_repeat = 1;
(*opt)->repeat_seconds = 0;
(*opt)->max_repeat_seconds = 0;
(*opt)->write_files = 1;
(*opt)->partition_from_file = NULL;
(*opt)->parallel = 0;
(*opt)->outfile_name = NULL;
(*opt)->simulate = 0;
(*opt)->admix_qfile = NULL;
(*opt)->admix_pfile = NULL;
(*opt)->simulate_outfile = "sim.stru";
(*opt)->test_run = 0;
return NO_ERROR;
} /* make_options */
/**
* Free options object.
*
* @param opt options object
* @return void
*/
void free_options(options* opt)
{
if (opt->partition_from_file)
FREE_VECTOR(opt->partition_from_file);
if (opt->accel_name)
free(opt->accel_name);
if (opt->accel_abbreviation)
free(opt->accel_abbreviation);
if (opt)
free(opt);
opt = NULL;
} /* free_options */