forked from ppdewolf/libmuargus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMuArgCtrl.cpp
6153 lines (5429 loc) · 173 KB
/
MuArgCtrl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Argus Open Source
* Software to apply Statistical Disclosure Control techniques
*
* Copyright 2014 Statistics Netherlands
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the European Union Public Licence
* (EUPL) version 1.1, as published by the European Commission.
*
* You can find the text of the EUPL v1.1 on
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
*
* This software is distributed on an "AS IS" basis without
* warranties or conditions of any kind, either express or implied.
*/
// MuArgCtrl.cpp : Implementation of CMuArgCtrl
#include "MuArgCtrl.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
std::string trimright(const std::string &t)
{
std::string str = t;
size_t found;
found = str.find_last_not_of(" \n\r\t");
if (found != str.npos)
str.erase(found+1);
else
str.clear(); // str is all whitespace
return str;
}
std::string trimleft(const std::string &t)
{
std::string str = t;
size_t found;
found = str.find_first_not_of(" \n\r\t");
if (found != str.npos)
str.erase(0,found);
else
str.clear(); // str is all whitespace
return str;
}
/////////////////////////////////////////////////////////////////////////////
// CMuArgCtrl
void CMuArgCtrl::SetProgressListener(IProgressListener* ProgressListener)
{
m_ProgressListener = ProgressListener;
}
void CMuArgCtrl::FireUpdateProgress(int Perc)
{
if (m_ProgressListener != NULL) {
m_ProgressListener->UpdateProgress(Perc);
}
}
/**
* Specifies the number of variables, reserves memory for the administration of the variables
* @param nvar number of variables
* returns false if nvar is not correct (<1) or insufficient memory
*/
bool CMuArgCtrl::SetNumberVar(long nvar)
{
// CleanUp(); // in case of a second call very usefull
m_nvar = nvar;
m_var = new CVariable[m_nvar];
if (m_var == 0) {
return false;
}
m_ntab = 0;
m_tab = 0;
if (m_nvar <= 0) {
return false;
}
else {
return true;
}
}
/**
* Specifies the properties of a variable
* @param Index 1,2,... index of variable
* @param bPos 1,2,... starting position in micro data file
* @param nPos 1,2,... number of positions in micro data file, up to 100
* @param nDec 0,1,... number of decimal places (especially important when writing safe file
* @param Missing1 Code for first missing
* @param Missing2 Code for second missing
* @param IsHHIdent Is identification variable for household
* @param IsHHVar Is a household variable
* @param IsCategorical Is a categorical variable
* @param IsNumeric Is a numeric variable
* @param IsWeight Is a weight
* @param RelatedVar Index of related variable
* @return false if one or more parameters is wrong
*/
bool CMuArgCtrl::SetVariable(long Index, long bPos, long nPos, long nDec, std::string Missing1, std::string Missing2,
bool IsHHIdent, bool IsHHVar, bool IsCategorical, bool IsNumeric, bool IsWeight, long RelatedVar)
{
long i = Index - 1;
std::string sMissing1 = Missing1;
std::string sMissing2 = Missing2;
bool bIsHHIdent,bIsHHVar,bIsCategorical,bIsNumeric,bIsWeight;
if (IsHHIdent) {
bIsHHIdent = true;
}
else {
bIsHHIdent = false;
}
if (IsHHVar) {
bIsHHVar = true;
}
else {
bIsHHVar = false;
}
if (IsCategorical) {
bIsCategorical = true;
}
else {
bIsCategorical = false;
}
if (IsNumeric) {
bIsNumeric = true;
}
else {
bIsNumeric = false;
}
if (IsWeight) {
bIsWeight = true;
}
else {
bIsWeight = false;
}
// Not the right moment, first call SetNumberVar
if (m_nvar == 0) {
return false;
}
if (Index < 1 || Index > m_nvar || bPos < 1 || nDec < 0 || nPos < 1 || nPos >= MAXCODEWIDTH) {
return false;
}
m_var[i].SetPosition(bPos,nPos,nDec);
if (IsCategorical || (IsNumeric && !IsWeight) ) {
// missings both empty?
if (Missing1[0] == 0 && Missing2[0] == 0) {
return false;
}
m_var[i].SetMissingString(sMissing1,sMissing2);
}
m_var[i].SetType(bIsCategorical,bIsNumeric,bIsWeight,bIsHHIdent,bIsHHVar);
if (IsHHIdent) {
m_HHIdentVar = i;
m_bHasHH = true;
}
if (IsHHVar) {
m_HHVars.push_back(i);
}
m_var[i].RelatedTo = RelatedVar - 1;
return true;
}
/**
* Examines of each categorical variable which codes occur. In fixed format input files,
* all records are of equal length. The only exception are empty records, which are ignored
* without warning
* @param FileName Name of file to be investigated
* @param ErrorCode
* FILENOTFOUND file can not be opened
* EMPTYFILE file is empty
* WRONGLENGTH not all record lengths are equal
* RECORDTOOSHORT a variable does not fit within specified record length
* NOVARIABLES there are no variables specified
* @param LineNumber Line number where error occurred
* @param VarIndex Index of variable where error occurred
* @return false in case of error
*/
bool CMuArgCtrl::ExploreFile(std::string FileName, long *ErrorCode, long *LineNumber, long *VarIndex)
{
long tempNumberofHH = 0;
std::string sFileName;
sFileName = FileName;
FILE *fd;
char str[MAXRECORDLENGTH];
int i, length, recnr = 0, varindex;
*ErrorCode = *LineNumber = *VarIndex = 0;
if (m_nvar == 0) {
*ErrorCode = NOVARIABLES;
return false;
}
fd = fopen(sFileName.c_str(), "r");
if (fd == 0) {
*ErrorCode = FILENOTFOUND;
return false;
}
fseek(fd, 0, SEEK_END);
m_fSize = ftell(fd);
rewind(fd);
// read first record to determine the fixed recordlength
str[0] = 0;
fgets((char *)str, MAXRECORDLENGTH, fd);
if (str[0] == 0) {
*ErrorCode = EMPTYFILE;
goto error;
}
length = strlen((char *)str) - 1;
while (length > 0 && str[length] < ' ') length--;
m_fixedlength = length + 1;
if (length == 0) {
*ErrorCode = EMPTYFILE; // first record empty
goto error;
}
// record length oke?
for (i = 0; i < m_nvar; i++) {
if (m_InFileIsFixedFormat) {
if (m_var[i].bPos + m_var[i].nPos > m_fixedlength) {
*ErrorCode = RECORDTOOSHORT;
goto error;
}
}
// initialize Min and Max Value for Numerics
if (m_var[i].IsNumeric) {
m_var[i].MaxValue = -DBL_MAX;
m_var[i].MinValue = DBL_MAX;
}
}
int res;
rewind(fd);
if ((!m_InFileIsFixedFormat)&&(m_IgnoreFirstLine)) {
res = ReadMicroRecord(fd, str);
}
while (!feof(fd) ) {
res = ReadMicroRecord(fd, str);
switch (res) {
case INFILE_ERROR:
recnr++;
*ErrorCode = WRONGLENGTH;
*LineNumber = recnr;
goto error;
case INFILE_EOF:
goto oke;
case INFILE_OKE:
recnr++;
// if ((!m_InFileIsFixedFormat)&&(m_IgnoreFirstLine)&&(recnr == 1)) {
// continue;
// }
// else {
if (recnr % FIREPROGRESS == 0) {
FireUpdateProgress((int)(ftell(fd) * 100.0 / m_fSize)); // for progressbar in container
}
if (m_bHasHH) {
if (!NumberOfHH(str, tempNumberofHH) ) {
goto error;
}
}
if (!DoMicroRecord(str, &varindex) ) {
*ErrorCode = WRONGRECORD;
*LineNumber = recnr;
*VarIndex = varindex;
goto error;
}
break;
}
}
oke:
fclose(fd);
m_nRecFile = recnr;
m_NumberofRecs = recnr;
if (m_bHasHH){
m_lNumberOfHH = tempNumberofHH +1; // for the last household
// terug zetten
CurrentHHName = "";
LastHHName = "";
}
for (i = 0; i < m_nvar; i++) {
if (m_var[i].IsCategorical) {
m_var[i].AddCode(m_var[i].Missing1.c_str(), true);
m_var[i].AddCode(m_var[i].Missing2.c_str(), true);
}
m_var[i].nCode = m_var[i].sCode.size(); // save for later use
}
FireUpdateProgress(100); // for progressbar in container
strcpy(m_fname, sFileName.c_str());
for (i = 0; i < m_nvar; i++) {
m_var[i].SortCodeLists();
}
return true;
error:
fclose(fd);
return false;
}
int CMuArgCtrl::ReadMicroRecord(FILE *fd, char *str)
{
int length = 0;
while (length == 0) {
str[0] = 0;
fgets(str, MAXRECORDLENGTH, fd);
if (str[0] == 0) return INFILE_EOF;
length = strlen(str) - 1;
while (length > 0 && str[length] < ' ') length--;
if (length == 0) continue; // skip empty records
str[length + 1] = 0;
if (m_InFileIsFixedFormat) {
if (length + 1 != m_fixedlength) {
return INFILE_ERROR;
}
}
}
return INFILE_OKE;
}
bool CMuArgCtrl::DoMicroRecord(char *str, int *varindex)
{
int i, bp, ap;
char code[MAXCODEWIDTH];
CVariable *var;
std::string tempcode;
for (i = 0; i < m_nvar; i++) {
*varindex = i + 1;
var = &(m_var[i]);
if (var->IsCategorical || var->IsNumeric) {
if(m_InFileIsFixedFormat) {
bp = var->bPos; // startposition
ap = var->nPos; // number of positions
strncpy(code, (const char *)&str[bp], ap); // get code from record
code[ap] = 0;
}
else {
ap = var->nPos; // number of positions
if (ReadVariableFreeFormat(str,i,&(tempcode))) {
strcpy(code,(const char*)tempcode.c_str());
code[ap] = 0;
}
}
}
else {
continue;
}
// Only add if not Missing code!!!!! ANCO
if (var->IsCategorical) { // only a categorical var has a codelist
if ((code != var->Missing1) && (code != var->Missing2))
{
//if (var->AddCode(i, code, false) ) { // adds if new, else does nothing
if (!(var->AddCode(code,false))){
return false;
}
}
}
if (var->IsNumeric) {
double d;
// exclude missings for calculating min/max
if (strcmp(code, var->Missing1.c_str()) != 0 && strcmp(code, var->Missing2.c_str()) != 0 ) {
if (!ConvertNumeric(code, d) ) return false; // is not numeric!
if (d > var->MaxValue) var->MaxValue = d;
if (d < var->MinValue) var->MinValue = d;
}
}
}
return true;
}
bool CMuArgCtrl::ReadVariableFreeFormat(char *Str, long VarIndex, std::string *VarCode)
{
std::vector<std::string> VarCodes;
std::string stempstr, stemp, tempvarcode;
CVariable *var;
VarCodes.resize(m_nvar);
stempstr = Str;
int inrem;
long lseppos;
long lcount= 0;
if (m_InFileSeperator != " ") {
lseppos = stempstr.find(m_InFileSeperator,0);
while (lseppos != -1) {
stemp = stempstr.substr(0,lseppos);
VarCodes.at(lcount) = stemp;
stempstr.erase(0, lseppos + 1);
lcount ++;
lseppos = stempstr.find(m_InFileSeperator, 0);
if (lseppos == stempstr.npos) lseppos = -1; // std::string.find returns npos if nothing found
}
//fill the stuff here
if ((stempstr.length() == 0) || (lcount <m_nvar - 1) || (lcount >= m_nvar)) {
// string too short or too long
return false;
}
else {
VarCodes.at(lcount) = stempstr;
}
tempvarcode = VarCodes.at(VarIndex);
//tempvarcode.TrimLeft();
tempvarcode = trimleft(tempvarcode);
//tempvarcode.TrimRight();
tempvarcode = trimright(tempvarcode);
//inrem = tempvarcode.Remove('"');
inrem = tempvarcode.size();
tempvarcode.erase(std::remove(tempvarcode.begin(),tempvarcode.end(),'"'),tempvarcode.end());
inrem = inrem - tempvarcode.size(); // Number of removed quotes
assert ((inrem == 2) || (inrem == 0)); // should be either 2 or 0
var = &(m_var[VarIndex]);
//AddSpacesBefore(tempvarcode,var->nPos); // Why add leading spaces for free format???? Removed 12/01/2021 PWOF
//Now add leading spaces
*VarCode = tempvarcode;
return true;
}
else {
return false;
}
}
bool CMuArgCtrl::ConvertNumeric(char *code, double &d)
{
char *stop;
//Setting the locale to C is not necessary for Windows, but it seems to be for Unix
std::string s = std::string(setlocale(LC_NUMERIC, "C"));
d = strtod(code, &stop);
if (*stop != 0) {
while (*(stop) == ' ') stop++;
if (*stop != 0) {
return false;
}
}
return true;
}
void CMuArgCtrl::AddSpacesBefore(std::string& str, int len)
{
int width = str.length();
if (width >= len) return; // nothing to do
{ //char tempstr[100];
std::string tempstr;
//sprintf(tempstr, "%*s", len - width, " ");
tempstr.clear();
tempstr.append(len - width,' ');
//str.Insert(0, tempstr);
str.insert(0,tempstr);
}
}
void CMuArgCtrl::AddSpacesBefore(char *str, int len)
{ int lstr = strlen(str);
if (lstr >= len) return; // nothing to do
char tempstr[MAXCODEWIDTH + 1];
strcpy(tempstr, str);
sprintf(str, "%*s%s", len - lstr, " ", tempstr);
}
/**
* Specifies the number of the table to compute.
* Clears previously specified tables, if any.
* @param nTab Number of tables
* @return false if nTab is incorrect or if insufficient memory
*/
bool CMuArgCtrl::SetNumberTab(long nTab)
{
if (m_nvar == 0 || nTab < 1) {
return false;
}
// ev. free and delete previous tables
if (m_ntab != 0) {
CleanTables();
}
m_ntab = nTab;
m_tab = new CTable[nTab + nTab]; // second part for recoded tables
if (m_tab == 0) {
return false;
}
return true;
}
/**
* Deletes all specified data and displays all the reserved memory.
* Also called by SetNumberVar
* @return always true
*/
bool CMuArgCtrl::CleanAll()
{
CleanUp();
return true;
}
void CMuArgCtrl::CleanUp()
{
for (int i = 0; i < m_nUC; i++) {
if (m_UCList[i].nDim != m_tab[m_UCList[i].TabNr].nDim) { // no base table
delete[] m_UCList[i].table.Cell;
m_UCList[i].table.Cell = 0;
m_UCList[i].table.nCell = 0;
if (m_UCList[i].table.IsBIR) {
if (m_UCList[i].table.BIRCell != 0) {
delete[] m_UCList[i].table.BIRCell;
m_UCList[i].table.BIRCell = 0;
}
}
}
}
// variables
CleanVars();
// tables
CleanTables();
if (m_HH != 0) {
delete[] m_HH;
}
m_HH = 0;
// List Unsafe Combinations
if (m_UCList != 0) {
delete [] m_UCList;
m_UCList = 0;
}
// number unsafe combinations
m_nUC = 0;
// name datafile
m_fname[0] = 0;
if (m_unsafe != 0) {
delete [] m_unsafe;
m_unsafe = 0;
}
if (m_varlist != 0) {
delete [] m_varlist;
m_varlist = 0;
}
m_HHIdentVar = -1; // make HHIdent na
m_HHVars.clear(); // remove all HHVars
if (m_nChangeFiles > 0) {
delete[] m_ChangeFiles;
m_nChangeFiles = 0;
}
m_lNumBIRs = 0;
m_lNumberOfHH = 0;
}
void CMuArgCtrl::CleanVars()
{
if (m_nvar > 0) {
/*for (i = 0; i < m_nvar; i++) {
if (m_var[i].Recode.DestCode != 0) {
free(m_var[i].Recode.DestCode);
}
}*/
delete [] m_var;
}
m_var = 0;
m_nvar = 0;
}
void CMuArgCtrl::CleanTables()
{
// also free the used Cells from the tables
if (m_ntab != 0) {
for (int i = 0; i < m_ntab + m_ntab; i++) {
if (m_tab[i].Cell != 0) {
delete[] m_tab[i].Cell;
}
if (m_tab[i].BIRCell != 0) {
delete[] m_tab[i].BIRCell;
}
}
delete [] m_tab;
}
m_tab = 0;
m_ntab = 0;
}
/**
* Specifies the attributes of a table.
* The threshold is not important in case IsBIR == true.
* In case of BIR, the threshold is specified after inspection of the histogram.
* @param TabIndex Index of the table
* @param Threshold Threshold
* @param nDim Number of dimensions (<=10)
* @param VarList The index for each dimension of the variable (1, 2, ..., nVar)
* @param IsBIR Is individual-risk-base table
* @param BIRWeightVarIndex Index of variabe containing BIR-associated weight
* @return false in case of specification errors
*/
bool CMuArgCtrl::SetTable(long TabIndex, long Threshold, long nDim, long *VarList, bool IsBIR, long BIRWeightVarIndex)
{
int i, d;
// check TableIndex
if (m_nvar == 0 || TabIndex < 1 || TabIndex > m_ntab) {
return false;
}
// check number of dimensions
if (nDim < 1 || nDim > MAXDIM) {
return false;
}
// check BIRWeightVarIndex
if (IsBIR) {
if (BIRWeightVarIndex < 1 || BIRWeightVarIndex > m_nvar || !m_var[BIRWeightVarIndex - 1].IsWeight) {
return false;
}
}
// check variable indices, variable should be categorical
for (i = 0; i < nDim; i++) {
d = VarList[i]; // index of variable, 1 .. m_nvar is oke
if (d < 1 || d > m_nvar) {
return false;
}
if (!m_var[d - 1].IsCategorical) { // property set in SetVariable(...)
return false;
}
}
// make zero based
i = TabIndex - 1;
// insert table properties
m_tab[i].Threshold = Threshold;
//////////////////////
//m_tab[i].nDim = nDim;
//for (d = 0; d < nDim; d++) {
//m_tab[i].Varnr[d] = VarList[d] - 1;
// m_tab[i].SizeDim[d] = 0; // yet unknown, after ExploreFile known
//}
///////////////////////
// check sequence vars, should be increasing with at least 1
/////////////////////
//////////////////////////////
m_tab[i].BaseTable = true;
if (IsBIR) {
m_bHasBIR = true;
m_lNumBIRs++;
m_tab[i].IsBIR = true;
}
else {
m_tab[i].IsBIR = false;
}
// m_tab[i].BIRWeightVar = BIRWeightVarIndex - 1;
m_tab[i].SetVariables(nDim,VarList,BIRWeightVarIndex);
if (!m_tab[i].CheckVarSequence() ) {
return false;
}
m_tab[i].BIRThreshold = 0; // of Threshold? AWTG 21-8-2001
return true;
}
/**
* Calculates the individual risk of records based on the frequency of key variable combination (fk)
* and the sum of the weights of (Fk). Only important if BIR-table is specified (see SetTable).
* If fk = 0, the result is 0. If fk = Fk = 1, the result is 1.
* This function is called by MakeSafeFile. The reason for this function as an export function to include
* is the fact that it is nice to have a complicated calculation process at your disposal.
* See "Strategy for the Implementation of individual risk methodology to write-ARGUS: independent
* (and hierarchical) units": Maurizio Bianchi and Alessandra Capo Lucarelli, ISTAT, MPS / D,
* Via C. Bilbao 16, 00184, Roma, Italy, Deliverable No: D1-1.2 May 30, 2001 (third draft)
* @param fk 0,1,2,... frequency of key variable combination
* @param Fk Total weights of the records with this key variable combination
* @param risk The risk of this combination, 0 <= risk <= 1
* @return false if parameters are wrong (fk < 0, Fk < 0)
*/
bool CMuArgCtrl::BaseIndividualRisk(long fk, double Fk, double *risk)
{
double p; long r; double q; double x1; double x2; long i;
*risk = 0;
if (fk == 0) goto ready; // no frequency, no risk
// parameters correct?
if (fk < 0) {
return false;
}
if (Fk <= 0) {
return false;
}
if (RISKMODEL == 1) //het oude risk model
{
// parameters are oke
if (fk >= Fk) {
if (fk == 1 && Fk == 1) {
*risk = 1;
goto ready;
}
p = 0.999;
}
else {
p = fk / Fk;
}
r = fk;
assert(p > 0 && p < 1);
switch(r) {
case 1:
*risk = (p / ( 1 - p) ) * log(1 / p);
goto ready;
case 2:
{
double h = p / (1 - p);
*risk = h - h * h * log(1 / p);
goto ready;
}
default:
if (r > 40) {
*risk = (double) p / (double)(r - 1 + p);
goto ready;
}
// r = 3, 4, ... 40
{
double c1 = 1, c2 = 1;
int j = 0;
do {
double c;
c = - (pow(r - j - 1, 2) / (j + 1) ) * ((pow(p, j - r + 2) - 1) / (pow(p, j - r + 1) - 1) ) / (r - 2 - j);
c2 *= c;
c1 += c2;
j++;
} while ( j <= r - 3 && fabs(c2) >= 1E-15);
double pqr = exp(r * (log(p) - log(1 - p) ) );
*risk = ( ( ( pow(1 / p, r - 1) - 1) / (r - 1) ) * c1 + (r & 1 ? -1 : 1) * log(p) ) * pqr;
goto ready;
}
}
}
if (RISKMODEL == 2) // Nieuw risk model van Silvia en Luisa
{
// parameters are oke; fk > 0
if (Fk <= fk) { // < kan eigenlijk niet gewichten zouden dan < 1 moeten zijn
// als Fk < fk dan eigenlijk Fk = fk beschouwen
*risk = 1.0 / fk;
goto ready;
}
else { // normale geval f < F
p = fk / Fk;
}
r = fk; q = 1 - p;
assert(p > 0 && p < 1);
switch (r) {
case 1:
*risk = - log (p) * ( p / q ) ;
goto ready;
case 2:
*risk = ( p * log(p) + q) * p / (q * q);
goto ready;
case 3:
*risk = p * ( q * ( 3 * q - 2) - 2 * p * p * log(p) ) / ( 2 * q * q * q);
goto ready;
default:
x1 = 1;
x2 = 1;
for ( i = 1 ; i <= 7 ; i++ ) {
x2 = x2 * i * q / (fk + i);
x1 = x1 + x2;
}
*risk = x1 * p / fk;
goto ready;
}
}
ready:
assert(*risk >= 0 && *risk <= 1);
return true;
}
/**
* Calculates all with SetTable specified tables from the data file and all subtables
* thereof, e.g., for table ABC also subtables AB, AC, BC, A, B and C.
* This also applies to the tables with the BIR property.
* For each (sub)table the number of table cells with value in [0, threshold] is calculated.
* All tables are stored in memory.
* @param ErrorCode
* NOVARIABLES no variables specified
* NOTABLES no tables specified
* NOTENOUGHMEMORY all tables together have too much memory, at the moment
* the limit is 50MB. This is to prevent the computer from swapping which
* unfortunately has unpleasant effects
* NOTABLEMEMORY for a single table there is not enough memory
* NODATAFILE there is no file specified to examine
* FILENOTFOUND file can not be opened
* @param TableIndex Index of table where error occurred, -1 = no error
* @return false in case of error
*/
bool CMuArgCtrl::ComputeTables(long *ErrorCode, long *TableIndex)
{
long MemSizeAll = 0, MemSizeTable;
int i,j;
FILE *fd;
char str[MAXRECORDLENGTH];
// initialize errorcodes
*ErrorCode = -1; // na
*TableIndex = -1; // na
// Not the right moment, first call SetNumberVar
if (m_nvar == 0) {
*ErrorCode = NOVARIABLES;
return false;
}
// Not the right moment, first call SetNumberTab
if (m_ntab == 0) {
*ErrorCode = NOTABLES;
return false;
}
// First do ExploreFile
if (m_fname[0] == 0) {
*ErrorCode = NODATAFILE;
return false;
}
// add SizeDim to tab
for (i = 0; i < m_ntab; i++) {
for (int d = 0; d < m_tab[i].nDim; d++) {
m_tab[i].SizeDim[d] = m_var[m_tab[i].Varnr[d]].nCode;
}
}
// Table returns a memory size
// compute memory size for each table
for (i = 0; i < m_ntab; i++) {
MemSizeTable = m_tab[i].GetMemSize();
MemSizeAll += MemSizeTable * sizeof(long);
if (m_tab[i].IsBIR) {
MemSizeAll += MemSizeTable * sizeof(double);
}
}
// check total memory to use
if (MemSizeAll > MAXMEMORYUSE) {
*ErrorCode = NOTENOUGHMEMORY;
return false;
}
for (i = 0; i < m_ntab; i++) {
if(!m_tab[i].PrepareTable()) {
*ErrorCode = NOTABLEMEMORY;
*TableIndex = i + 1;
return false;
}
}
// make space for households
if ((m_lNumberOfHH != 0) && (m_bHasBIR)) {
m_HH = new CHousehold [m_lNumberOfHH];
if (m_HH == 0) {
// Not enough memory
return false;
}
for (i= 0; i<m_lNumberOfHH; i++) {
if (!m_HH[i].PrepareHouseholdBHR(m_lNumBIRs)) {
return false;
}
}
}
fd = fopen(m_fname, "r");
if (fd == 0) {
*ErrorCode = FILENOTFOUND;
return false;
}
int recnr = 0;
//hier gaat de SAS variant wel goed AHNL 30 maart 2005
while (!feof(fd) ) {
int res = ReadMicroRecord(fd, str);
if (++recnr % FIREPROGRESS == 0) {
FireUpdateProgress((int)(ftell(fd) * 100.0 / m_fSize)); // for progressbar in container
}
switch (res) {
case INFILE_ERROR:
goto error;
break;
case INFILE_EOF:
goto oke;
break;
case INFILE_OKE:
if ((!m_InFileIsFixedFormat)&&(m_IgnoreFirstLine)&&(recnr == 1)) {
continue;
}
else {
FillTables(str);
break;
}
}
}
oke:
// Once more to fill Households
if ((m_lNumberOfHH>0) && (m_bHasBIR)) {
rewind(fd);
int res;
if ((!m_InFileIsFixedFormat)&&(m_IgnoreFirstLine)) {
res = ReadMicroRecord(fd, str);
}
bool newhousehold = false;
long numberofmem = 0;
long HHnum = 0;
while (!feof(fd) ) {
res = ReadMicroRecord(fd, str);
if (++recnr % FIREPROGRESS == 0) {
FireUpdateProgress((int)(ftell(fd) * 100.0 / m_fSize)); // for progressbar in container
}
switch (res) {
case INFILE_ERROR:
goto error;
break;
case INFILE_EOF:
m_HH[m_lNumberOfHH - 1].m_lNumberofMembers = numberofmem;
goto oke1;
break;
case INFILE_OKE:
// if ((!m_InFileIsFixedFormat)&&(m_IgnoreFirstLine)&&(recnr == 1)) {
// continue;
// }
// else {
//Here find the number of members in a household
newhousehold = IsNewHH(str);
if (newhousehold) {
m_HH[HHnum].m_lNumberofMembers= numberofmem;
numberofmem = 1;
HHnum++;
}
else {
numberofmem ++;
}
break;
// }
}
}
m_HH[HHnum].m_lNumberofMembers= numberofmem;
}
else {