-
Notifications
You must be signed in to change notification settings - Fork 3
/
ml_multout.c
1703 lines (1538 loc) · 56.4 KB
/
ml_multout.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
/*
* Copyright (C) 2006 Murphy Lab,Carnegie Mellon University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* For additional information visit http://murphylab.web.cmu.edu or
* send email to murphy@cmu.edu
*/
/*
jg_multout.c
by Jim Gajnak (jgajnak@cmu.edu)
A port of the multout program to Matlab
Most of the author's original comments have been removed. The author's comments that I
left in are prefixed by "#"s (this excludes function seperators)
*/
#define SEEDSAVEMAX 1200000000
/* added to allow Matlab functionality */
#include "mex.h"
/* original includes */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <memory.h>
#include <search.h>
#include <float.h>
/* parms */
int Lambda; /* target partition size */
float Cut1, Cut2; /* for outlier ID */
float SimTol;
/* define the algorithm begin used */
#define BaseSubSampleSize (int)(XCnt/2) /* whence we "lap" */
/* define the means of evaluating a partition as SCRIT or MVECRIT */
/*#include "std.c"*/
/* to allow compilation of the same code on the DECstations */
/* set host ULTRIX or PC */
#define PC 1
#define ULTRIX 2
#define HOST ULTRIX
/* version 6: Ultrix really means OSF/1 */
#if HOST == ULTRIX
# define far /* no need for memory kludges */
# define _fmalloc malloc /* ditto */
# define _ffree free
#endif
#define True -1 /* for use in */
#define False 0 /* setting vars only */
#define SEEDFILE "SEED.DAT" /* to allow variations in seed */
#define ALLCHK(x) if (x == NULL) {mexErrMsgTxt("allocation error\n"); assert(x);}
#define NTOL (double)0.00001 /* newton tolerance */
#define WTOL (double)0.001 /* weight convergence tolerance */
/*#define LTOL 1./(double)(XCnt*VectLen)*/ /* lambda tolerance */
#define LTOL 1./(double)VectLen /* lambda tolerance */ /*12/21/92*/
#define NTIMEOUT 100 /* max newton iters */
#define GMULT 1.2 /* controls ghost precision */
#define dabs(x) (((x) < 0.) ? -(x) : (x))
/* shared parms */
int Trace; /* controls debug trace dump info */
long ItersAllowed;
/* run time parm (for all but simulated annealing) */
float Cut1, Cut2; /* for outlier ID */
/* global data */
int VectLen; /* number of attributes */
int XCnt; /* number of observations */
double *X; /* The observations */
#define XRow(i) (X+(i-1)*VectLen)
#define Xof(i,j) *(X+(i-1)*VectLen+j-1) /* X[i,j] */
double InstanceID = 0.; /* to hash an instance ID using Diag of data */
/* the J set is defined by non-zero JBit indicators */
int *JBits; /* indicators for J set (squander bits) */
int *BestJBits; /* best XJ seen so far */
int *OnesList, *ZerosList; /* indexes of bits set and zero */
double *XBarJ; /* x bar values for the J set */
#define XBarJof(i) *(XBarJ+i-1) /* XBarJ[i] */
double *XJ; /* data matrix corresp. to J set */
#define XJof(i,j) *(XJ+(i-1)*VectLen+j-1) /* XJ[i,j] */
double *ZJ; /* e concat XJ */
#define ZJof(i,j) *(ZJ+(i-1)*(VectLen+1)+j-1) /* ZJ[i,j] */
/* covariance matrix, rectangular space to facilitate GJ inversion */
/* the inverse is going to be in the right half of the C matrix, so */
/* space is not allocated, just a macro to get at the data */
double *C; /* COLUMN MAJOR covariance matrix */
#define Cof(i,j) (*(C+(i-1)+(j-1)*VectLen)) /* C[i,j] */
double *A; /* ZZt */
#define Aof(i,j) (*(A+(i-1)+(j-1)*(VectLen+1))) /* A[i,j] */
double Determinant; /* the product of the pivots, in this case */
#define C_1of(i,j) *(C+VectLen*VectLen+(i-1)+(j-1)*VectLen) /* C-1[i,j] */
#define A_1of(i,j) *(A+(VectLen+1)*(VectLen+1)+(i-1)+(j-1)*(VectLen+1))
long SingularCnt=0; /* count the number of Det=0 seen */
/* many of these vectors are global only to make dynamic allocation easy */
/* the so-called sqresiduals vector is the squared mahalanobis distances */
double *SqResiduals; /* squared distances, zero based */
double *kSqSpace; /* for sorting in compute_k */
double *dTilde; /* modified distances (used in s estimation) */
double *wVector; /* weights vector stored to save comp. & test converg.*/
double *OldwVector; /* last iteration's wieght vector */
double Sumw, Sumv; /* save some time in M iterations */
double mJ2; /* the left hand side of Rouss...(1.24) */
double c1=0., b0=0.; /* "constants" for S estimation " */
double M=0.; /* "constant" for t-biweight */
double ActualBP; /* breakdown point implied by c and b0 <= RequestedBP */
double *uAu; /* local to the descent routine */
/* also need a record for the times when we want to know who is at the dist */
struct ResidRec{
double SqMahalDist; /* distance to the point */
int SampleNum; /* index into X */
};
struct ResidRec *ResidRecs; /* to be used whenever needed */
/* minimization variables */
double ObjectiveValue; /* to be minimized */
double BestObjectiveValue; /* to keep score */
/* Random Number generator declarations */
#define Ua (long)1317 /*a,b, and c are for URan*/
#define Ub (long)27699
#define Uc (long)131072
long seed; /* random number seed (running) */
long SeedSave; /* so we have the original seed as ID */
/* enhanced algorithm declarations */
# define HALFWAY (VectLen + 1) / 2 + XCnt / 4 /*between p+1 and 1/2 samp*/
/* forward declarations */
double Compute_k();
void Set_c_and_b0();
double rho(double d);
void Standardize_X();
void Use_Algo_Rej_Code(); /* // have assumed n==XCnt */
void Pre_Check_Data();
int i_i; /* to be used by copy macro */
#define Copy(x,y,z) for (i_i=0; i_i<(z); i_i++) x[i_i] = y[i_i]
/*---------------------------------------------------------------------------*/
double URan( long *seed)
/*return a uniform 0,1 rv using and returning the seed*/
{
do *seed = (Ua * *seed + Ub) % Uc; while (*seed == 0);
return((double)*seed / (double)Uc);
}
/*--------------------------------------------------------------------------*/
double Norm(double mu, double sd, long *z)
/* return a normal deviate with mean mu and std dev sd,
use seed z */
/* just waste a deviate... */
{
double v1,v2,r;
do {
v1 = 2.0 * URan(z) - 1.;
v2 = 2.0 * URan(z) - 1.;
r = v1*v1 + v2*v2;
} while (r >= 1.0);
return(mu + sd * (v1 * sqrt(-2.0 * log(r)/r)));
}
/*-------------------------------------------------------------------------*/
void Dump_Data(char *msg)
/* dump the X array */
{
int row, col;
mexPrintf("Dump of X data array %s\n",msg);
for (row=1; row<=XCnt; row++) {
for (col=1; col<=VectLen; col++) mexPrintf("%E ",Xof(row,col));
mexPrintf("\n");
}
}
/*-------------------------------------------------------------------------*/
void Make_Room()
/* allocate space for global data structures */
/* everything is made, no matter what you are doing .... */
{
JBits = malloc((XCnt)*sizeof(int));
ALLCHK(JBits)
OnesList = malloc(XCnt*sizeof(int));
ALLCHK(OnesList)
ZerosList = malloc(XCnt*sizeof(int));
ALLCHK(ZerosList)
BestJBits = malloc(XCnt*sizeof(int));
ALLCHK(BestJBits)
XBarJ = malloc(VectLen*sizeof(double));
ALLCHK(XBarJ)
XJ = malloc((XCnt)*VectLen*sizeof(double)); /* lots of room */
ALLCHK(XJ)
ZJ = malloc(sizeof(double)*(size_t)XCnt*(size_t)(VectLen+1)); /* lots */
ALLCHK(ZJ)
C = malloc(VectLen*VectLen*2*sizeof(double));
ALLCHK(C)
A = malloc((VectLen+1)*(VectLen+1)*2*sizeof(double));
ALLCHK(A)
SqResiduals = malloc((XCnt)*sizeof(double));
ALLCHK(SqResiduals)
kSqSpace = malloc((XCnt)*sizeof(double));
ALLCHK(kSqSpace)
dTilde = malloc((XCnt)*sizeof(double));
ALLCHK(dTilde)
wVector = malloc((XCnt)*sizeof(double));
ALLCHK(wVector)
OldwVector = malloc((XCnt)*sizeof(double));
ALLCHK(OldwVector)
ResidRecs = malloc((XCnt)*sizeof(struct ResidRec));
ALLCHK(ResidRecs)
uAu = malloc((XCnt+1)*sizeof(double));
ALLCHK(uAu)
}
/*-------------------------------------------------------------------------*/
void Check_Bits(int JCnt, char *msg)
/* debug tool */
{
int OPos, ZPos; /* to loop through substring lists */
int i, locj; /* to loop through JBits */
locj = 0;
for (i=0; i<XCnt; i++) locj += *(JBits+i);
if (locj != BaseSubSampleSize) {
printf("There are only %d bits rather than %d in J\n%s\n",locj,BaseSubSampleSize,msg);
for (i=0; i<XCnt; i++) printf("%d ",*(JBits+i)); mexPrintf("\n");
mexErrMsgTxt("Fatal error");
}
for (OPos=0; OPos < JCnt; OPos++) if (!(*(JBits+*(OnesList+OPos)))) {
mexPrintf("zero bit Opos=%d, jbit pos is %d\n",OPos, *(OnesList+OPos));
mexPrintf("%s\n",msg);
mexErrMsgTxt("Fatal Error");
}
for (ZPos=0; ZPos < JCnt; ZPos++) if ((*(JBits+*(ZerosList+ZPos)))) {
mexPrintf("one bit Zpos=%d, jbit pos is %d\n",ZPos, *(ZerosList+ZPos));
mexPrintf("%s\n",msg);
mexErrMsgTxt("Fatal Error");
}
mexPrintf("bits OK: %s\n",msg);
for (i=0; i<XCnt; i++) mexPrintf("%d ",*(JBits+i)); mexPrintf("\n");
}
/*-------------------------------------------------------------------------*/
void Create_SubString_Lists(const int JCnt)
/* Update sub-string lists for ones and zeros in JBits */
/* no need to clear first */
/* JCnt is the size of the sub-sample */
/* (this isn't as useful in genetic.c because we may never use them...)*/
{
int row,oh=0,zee=0; /* to loop */
for (row=0; row<XCnt; row++)
if (*(JBits+row)) *(OnesList+oh++) = row; else *(ZerosList+zee++)=row;
}
/*-------------------------------------------------------------------------*/
void Form_XJ()
/* put rows in XJ corresponding to the J set indexes */
/* note that the indicator set is zero based; also note row data vectors*/
{
int Xrow, XJrow, col; /* to loop */
XJrow = 1;
for (Xrow = 1; Xrow <= XCnt; Xrow++) {
if (*(JBits+Xrow-1)) {
for (col = 1; col <= VectLen; col++)
XJof(XJrow, col) = Xof(Xrow, col);
/* the row index is in the J set */
XJrow++;
}
}
}
/*-------------------------------------------------------------------------*/
void Form_ZJ(double *X)
/* put rows in ZJ corresponding to the J set indexes */
/* note that the indicator set is zero based; also note row data vectors*/
/* X is provided as an argument to allow for ghost images */
{
int Zrow, ZJrow, col; /* to loop */
ZJrow = 1;
for (Zrow = 1; Zrow <= XCnt; Zrow ++) {
if (*(JBits+Zrow-1)) {
ZJof(ZJrow, 1) = 1;
for (col = 2; col <= VectLen+1; col++)
ZJof(ZJrow, col) = Xof(Zrow, col-1);
/* the row index is in the J set */
ZJrow++;
}
}
}
/*-------------------------------------------------------------------------*/
void Dump_XJ(const int JCnt, char *msg)
/* dump the bit map and the rows */
/* JCnt is the size of the sub-sample */
{
int row,col; /* to loop */
printf("J set and corresp. data matrix %s\n",msg);
for (row=0; row<XCnt; row++) printf("%2d",*(JBits+row));
printf("\n\n");
for (row=1; row<=JCnt; row++) {
for (col=1; col<=VectLen; col++) printf("%7E ",XJof(row,col));
printf("\n");
}
}
/*-------------------------------------------------------------------------*/
void Dump_ZJ(const int JCnt, char *msg)
/* dump the bit map and the rows */
/* JCnt is the size of the sub-sample */
{
int row,col; /* to loop */
printf("J set and corresp. ZJ: %s\n",msg);
for (row=0; row<XCnt; row++) printf("%2d",*(JBits+row));
printf("\n\n");
for (row=1; row<=JCnt; row++) {
for (col=1; col<=VectLen+1; col++) printf("%7E ",ZJof(row,col));
printf("\n");
}
}
/*-------------------------------------------------------------------------*/
void Compute_XBarJ(const int JCnt)
/* compute XBarJ values (observations are "row" vectors) */
/* JCnt is the size of the sub-sample */
/* very simple */
{
int row, col; /* to loop */
# define XBCOL *(XBarJ+col-1) /* typing aid */
for (col=1; col<=VectLen; col++) {
XBCOL = XJof(1,col);
for (row=2; row<=JCnt; row++) XBCOL += XJof(row,col);
XBCOL = XBCOL / (JCnt);
}
}
/*-------------------------------------------------------------------------*/
void Dump_XBarJ(char *msg)
/* display the estimate of the center */
{
int col; /* to loop */
printf("Dump of Mean for current J set: %s\n",msg);
for (col=1; col <= VectLen; col++) printf(" %E\n", XBarJof(col));
}
/*-------------------------------------------------------------------------*/
void Randomize_JBits(const int JCnt)
/* produce random J bit settings */
/* URan is to (0,1) not [0,1]; JBits is zero based */
/* JCnt is the size of the sub-sample */
{
int setsofar=0; /* keep track of number set */
int spot; /* element to consider setting */
memset(JBits, 0, (XCnt)*sizeof(int));
while (setsofar < JCnt) {
spot = (int)(URan(&seed) * XCnt);
if (!(*(JBits+spot))) {
++setsofar;
++(*(JBits+spot));
}
}
}
/*-------------------------------------------------------------------------*/
void Form_C(const int JCnt)
/* form the covariance matrix for XJ */
/* JCnt is the size of the sub-sample */
{
int i, j; /* current cell in C */
int k; /* to loop through samples */
for (i=1; i<=VectLen; i++) {
for (j=1; j<=i; j++) {
Cof(i,j) = 0;
for (k=1; k<=JCnt; k++) {
Cof(i,j) += (XJof(k,i) - XBarJof(i))
* (XJof(k,j) - XBarJof(j));
}
Cof(i,j) = Cof(i,j) / (double)(JCnt - 1);
}
}
for (i=1; i<=VectLen;i++) for (j=i+1; j<=VectLen;j++) Cof(i,j) = Cof(j,i);
}
/*-------------------------------------------------------------------------*/
void Form_A(const int JCnt)
/* form the ZJ * Trans(ZJ) */
/* JCnt is size of half sample */
{
int i, j; /* current cell in C */
int k; /* to loop through samples */
for (i=1; i<=VectLen+1; i++) {
for (j=1; j<=i; j++) {
Aof(i,j) = 0;
for (k=1; k<=JCnt; k++) {
Aof(i,j) += ZJof(k,i) * ZJof(k,j);
}
}
}
for (i=1; i<=VectLen+1;i++) for (j=i+1; j<=VectLen+1;j++) Aof(i,j) = Aof(j,i);
}
/*-------------------------------------------------------------------------*/
void Dump_C(char *msg)
/* dump the C matrix (COLUMN MAJOR storage, but output the usual way) */
{
int i,j; /* to loop */
printf("Entire rectangle: %s\n",msg);
for (i=0; i<VectLen; i++) {
for (j=0; j<2*VectLen; j++) printf("%.2E ",*(C+i+j*VectLen));
printf("|\n");
}
}
/*-------------------------------------------------------------------------*/
void InvertC(double *C, int VectLen, double *Determinant)
/* things are getting a bit hacked up here..... */
/* assume C is VectLen by VectLen */
/* C must have room for another square on the right */
/* do Gauss-Jordon Elimination on C*x(j) = e(j); Strang 29 */
/* see also page 38 (no use exchanging rows since PDS) */
/* keep a running product of the pivots as the determinant of C */
/* (later, try to do something more efficient (e.g. use Symm)) */
/* COLUMN MAJOR arrays, look out... */
/* pivots are left in original C space, result is on ``right'' side */
{
/* "locals" */
int pivotrow, row, col; /* to loop */
double Pivot; /* C[pivotrow, pivotrow] */
double m; /* multiplier */
/* put I in the right half */
for (row=1; row <= VectLen; row++)
for (col = VectLen+1; col <= 2*VectLen; col++)
if (col == row+VectLen) Cof(row,col) = 1.; else Cof(row,col) = 0.;
/* forward elimination */
*Determinant = 1; /* running product */
for (pivotrow = 1; pivotrow < VectLen; pivotrow++) {
if (Cof(pivotrow,pivotrow) <= 0.0) {
/*printf("bad pivot at row %d, you lose\n",pivotrow);*/
*Determinant = 0;
return;
}
else { /* non-zero pivot in C[row,row] */
Pivot = Cof(pivotrow, pivotrow); /* two uses for pivot */
for (row = pivotrow+1; row <= VectLen; row++) {
m = Cof(row, pivotrow) / Pivot;
for (col = pivotrow; col <= VectLen+pivotrow; col++) {
/* assumes no zero pivots shuffles!!!*/
Cof(row,col) = Cof(row,col) - m * Cof(pivotrow,col);
}
}
}
*Determinant *= Pivot;
}
*Determinant *= Cof(VectLen, VectLen);
if (!*Determinant) {return;}
/* back substitution, pivots are non-zero, so use them */
for (pivotrow = 2; pivotrow <=VectLen; pivotrow++){
Pivot = Cof(pivotrow, pivotrow);
for (row = 1; row < pivotrow; row++) {
if (Cof(row,pivotrow)) {
m = Cof(row,pivotrow) / Pivot;
for (col = pivotrow; col <= VectLen+pivotrow; col++) {
Cof(row,col) = Cof(row,col) - m*Cof(pivotrow, col);
}
}
}
}
/* finally, divide the rows in the inverse by the pivots */
for (row = 1; row <= VectLen; row++)
for (col = VectLen+1; col <= 2*VectLen; col++)
Cof(row, col) = Cof(row,col) / Cof(row,row);
}
/*-------------------------------------------------------------------------*/
void InvertA(double *A, int VL, double *Determinant)
/* things are getting a bit hacked up here..... */
/* (what is needed is a few moments to write a general invert.... */
/* this is hideous (we pass in VL+1 or else.... */
/* see InvertC for details*/
{
/* "locals" */
int pivotrow, row, col; /* to loop */
double Pivot; /* A[pivotrow, pivotrow] */
double m; /* multiplier */
/* put I in the right half */
for (row=1; row <= VL; row++)
for (col = VL+1; col <= 2*VL; col++)
if (col == row+VL) Aof(row,col) = 1; else Aof(row,col) = 0;
/* forward elimination */
*Determinant = 1; /* running product */
for (pivotrow = 1; pivotrow < VL; pivotrow++) {
if (!Aof(pivotrow,pivotrow)) {
*Determinant = 0;
return;
}
else {
/* non-zero pivot in A[row,row] */
Pivot = Aof(pivotrow, pivotrow); /* two uses for pivot */
for (row = pivotrow+1; row <= VL; row++) {
m = Aof(row, pivotrow) / Pivot;
for (col = pivotrow; col <= VL+pivotrow; col++) { /* assumes no zero pivots shuffles!!!*/
Aof(row,col) = Aof(row,col) - m * Aof(pivotrow,col);
}
}
}
*Determinant *= Pivot;
}
*Determinant *= Aof(VL, VL);
if (!*Determinant) return;
/* back substitution, pivots are non-zero, so use them */
for (pivotrow = 2; pivotrow <=VL; pivotrow++){
Pivot = Aof(pivotrow, pivotrow);
for (row = 1; row < pivotrow; row++) {
if (Aof(row,pivotrow)) {
m = Aof(row,pivotrow) / Pivot;
for (col = pivotrow; col <= VL+pivotrow; col++) {
Aof(row,col) = Aof(row,col) - m*Aof(pivotrow, col);
}
}
}
}
/* finally, divide the rows in the inverse by the pivots */
for (row = 1; row <= VL; row++)
for (col = VL+1; col <= 2*VL; col++)
Aof(row, col) = Aof(row,col) / Aof(row,row);
}
/*-------------------------------------------------------------------------*/
int Compare_doubles(const void *arg1, const void *arg2)
/* compare *arg1 and *arg2 as per qsort needs */
/* assume that doubles can never really be equal */
{
if (*(double*)arg1 < *(double*)arg2) return(-1); else return(1);
}
/*--------------------------------------------------------------------------*/
void Compute_Distance_Vector()
/* compute a squared distance vector (called SqResiduals) for the current C_1
and sub-sample
*/
{
double rowsum; /* to accumulate rightmost mult first */
int i; /* index into vector being formed */
int row, col; /* indexes for vector matrix mult. */
/* (row and col refer to c-1) */
for (i=1; i<=XCnt; i++) {
*(SqResiduals+i-1) = 0.;
for (row = 1; row <= VectLen; row++) {
rowsum = 0;
for (col = 1; col <= VectLen; col++) {
rowsum += (Xof(i,col) - XBarJof(col)) * C_1of(row,col);
}
*(SqResiduals+i-1) += rowsum * (Xof(i,row) - XBarJof(row));
}
}
}
/*-------------------------------------------------------------------------*/
void Compute_mJ2()
/* replace the word "median" with (n+p+1)/2 percentile */
/* compute a vector that represents the argument to the med in 1.24 */
/* then find sqrt of its median and place it in global mJ */
/* note that the vector is declared globally for mindless dynamic allocation*/
/* (Could form vectors to save a subtraction at the expense of an assignment*/
/* and loop control; if you have a vector processor, you may want to do it) */
{
Compute_Distance_Vector();
qsort(SqResiduals, XCnt, sizeof(double), Compare_doubles);
mJ2 = *(SqResiduals+(XCnt+VectLen+1)/2);
}
/*-------------------------------------------------------------------------*/
double Mahalanobis_Dist(int SampNo)
/* find the squared mahalanombis distance to the sample SampNo (not 0 based) */
/* using the current C inverse and the current X bar */
{
double rowsum; /* to accumulate rightmost mult first */
double RetVal=0.; /* to collect the distance (squared) */
int row, col; /* indexes for vector matrix mult. */
/* (row and col refer to c inverse) */
for (row = 1; row <= VectLen; row++) {
rowsum = 0.;
for (col = 1; col <= VectLen; col++) {
rowsum += (Xof(SampNo,col) - XBarJof(col)) * C_1of(row,col);
}
RetVal += rowsum * (Xof(SampNo,row) - XBarJof(row));
}
return RetVal;
}
/*-------------------------------------------------------------------------*/
void Record_Best()
/* the global variable ObjectiveValue < BestObjectiveValue so do some
bookkeeping */
{
int i, cntj; /* to count bits */
BestObjectiveValue = ObjectiveValue;
Copy(BestJBits, JBits, XCnt);
cntj = 0;
for (i=0; i<XCnt; i++) cntj += *(JBits+i);
if (cntj != BaseSubSampleSize) {
printf("wrong number of bits in best %d\n",cntj);
for (i=0; i<XCnt; i++) printf("%d ",*(JBits+i));
mexErrMsgTxt("Fatal Error");;
}
if (Trace) mexPrintf("Objective Value Reduced to %14.9lf\n", ObjectiveValue);
if (Trace) {for (i=0; i<XCnt; i++) mexPrintf("%d ",*(JBits+i)); mexPrintf("\n");}
}
/*---------------------------------------------------------------------------*/
void Process_JBits(const int JCnt)
/* Given JBits, do all the calculations */
{
int debcnt=0; /* debug count */
Form_ZJ(X);
Form_A(JCnt);
InvertA(A, VectLen+1, &Determinant);
ObjectiveValue = Determinant; /* LOOK! unscaled by 1/(n-h)^(p+1) */
if (Determinant <= (double)0.0) {
printf("Singular Covariance matrix");
printf("Determinant = %E\n", Determinant);
Dump_ZJ(JCnt, "zero determinant");
printf("End of zero determinant dump\n");
ObjectiveValue = 10 * ObjectiveValue; /* try to stay out */
SingularCnt++;
/* // return; */
mexErrMsgTxt("Fatal Error");
}
if (!ObjectiveValue) {
printf("Zero objective value\n");
printf("Determinant = %E, mJ2=%E\n", Determinant, mJ2);
Dump_XJ(JCnt, "Zero objective Value");
printf("End of zero objective value dump\n");
mexErrMsgTxt("Fatal Error");
}
if (ObjectiveValue < BestObjectiveValue){
Record_Best();
}
}
/*---------------------------------------------------------------------------*/
double rho(double d)
/* compute the rho function, use conditional compilition for more forms...*/
/* assume that c is global */
/* change this to a macro for slight speed up */
{
double d2,c2,c4,d4,M2,M4; /* intermediate calcs */
double retval; /* debugging */
if (d > (M + c1)) return(M*M/2. + c1 * (5.*c1 + 16.*M)/30.);
else if (d >= M) {
d2 = d*d; d4 = d2*d2;
c2 = c1*c1; c4 = c2*c2;
M2 = M*M; M4 = M2*M2;
retval = M2/2. - M2 * (M4 - 5.*M2*c2 + 15.*c4)/(30.*c4)
+d2*(0.5 + M4/(2*c4) - M2/c2)
+d*d2*(4*M/(3*c2) - 4*M2*M/(3*c4))
+d4*(3*M2/(2*c4) - 1/(2*c2))
-4*M*d*d4/(5*c4) + d4*d2/(6*c4);
return(retval);
}
else return(d*d/2.);
}
/*---------------------------------------------------------------------------*/
double psi(double d)
/* compute the psi function, use conditional compilition for more forms...*/
/* assume that c is global */
/* change this to a macro for slight speed up */
{
double inner; /* intermediate calc */
if (d > (M + c1)) return(0.);
else if (d >= M) {
inner = 1. - ((d-M)/c1)*((d-M)/c1);
return(d * inner * inner);
} else return(d);
}
/*---------------------------------------------------------------------------*/
double w(double d)
/* compute the weight function, use conditional compilition for more forms...*/
/* assume that c1 is global */
/* change this to a macro for slight speed up */
{
double inner; /* intermediate calc */
if (d > (M + c1)) return(0.);
else if (d >= M) {
inner = 1 - ((d-M)/c1)*((d-M)/c1);
return(inner * inner);
} else return(1.);
}
/*---------------------------------------------------------------------------*/
double Compute_k()
/* find the k value to enforce the constraint (see Rocke paper) */
/* assumes the distances vector, SqResiduals, has been computed */
{
double k; /* newton converge on k (return val) */
Copy(kSqSpace, SqResiduals, XCnt);
qsort(kSqSpace, XCnt, sizeof(double), Compare_doubles);
k = sqrt(*(kSqSpace+(XCnt+VectLen+1)/2)) / M;
return(k);
}
/*---------------------------------------------------------------------------*/
void Compute_wVector_and_Sums()
/* (for s estimation iteration) find a k value and then adjust the distances*/
/* Assume that b0 is global */
/* the result is placed in the global vector dTilde */
/* note: cute math, fk = mean(rho(d/k)) and dfk = -mean(psi(d/k)*d/k^2)
/* also pre-compute the results of calls to the w function */
{
double k; /* newton converge on k*/
int i; /* to loop for sums */
k = Compute_k();
Sumw = Sumv = 0.;
for (i=0; i<XCnt; i++) {
Sumw += (*(wVector+i) = w((*(dTilde+i) = sqrt(*(SqResiduals+i))/k)));
Sumv += (*(wVector+i)) * (*(SqResiduals+i) / (k*k));
}
}
/*---------------------------------------------------------------------------*/
void M_Iterate()
/* given a C matrix, iterate to an M estimate */
/* note that this routines abuses many data structures, in particular,
XBarJ is used as the iterated mean and C is adjusted as well
*/
/* assumes that c and b0 have been set */
{
int i,j,k; /* to loop */
double MaxWDelta; /* max delta of a wieight element */
long siters=0; /* to time out on iterations */
Sumw = 0;
for (i=0; i<XCnt; i++) *(OldwVector+i) = 1.;
do {
InvertC(C, VectLen, &Determinant);
if (Determinant <= 0.0) {
printf("Singular Covariance matrix\n");
printf("Determinant = %E\n", Determinant);
printf("w vector\n");
for (j = 0; j <XCnt; j++) printf("%E ",*(wVector+j));
printf("\n");
printf("End of zero determinant dump from M_Iterate\n");
mexErrMsgTxt("Fatal Error");
}
Compute_Distance_Vector();
Compute_wVector_and_Sums();
for (j = 1; j <= VectLen; j++) {
XBarJof(j) = 0.;
for (i=0; i < XCnt; i++) XBarJof(j) += (*(wVector+i)) * Xof(i+1,j);
XBarJof(j) = XBarJof(j) / Sumw;
}
for (i=1; i<=VectLen; i++) { /* sorry about the use of k for i */
for (j=1; j<=i; j++) {
Cof(i,j) = 0;
for (k=1; k<=XCnt; k++) {
Cof(i,j) += (*(wVector+k-1))
* (Xof(k,i) - XBarJof(i))
* (Xof(k,j) - XBarJof(j));
}
Cof(i,j) = VectLen * Cof(i,j) / Sumv;
}
}
for (i=1; i<=VectLen;i++)
for (j=i+1; j<=VectLen;j++)
Cof(i,j) = Cof(j,i);
MaxWDelta = 0.;
for (i=0; i<XCnt; i++) {
if (dabs((*(wVector+i)) - (*(OldwVector+i))) > MaxWDelta)
MaxWDelta = dabs((*(wVector+i)) - (*(OldwVector+i)));
*(OldwVector+i) = *(wVector+i);
}
if (siters++ > (long)(1./(float)WTOL)) {
printf("Time out in M convergence, MaxWDelta = %lf, WTOL = %lf\n",
MaxWDelta, WTOL);
break;
}
} while (MaxWDelta > WTOL); /* wgts converge */
}
/* --------------------------------------------------------------------------*/
double xp(float p)
/* return inverse of normal (approx. Abromowitz and Stegun 941 */
{
double t;
if (p > (float)0.5) p = (float)1.-p;
t = sqrt(log(1/(p*p)));
#define a0 2.30753
#define a1 0.27061
#define b1 0.99229
#define b2 0.04481
return t - (a0 + a1*t) / (1+b1*t+b2*t*t);
#undef a0
#undef a1
#undef b1
#undef b2
}
/* --------------------------------------------------------------------------*/
double ChiSq_1(int v, float x)
/* return the x point of a v degree chi square (e.g., its inverse)*/
/* (approx. Abromowitz and Stegun 932 */
/* only above the median */
{
double inner;
inner = 1. - 2./(9.*v) + xp(x) * sqrt((double)2./(double)(9.*v));
return v * inner * inner * inner;
}
/* --------------------------------------------------------------------------*/
float ChiSq(int v, double D, double tol)
/* return the v degree chi square by searching the inverse */
{
int i=0; /* debug... get rid of this */
float bot, top, mid; /* for binary search */
double d; /* mid dist */
bot = (float)0.5;
top = (float)1. - (float)tol;
if ((D > ChiSq_1(v, top)) || (D < ChiSq_1(v, bot))) {
printf("Cannot find chiSq(%d) for %lf (tol=%lf)\n", v, D, tol);
mexErrMsgTxt("Fatal Error");
}
mid = (top+bot)/(float)2.;
while ((dabs((d = (double)ChiSq_1(v, mid))-D) > tol) && (++i<20)) {
if (d > D) top = mid; else bot = mid;
mid = (top + bot) / (float)2.;
}
return(mid);
}
/*---------------------------------------------------------------------------*/
void Set_c_and_b0()
/* set the values of c and M using rough approximations */
/* ignore the requested breakdown point */
/* no longer b0 because we are no longer using S */
{
double MPlusc; /* F^-1(1-arp) */
MPlusc = ChiSq_1(VectLen, (float)0.999);
M = sqrt(ChiSq_1(VectLen, (float)(XCnt+VectLen+1)/(float)(2*XCnt)));
c1 = sqrt(MPlusc) - M;
ActualBP = 0.; /* not used */
}
/*-------------------------------------------------------------------------*/
int Compare_Resids(const void *arg1, const void *arg2)
/* compare *arg1 and *arg2 as per qsort needs */
/* assume that doubles can never really be equal */
{
if (((struct ResidRec *)arg1)->SqMahalDist
< ((struct ResidRec *)arg2)->SqMahalDist)
return(-1); else return(1);
}
/*---------------------------------------------------------------------------*/
double Sq_Rej_Dist(int n, float a, float tol, int UseAlgo)
/* useit controls use of the iterative estimator */
/* find the distance to reject fraction a; WRECKS Xbar, C,etc; */
/* ASSUMES VectLen */
{
double sofar, oldsofar; /* // these are cutoffs (sq distances) */
int cnt, row, col;
int XCntSave;
double far *XSave;
int Blocks, Blk, Sector, CutCnt;
double *BigSqSpace;
assert(n > VectLen); assert(n <= XCnt);
if (a<=0.) return HUGE_VAL;
if (a>=1.) return 0.;
XSave = _fmalloc(VectLen*XCnt*sizeof(double)); ALLCHK(XSave)
Copy(XSave, X, XCnt * VectLen);
XCntSave = XCnt;
XCnt = n;
Blocks = (int) (10./((float)XCnt * a)); /* for small a */
if (Blocks < 40) Blocks = 40;
Sector = Blocks * XCnt;
CutCnt = (int)(a * (float)Sector);
BigSqSpace = malloc(Sector * sizeof(double)); ALLCHK(BigSqSpace)
cnt = 0;
sofar = oldsofar = 0.;
do {
for (Blk = 0; Blk < Blocks; Blk++) {
for (row = 1; row <= XCnt; row++)
for (col = 1; col <= VectLen; col++)
Xof(row, col) = XJof(row,col) = Norm((double)0.,(double)1.,&seed);
Compute_XBarJ(n);
Form_C(n);
/* overall, the next line is brutal hack... */
if (UseAlgo) Use_Algo_Rej_Code(); /* // have assumed n==XCnt... */
InvertC(C, VectLen, &Determinant);
Compute_Distance_Vector(); /* // of len XCnt */
for (row=0; row<XCnt; row++) BigSqSpace[Blk*XCnt+row] = SqResiduals[row];
}
qsort(BigSqSpace, Sector, sizeof(double), Compare_doubles);
oldsofar = sofar;
sofar += (BigSqSpace[Sector-CutCnt]+BigSqSpace[Sector-CutCnt-1])/2.;
if (++cnt > 100) break;
if (Trace) printf ("ID sector cnt=%d, sofar=%lf\n",cnt, sofar);
} while ((cnt < 2)
|| (dabs(oldsofar/(cnt-1) - sofar/cnt) / (sofar/cnt) > tol));
XCnt = XCntSave;
Copy(X, XSave, XCnt * VectLen);
_ffree(XSave); free(BigSqSpace);
return sofar/cnt;
}
/*---------------------------------------------------------------------------*/
float ID_Good(float a1, float a2)
/* on input, the distance vector must be ready to use */
/* on output, set JBits set for nominally good points */
/* return the cutoff distance */
/* do a two step using a1 and a2 as fraction to reject */
/* this routine is very fragile (as noted) */
/* all the globals make it a hack */
{
double far *SqSave; /* // to save "real" data */
int XCntSave;
double CutPt1, CutPt2; /* // cutoff for sq dist */
int i,n; /* // index and temp data size */
SqSave = _fmalloc(XCnt*sizeof(double)); ALLCHK(SqSave)
Copy(SqSave, SqResiduals, XCnt);
CutPt1 = Sq_Rej_Dist(XCnt, a1, SimTol, True); /* // wreck the globals... */
n = 0;
for (i=0; i<XCnt; i++)
if (SqSave[i] < CutPt1) {JBits[i] = 1; ++n;}
else JBits[i]=0;
if (Trace) printf("first cut uses %E and leaves %d\n",CutPt1, n);
if (n <= VectLen) {
printf("Warning: too few points kept with cutoff fraction %f\n", a1);