-
Notifications
You must be signed in to change notification settings - Fork 0
/
automix.c
executable file
·1599 lines (1384 loc) · 37.9 KB
/
automix.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
/* The AutoMix program.
Last edited 25/11/04.
Developed by David Hastie, Department of Mathematics,
University of Bristol, UK as a part of a submission for the
degree of Ph.D. This Ph.D. was supervised by Prof. Peter Green (PJG),
University of Bristol. Special thanks also to Dr. Christophe Andrieu CA),
University of Bristol, for advice on adaptive schemes and mixture fitting.
The AutoMix sampler is free for personal and academic use, but must
reference the sampler as instructed below. For commercial
use please permission must be sought from the author. To seek permission
for such use please send an e-mail to d_hastie@hotmail.com
outlining the desired usage.
Use of the AutoMix sampler is entirely at the user's own risk. It is the
responsibility of the user to ensure that any conclusions made through the
use of the AutoMix sampler are valid. The author accepts no responsibility
whatsoever for any loss, financial or otherwise, that may arise in
connection with the use of the sampler.
The AutoMix sampler is available from http://www.davidhastie.me.uk/AutoMix
Although the sampler may be modified and redistributed, the author
encourages users to register at the above site so that updates of the
software can be received.
Before use, please read the README file bundled with this software.
Users should reference the sampler as instructed on the AutoMix website
(see above). Initially this is likely to be the Ph.D. thesis that
introduces the AutoMix sampler. However, this will hopefully change to
be a published paper in the not too distant future. */
/* Standard library files */
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#define max(A,B) ((A)>(B)?(A):(B))
#define min(A,B) ((A)<(B)?(A):(B))
/* Global constants (please feel free to change as required)
nkmaxmax = maximum dimension of any one model under consideration
kmaxmax = maximum number of models
Lkmaxmax = initial number of mixture components fitted in stage 2 of
AutoMix algorithm */
#define nkmaxmax 20
#define kmaxmax 15
#define Lkmaxmax 30
#define tpi 6.283185307179586477
#define pi 3.141592653589793238
#define logrtpi 0.5*log(tpi)
/* --- Internal functions (described below) ----------------- */
void gauss(double *z,int nkk);
void rt(double *z,int nkk,int dof);
void chol(int nkk,double **B);
void perm(double *work,int nkk);
double ltprob(int dof,double z,double *constt);
double lnormprob(int k,int nkk,int l,double ***mu,
double ****B, double *datai);
double det(int k, int nkk, int l, double ****B);
/* --- External functions -----------------*/
/* Random number functions sdrni and sdrand can be found in sd.c
bundled with this software. References for these functions can be
found within sd.c */
extern void sdrni(unsigned long *seed);
extern double sdrand();
/* Functions rgamma and loggamma can be found in gammafns.c bundled with
with this software. */
extern double rgamma(double s);
extern double loggamma(double s);
/* Function sokal is found in file sokal.c bundled with this software. */
extern void sokal(int n, double *xreal, double *var, double *tau, int *m);
/* --- User supplied functions ------------ */
/* Functions must be supplied in user***.c file (see e.g. usertoy1.c,
usercpt.c etc bundled with this software).
Descriptions:
1. lpost(&k,theta,&llh)
This should be a c function written by the user that evaluates
log posterior (up to an additive constant) at (k,theta). The function
can also return the likelihood at this point in llh.
2. getkmax(&kmax)
This should be a c function written by the user that returns the
number of models kmax.
3. getnk(kmax, nk)
This should be a c function written by the user that returns the dimensions
nk for model k=1,...,kmax.
4. getic(k,nkk,rwm)
This should be a c function written by the user that returns the
possibly random starting point for the rwm in stage 1 of the AutoMix
sampler */
extern double lpost(int k, int nkk, double *theta, double *llh);
extern void getkmax(int *kmax);
extern void getnk(int kmax,int nk[kmax]);
extern void getic(int k, int nkk, double *rwm);
/* ---main program-------------------------- */
int main(int argc,char *argv[]){
/*---Section 1 Declare Variables -------------------------*/
/* ---clock variables ---------------------- */
clock_t starttime,endtime;
double timesecs;
/* ---indexing variables ------------------- */
int t1,t2,i1,i2,j1,j2,k1,l1,l2,sweep,remain;
/* ---counting variables ------------------- */
int nsweep,count,nsweep2,naccrwmb,naccrwms,nacctd,ntryrwmb,ntryrwms,ntrytd;
int nburn,nsokal,nkeep,keep,nsweepr,*nacc,*ntry,*ksummary;
/* ---command line reading parameters ------ */
int numargs,sametest;
char word[20],selector[3],iparam[18];
/* ---filename variables ------------------- */
int check;
FILE *fpk,*fpl,*fpt[kmaxmax],*fpcf,*fpmix,*fplp,*fpp,*fpac,*fpad;
char fname[18],fname1[18],kno[6];
/* ---random no. variables ----------------- */
unsigned long seed;
double u,constt;
int dof;
/* ---logical variables -------------------- */
int doperm;
/* ---State parameters and variables ------- */
int k,kn,kmax,nkk,nkkn,nkmax,lendata;
int *nk;
double *theta,*thetan;
double **data,*propk,*pk;
/* ---Mixture parameters --------------------*/
int l,ln,Lkk,Lkkn,Lkkmin,nparams,ldel,Lkmax;
int *Lk;
double ***mu,****B,****BBT,**detB;
double ***mumin,****Bmin,****BBTmin;
double **lambda,**lambdamin,**w,*logw,**lpdatagivenl,*palloc,*pallocn;
double tol=0.00001,costfn,costfnnew,costfnmin,minlambda;
/* ---RWM parameters ------------------------*/
double *rwm,*rwmn,Z[1],*Znkk;
double **sig,gamma,accept,alphastar=0.25;
/* ---Probabilities ------------------------ */
double lp,lpn,logratio,llh,llhn;
/* ---working arrays and variables --------- */
int indic,stop,natann,forceann,mode;
int *init;
double sum,sigma,wnew,wnewl1,*sumw,sumwnew,sumlambda,*work,thresh;
double *datamean,**M1;
/* ---autocorrelation variables ------------ */
double *xr,var,tau;
int m;
/* ---adaptation parameters ---------------- */
int adapt,reinit,nreinit;
double pkllim;
/* --- Section 2 - Read in Comand Line Variables ----------------- */
starttime=clock();
/* Definition of command line variables and explanation
Prog variable ~ Command line variable ~ Explanation
mode ~ m ~ 0 if mixture fitting, 1 if user supplied mixture params,
2 if AutoRJ
nsweep ~ N ~ no. of reversible jump sweeps in stage 3
nsweep2 ~ n ~ max(n,10000*nk,100000) sweeps in within-model RWM in stage 1
adapt ~ a ~ 1 if RJ adaptation done in stage 3, 0 otherwise
doperm ~ p ~ 1 if random permutation done in stage 3 RJ move, 0 otherwise
seed ~ s ~ random no. seed, 0 uses clock seed
dof ~ t ~ 0 if Normal random variables used in RWM and RJ moves, otherwise
specify integer degrees of freedom of student t variables
fname ~ f ~ filename base */
/* Default values */
nsweep=100000;
nsweep2=100000;
numargs=argc-1;
strcpy(fname,"output");
doperm=1;
seed=0;
mode=0;
adapt=1;
dof=0;
/* Override defaults if user supplies command line options */
if(numargs>0){
for(t1=1;t1<=numargs;t1++){
strcpy(word,argv[t1]);
for(t2=0;t2<2;t2++){
selector[t2]=word[t2];
}
selector[2]='\0';
for(t2=0;t2<17;t2++){
iparam[t2]=word[t2+2];
}
iparam[17]='\0';
sametest=strcmp(selector,"-f");
if(sametest==0){
strcpy(fname,iparam);
continue;
}
sametest=strcmp(selector,"-N");
if(sametest==0){
nsweep=atoi(iparam);
continue;
}
sametest=strcmp(selector,"-n");
if(sametest==0){
nsweep2=max(atoi(iparam),100000);
continue;
}
sametest=strcmp(selector,"-s");
if(sametest==0){
seed=atoi(iparam);
continue;
}
sametest=strcmp(selector,"-p");
if(sametest==0){
doperm=atoi(iparam);
continue;
}
sametest=strcmp(selector,"-m");
if(sametest==0){
mode=atoi(iparam);
continue;
}
sametest=strcmp(selector,"-a");
if(sametest==0){
adapt=atoi(iparam);
continue;
}
sametest=strcmp(selector,"-t");
if(sametest==0){
dof=atoi(iparam);
continue;
}
}
}
sdrni(&seed);
/* --- Section 3 - Initial File handling --------------------- */
sprintf(fname1,fname);
strcat(fname1,"_log.data");
fpl = fopen(fname1,"w");
sprintf(fname1,fname);
strcat(fname1,"_pk.data");
fpp = fopen(fname1,"w");
sprintf(fname1,fname);
strcat(fname1,"_ac.data");
fpac = fopen(fname1,"w");
sprintf(fname1,fname);
strcat(fname1,"_adapt.data");
fpad = fopen(fname1,"w");
sprintf(fname1,fname);
strcat(fname1,"_cf.data");
fpcf = fopen(fname1,"w");
/* Print user options to log file */
fprintf(fpl,"seed: %ld\n",seed);
fprintf(fpl,"m: %d\n",mode);
fprintf(fpl,"a: %d\n",adapt);
fprintf(fpl,"p: %d\n",doperm);
fprintf(fpl,"n: %d\n",nsweep2);
fprintf(fpl,"N: %d\n",nsweep);
/* Check user has supplied mixture parameters if trying to use mode 1.
If not default back to mode 0 */
if(mode==1){
sprintf(fname1,fname);
strcat(fname1,"_mix.data");
if((fpmix = fopen(fname1,"r"))==NULL){
printf("\nMixture file doesn't exist:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
}
}
/* --- Section 4.0 - Read in key variables from user functions -*/
getkmax(&kmax);
if(kmax>kmaxmax){
printf("\nError:kmax too large \n");
return 0;
}
else if(kmax<0){
printf("\nError:negative kmax \n");
return 0;
}
nk=(int*)malloc(kmax*sizeof(int));
Lk=(int*)malloc(kmax*sizeof(int));
ksummary=(int*)malloc(kmax*sizeof(int));
getnk(kmax,nk);
nkmax=nk[0];
ksummary[0]=0;
for(k1=1;k1<kmax;k1++){
nkmax=max(nk[k1],nkmax);
ksummary[k1]=0;
}
lambda=(double**)malloc(kmax*sizeof(double));
lambdamin=(double**)malloc(kmax*sizeof(double));
mu=(double***)malloc(kmax*sizeof(double));
mumin=(double***)malloc(kmax*sizeof(double));
BBT=(double****)malloc(kmax*sizeof(double));
BBTmin=(double****)malloc(kmax*sizeof(double));
B=(double****)malloc(kmax*sizeof(double));
Bmin=(double****)malloc(kmax*sizeof(double));
detB=(double**)malloc(kmax*sizeof(double));
sig=(double**)malloc(kmax*sizeof(double));
for(k1=0;k1<kmax;k1++){
nkk=nk[k1];
lambda[k1]=(double*)malloc(Lkmaxmax*sizeof(double));
lambdamin[k1]=(double*)malloc(Lkmaxmax*sizeof(double));
mu[k1]=(double**)malloc(Lkmaxmax*sizeof(double));
mumin[k1]=(double**)malloc(Lkmaxmax*sizeof(double));
BBT[k1]=(double***)malloc(Lkmaxmax*sizeof(double));
BBTmin[k1]=(double***)malloc(Lkmaxmax*sizeof(double));
B[k1]=(double***)malloc(Lkmaxmax*sizeof(double));
Bmin[k1]=(double***)malloc(Lkmaxmax*sizeof(double));
detB[k1]=(double*)malloc(Lkmaxmax*sizeof(double));
sig[k1]=(double*)malloc(nkk*sizeof(double));
for(l1=0;l1<Lkmaxmax;l1++){
mu[k1][l1]=(double*)malloc(nkk*sizeof(double));
mumin[k1][l1]=(double*)malloc(nkk*sizeof(double));
BBT[k1][l1]=(double**)malloc(nkk*sizeof(double));
BBTmin[k1][l1]=(double**)malloc(nkk*sizeof(double));
B[k1][l1]=(double**)malloc(nkk*sizeof(double));
Bmin[k1][l1]=(double**)malloc(nkk*sizeof(double));
for(j1=0;j1<nkk;j1++){
BBT[k1][l1][j1]=(double*)malloc(nkk*sizeof(double));
BBTmin[k1][l1][j1]=(double*)malloc(nkk*sizeof(double));
B[k1][l1][j1]=(double*)malloc(nkk*sizeof(double));
Bmin[k1][l1][j1]=(double*)malloc(nkk*sizeof(double));
}
}
}
/* --- Section 5.1 - Read in mixture parameters if mode 1 (m=1) --- */
/* These parameters are used if mode 1 (m=1) of the AutoMix sampler is
used. Note that if the parameters are unavailable or inconsistent with
the user supplied functions or unavailable go straight to section 5.2
where initial within-model RWM are performed */
if(mode>2){
printf("\nInvalid mode entered. Mode must be 0,1,2");
return -100;
}
else if(mode==1){
if((check=fscanf(fpmix,"%d",&k1))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
if(k1!=kmax){
printf("\nFile kmax contradicts getkmax function:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
for(k1=0;k1<kmax;k1++){
if((check=fscanf(fpmix,"%d",&j1))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
if(j1!=nk[k1]){
printf("\nFile kmax contradicts getnk function:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
}
for(k1=0;k1<kmax;k1++){
nkk=nk[k1];
for(j1=0;j1<nkk;j1++){
if((check=fscanf(fpmix,"%lf",&(sig[k1][j1])))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
}
if((check=fscanf(fpmix,"%d",&(Lk[k1])))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
Lkk=Lk[k1];
for(l1=0;l1<Lkk;l1++){
if((check=fscanf(fpmix,"%lf",&(lambda[k1][l1])))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
for(j1=0;j1<nkk;j1++){
if((check=fscanf(fpmix,"%lf",&(mu[k1][l1][j1])))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
}
for(j1=0;j1<nkk;j1++){
for(j2=0;j2<=j1;j2++){
if((check=fscanf(fpmix,"%lf",&(B[k1][l1][j1][j2])))==EOF){
printf("\nEnd of file encountered before parameters read:");
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
}
}
}
sumlambda=0.0;
for(l1=0;l1<Lkk;l1++){
sumlambda+=lambda[k1][l1];
}
if(sumlambda<0.99999||sumlambda>1.00001){
printf("\nComponents weights read do not sum to one for k=%d:",k1);
printf("\nContinuing using RWM to estimate parameters");
mode=0;
goto RWMSTART;
}
if(sumlambda<1.0||sumlambda>1.0){
for(l1=0;l1<Lkk;l1++){
lambda[k1][l1]/=sumlambda;
}
}
}
if(!(fpmix==NULL)){
fclose(fpmix);
}
}
else if(mode==0||mode==2){
/* --- Section 5.2 - Within-model runs if mixture parameters unavailable -*/
RWMSTART:
for(k1=0;k1<kmax;k1++){
/* --- Section 5.2.1 - RWM Within Model (Stage 1) -------*/
nkk=nk[k1];
nparams=nkk+(nkk*(nkk+1))/2;
lendata=1000*nkk;
nsweepr=max(nsweep2,10000*nkk);
nburn=nsweepr/10;
nsweepr+=nburn;
data=(double**) malloc(lendata*sizeof(double));
for(i1=0;i1<lendata;i1++){
data[i1]=(double*)malloc(nkk*sizeof(double));
}
rwm=(double*)malloc(nkk*sizeof(double));
rwmn=(double*)malloc(nkk*sizeof(double));
nacc=(int*)malloc(nkk*sizeof(int));
ntry=(int*)malloc(nkk*sizeof(int));
Znkk=(double*)malloc(nkk*sizeof(double));
init=(int*)malloc(nkk*sizeof(int));
printf("\nRWM for Model %d",k1+1);
fprintf(fpl,"\nRWM for Model %d",k1+1);
fprintf(fpcf,"RWM for Model %d\n",k1+1);
fprintf(fpad,"RWM for Model %d\n",k1+1);
fflush(NULL);
getic(k1,nkk,rwm);
for(j1=0;j1<nkk;j1++){
rwmn[j1]=rwm[j1];
sig[k1][j1]=10.0;
nacc[j1]=0;
ntry[j1]=0;
}
lp=lpost(k1,nkk,rwm,&llh);
i2=0;
remain=nsweepr;
for(sweep=1;sweep<=nsweepr;sweep++){
remain--;
if((sweep>=nburn)&&(fmod((sweep-nburn),((nsweepr-nburn)/10))<tol)){
printf("\nNo. of iterations remaining: %d",remain);
fflush(NULL);
}
u=sdrand();
if(sweep>nburn&&u<0.1){
if(dof>0){
rt(Znkk,nkk,dof);
}
else{
gauss(Znkk,nkk);
}
for(j1=0;j1<nkk;j1++){
rwmn[j1]=rwm[j1]+sig[k1][j1]*Znkk[j1];
}
lpn=lpost(k1,nkk,rwmn,&llhn);
if(sdrand()<exp(max(-30.0,min(0.0,lpn-lp)))){
for(j1=0;j1<nkk;j1++){
rwm[j1]=rwmn[j1];
}
lp=lpn;
llh=llhn;
}
}
else{
gamma=10.0*pow(1.0/(sweep+1),2.0/3.0);
for(j1=0;j1<nkk;j1++){
rwmn[j1]=rwm[j1];
}
for(j1=0;j1<nkk;j1++){
if(dof>0){
rt(Z,1,dof);
}
else{
gauss(Z,1);
}
rwmn[j1]=rwm[j1]+sig[k1][j1]*Z[0];
lpn=lpost(k1,nkk,rwmn,&llhn);
accept=min(1,exp(max(-30.0,min(0.0,lpn-lp))));
if(sdrand()<accept){
(nacc[j1])++;
(ntry[j1])++;
rwm[j1]=rwmn[j1];
lp=lpn;
llh=llhn;
sig[k1][j1]=max(0,sig[k1][j1]-gamma*(alphastar-1));
}
else{
(ntry[j1])++;
rwmn[j1]=rwm[j1];
sig[k1][j1]=max(0,sig[k1][j1]-gamma*(alphastar));
}
}
}
if(remain<(10000*nkk)&&fmod(remain,10.0)<0.05){
for(j1=0;j1<nkk;j1++){
data[i2][j1]=rwm[j1];
}
i2++;
}
if(fmod(sweep,100.0)<0.05){
for(j1=0;j1<nkk;j1++){
fprintf(fpad,"%lf %lf ",sig[k1][j1],
(double)nacc[j1]/(double)ntry[j1]);
}
fprintf(fpad,"\n");
}
}
free(init);
free(rwm);
free(rwmn);
free(nacc);
free(ntry);
free(Znkk);
/* --- Section 5.2.2 - Fit Mixture to within-model sample, (stage 2)- */
/* Note only done if mode 0 (m=0) if mode m=2, go to section 5.2.3*/
/* Mixture fitting done component wise EM algorithm described in
Figueiredo and Jain, 2002 (see thesis for full reference) */
printf("\nMixture Fitting: Model %d",k1+1);
if(mode==0){
Lkk=Lkmaxmax;
init=(int*)malloc(Lkk*sizeof(int));
l1=0;
while(l1<Lkk){
indic=0;
u=sdrand();
init[l1]=(int)floor(lendata*u);
if(l1>0){
for(l2=0;l2<l1;l2++){
if(init[l2]==init[l1]){
indic=1;
break;
}
}
}
if(indic==0){
l1++;
}
}
datamean=(double*)malloc(nkk*sizeof(double));
M1=(double**)malloc(nkk*sizeof(double));
for(j1=0;j1<nkk;j1++){
M1[j1]=(double*)malloc(nkk*sizeof(double));
}
for(j1=0;j1<nkk;j1++){
datamean[j1]=0.0;
for(i1=0;i1<lendata;i1++){
datamean[j1]+=data[i1][j1];
}
datamean[j1]/=((double)lendata);
}
for(j1=0;j1<nkk;j1++){
for(j2=0;j2<nkk;j2++){
M1[j1][j2]=0;
for(i1=0;i1<lendata;i1++){
M1[j1][j2]+=(data[i1][j1]-datamean[j1])*
(data[i1][j2]-datamean[j2]);
}
M1[j1][j2]/=((double)lendata);
}
}
sigma=0.0;
for(j1=0;j1<nkk;j1++){
sigma+=M1[j1][j1];
}
sigma/=(10.0*nkk);
for(l1=0;l1<Lkk;l1++){
for(j1=0;j1<nkk;j1++){
mu[k1][l1][j1]=data[init[l1]][j1];
BBT[k1][l1][j1][j1]=sigma;
B[k1][l1][j1][j1]=BBT[k1][l1][j1][j1];
for(j2=0;j2<j1;j2++){
BBT[k1][l1][j1][j2]=0.0;
B[k1][l1][j1][j2]=BBT[k1][l1][j1][j2];
}
}
chol(nkk,B[k1][l1]);
lambda[k1][l1]=1.0/Lkk;
}
w=(double**)malloc(lendata*sizeof(double));
logw=(double*)malloc(Lkk*sizeof(double));
lpdatagivenl=(double**)malloc(lendata*sizeof(double));
for(i1=0;i1<lendata;i1++){
w[i1]=(double*)malloc(Lkk*sizeof(double));
lpdatagivenl[i1]=(double*)malloc(Lkk*sizeof(double));
}
for(i1=0;i1<lendata;i1++){
sum=0.0;
for(l1=0;l1<Lkk;l1++){
lpdatagivenl[i1][l1]=lnormprob(k1,nkk,l1,mu,B,data[i1]);
logw[l1]=log(lambda[k1][l1])+lpdatagivenl[i1][l1];
w[i1][l1]=exp(logw[l1]);
sum+=w[i1][l1];
}
for(l1=0;l1<Lkk;l1++){
w[i1][l1]/=sum;
}
}
sumw=(double*)malloc(Lkk*sizeof(double));
stop=0;
count=0;
while(!stop){
count++;
l1=0;
natann=0;
forceann=0;
while(l1<Lkk){
sumwnew=0.0;
for(l2=0;l2<Lkk;l2++){
sumw[l2]=0.0;
for(i1=0;i1<lendata;i1++){
sumw[l2]+=w[i1][l2];
}
wnew=max(0.0,(sumw[l2]-nparams/2.0));
if(l2==l1){
wnewl1=wnew;
}
sumwnew+=wnew;
}
lambda[k1][l1]=wnewl1/sumwnew;
sumlambda=0.0;
for(l2=0;l2<Lkk;l2++){
sumlambda+=lambda[k1][l2];
}
for(l2=0;l2<Lkk;l2++){
lambda[k1][l2]/=sumlambda;
}
if(lambda[k1][l1]>0.005){
/*changed to 0.005 from 0.0 -renormalise else */
for(j1=0;j1<nkk;j1++){
mu[k1][l1][j1]=0.0;
for(i1=0;i1<lendata;i1++){
mu[k1][l1][j1]+=data[i1][j1]*w[i1][l1];
}
mu[k1][l1][j1]/=sumw[l1];
for(j2=0;j2<=j1;j2++){
BBT[k1][l1][j1][j2]=0.0;
for(i1=0;i1<lendata;i1++){
BBT[k1][l1][j1][j2]+=(data[i1][j1]-mu[k1][l1][j1])*
(data[i1][j2]-mu[k1][l1][j2])*w[i1][l1];
}
BBT[k1][l1][j1][j2]/=sumw[l1];
B[k1][l1][j1][j2]=BBT[k1][l1][j1][j2];
}
}
chol(nkk,B[k1][l1]);
for(i1=0;i1<lendata;i1++){
lpdatagivenl[i1][l1]=lnormprob(k1,nkk,l1,mu,B,data[i1]);
}
l1++;
}
else{
if(fmod(Lkk,5)<0.05){
printf("\n");
}
printf("%d(%d-n) ",Lkk,count);
natann=1;
if(l1<(Lkk-1)){
for(l2=l1;l2<(Lkk-1);l2++){
lambda[k1][l2]=lambda[k1][l2+1];
for(j1=0;j1<nkk;j1++){
mu[k1][l2][j1]=mu[k1][l2+1][j1];
for(j2=0;j2<=j1;j2++){
BBT[k1][l2][j1][j2]=BBT[k1][l2+1][j1][j2];
B[k1][l2][j1][j2]=B[k1][l2+1][j1][j2];
}
}
for(i1=0;i1<lendata;i1++){
lpdatagivenl[i1][l2]=lpdatagivenl[i1][l2+1];
}
}
}
Lkk--;
sumlambda=0.0;
for(l2=0;l2<Lkk;l2++){
sumlambda+=lambda[k1][l2];
}
for(l2=0;l2<Lkk;l2++){
lambda[k1][l2]/=sumlambda;
}
}
lpn=0.0;
for(i1=0;i1<lendata;i1++){
sum=0.0;
for(l2=0;l2<Lkk;l2++){
logw[l2]=log(lambda[k1][l2])+lpdatagivenl[i1][l2];
w[i1][l2]=exp(logw[l2]);
sum+=w[i1][l2];
}
if(sum>0){
for(l2=0;l2<Lkk;l2++){
w[i1][l2]/=sum;
}
lpn+=log(sum);
}
else{
/* if no component fits point well make equally likely */
for(l2=0;l2<Lkk;l2++){
w[i1][l2]=1.0/Lkk;
}
lpn+=(-500.0);
}
}
}
sum=0.0;
for(l1=0;l1<Lkk;l1++){
sum+=log(lendata*lambda[k1][l1]/12.0);
}
costfnnew=(nparams/2.0)*sum+(Lkk/2.0)*log(lendata/12.0)+
Lkk*(nparams+1)/2.0-lpn;
if(count==1){
costfn=costfnnew;
}
if(count==1||costfnnew<costfnmin){
Lkkmin=Lkk;
costfnmin=costfnnew;
for(l1=0;l1<Lkk;l1++){
lambdamin[k1][l1]=lambda[k1][l1];
for(j1=0;j1<nkk;j1++){
mumin[k1][l1][j1]=mu[k1][l1][j1];
for(j2=0;j2<=j1;j2++){
Bmin[k1][l1][j1][j2]=B[k1][l1][j1][j2];
}
}
}
}
if((fabs(costfn-costfnnew)<min(tol*fabs(costfn),0.01))&&(count>1)){
if(Lkk==1){
stop=1;
}
else{
if(fmod(Lkk,5)<0.05){
printf("\n");
}
printf("%d(%d-f) ",Lkk,count);
forceann=2;
minlambda=lambda[k1][0];
ldel=0;
for(l1=1;l1<Lkk;l1++){
if(minlambda>lambda[k1][l1]){
minlambda=lambda[k1][l1];
ldel=l1;
}
}
if(ldel<(Lkk-1)){
for(l1=ldel;l1<(Lkk-1);l1++){
lambda[k1][l1]=lambda[k1][l1+1];
for(j1=0;j1<nkk;j1++){
mu[k1][l1][j1]=mu[k1][l1+1][j1];
for(j2=0;j2<=j1;j2++){
BBT[k1][l1][j1][j2]=BBT[k1][l1+1][j1][j2];
B[k1][l1][j1][j2]=B[k1][l1+1][j1][j2];
}
}
for(i1=0;i1<lendata;i1++){
lpdatagivenl[i1][l1]=lpdatagivenl[i1][l1+1];
}
}
}
Lkk--;
sumlambda=0.0;
for(l1=0;l1<Lkk;l1++){
sumlambda+=lambda[k1][l1];
}
for(l1=0;l1<Lkk;l1++){
lambda[k1][l1]/=sumlambda;
}
lpn=0.0;
for(i1=0;i1<lendata;i1++){
sum=0.0;
for(l2=0;l2<Lkk;l2++){
logw[l2]=log(lambda[k1][l2])+lpdatagivenl[i1][l2];
w[i1][l2]=exp(logw[l2]);
sum+=w[i1][l2];
}
if(sum>0){
for(l2=0;l2<Lkk;l2++){
w[i1][l2]/=sum;
}
lpn+=log(sum);
}
else{
/* if no component fits point well make equally likely */
for(l2=0;l2<Lkk;l2++){
w[i1][l2]=1.0/Lkk;
}
lpn+=(-500.0);
}
}
sum=0.0;
for(l1=0;l1<Lkk;l1++){
sum+=log(lendata*lambda[k1][l1]/12.0);
}
costfnnew=(nparams/2.0)*sum+(Lkk/2.0)*log(lendata/12.0)+
Lkk*(nparams+1)/2.0-lpn;
}
}
if(count>5000){
stop=1;
}
costfn=costfnnew;
fprintf(fpcf,"%d %lf %lf %d\n",Lkk,lpn,costfnnew,(natann+forceann));
fflush(NULL);
}
for(j1=0;j1<nkk;j1++){
free(M1[j1]);
}
free(M1);
free(datamean);
for(i1=0;i1<lendata;i1++){
free(data[i1]);
free(w[i1]);
free(lpdatagivenl[i1]);
}
free(w);
free(lpdatagivenl);
free(data);
free(logw);
free(sumw);
free(init);
Lk[k1]=Lkkmin;
for(l1=0;l1<Lkkmin;l1++){
lambda[k1][l1]=lambdamin[k1][l1];
for(j1=0;j1<nkk;j1++){
mu[k1][l1][j1]=mumin[k1][l1][j1];
}
for(j1=0;j1<nkk;j1++){
for(j2=0;j2<=j1;j2++){
B[k1][l1][j1][j2]=Bmin[k1][l1][j1][j2];
}
}
}
}
else if(mode==2){
/* --- Section 5.2.3 - Fit AutoRJ single mu vector and B matrix --*/
/* Note only done if mode 2 (m=2).*/
Lk[k1]=1;
lambda[k1][0]=1.0;
for(j1=0;j1<nkk;j1++){
mu[k1][0][j1]=0.0;
for(i1=0;i1<lendata;i1++){
mu[k1][0][j1]+=data[i1][j1];
}
mu[k1][0][j1]/=((double)lendata);
}
for(j1=0;j1<nkk;j1++){
for(j2=0;j2<=j1;j2++){
B[k1][0][j1][j2]=0.0;
for(i1=0;i1<lendata;i1++){
B[k1][0][j1][j2]+=(data[i1][j1]-mu[k1][0][j1])*
(data[i1][j2]-mu[k1][0][j2]);
}
B[k1][0][j1][j2]/=((double)(lendata-1));
}
}
chol(nkk,B[k1][0]);
for(i1=0;i1<lendata;i1++){
free(data[i1]);
}
free(data);
}
}
}
/* Print mixture parameters to file (log and mix files) for reference
and use in future runs. */
sprintf(fname1,fname);
strcat(fname1,"_mix.data");
fpmix = fopen(fname1,"w");
fprintf(fpmix,"%d\n",kmax);
for(k1=0;k1<kmax;k1++){