Annotation of imach/src/imach.c, revision 1.343

1.343   ! brouard     1: /* $Id: imach.c,v 1.342 2022/09/11 19:54:09 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.343   ! brouard     4:   Revision 1.342  2022/09/11 19:54:09  brouard
        !             5:   Summary: 0.99r38
        !             6: 
        !             7:   * imach.c (Module): Adding timevarying products of any kinds,
        !             8:   should work before shifting cotvar from ncovcol+nqv columns in
        !             9:   order to have a correspondance between the column of cotvar and
        !            10:   the id of column.
        !            11:   (Module): Some cleaning and adding covariates in ILK.txt
        !            12: 
1.342     brouard    13:   Revision 1.341  2022/09/11 07:58:42  brouard
                     14:   Summary: Version 0.99r38
                     15: 
                     16:   After adding change in cotvar.
                     17: 
1.341     brouard    18:   Revision 1.340  2022/09/11 07:53:11  brouard
                     19:   Summary: Version imach 0.99r37
                     20: 
                     21:   * imach.c (Module): Adding timevarying products of any kinds,
                     22:   should work before shifting cotvar from ncovcol+nqv columns in
                     23:   order to have a correspondance between the column of cotvar and
                     24:   the id of column.
                     25: 
1.340     brouard    26:   Revision 1.339  2022/09/09 17:55:22  brouard
                     27:   Summary: version 0.99r37
                     28: 
                     29:   * imach.c (Module): Many improvements for fixing products of fixed
                     30:   timevarying as well as fixed * fixed, and test with quantitative
                     31:   covariate.
                     32: 
1.339     brouard    33:   Revision 1.338  2022/09/04 17:40:33  brouard
                     34:   Summary: 0.99r36
                     35: 
                     36:   * imach.c (Module): Now the easy runs i.e. without result or
                     37:   model=1+age only did not work. The defautl combination should be 1
                     38:   and not 0 because everything hasn't been tranformed yet.
                     39: 
1.338     brouard    40:   Revision 1.337  2022/09/02 14:26:02  brouard
                     41:   Summary: version 0.99r35
                     42: 
                     43:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     44:   1+age+V1+V1*age for females and 1+age for females only
                     45:   (education=1 noweight)
                     46: 
1.337     brouard    47:   Revision 1.336  2022/08/31 09:52:36  brouard
                     48:   *** empty log message ***
                     49: 
1.336     brouard    50:   Revision 1.335  2022/08/31 08:23:16  brouard
                     51:   Summary: improvements...
                     52: 
1.335     brouard    53:   Revision 1.334  2022/08/25 09:08:41  brouard
                     54:   Summary: In progress for quantitative
                     55: 
1.334     brouard    56:   Revision 1.333  2022/08/21 09:10:30  brouard
                     57:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     58:   reassigning covariates: my first idea was that people will always
                     59:   use the first covariate V1 into the model but in fact they are
                     60:   producing data with many covariates and can use an equation model
                     61:   with some of the covariate; it means that in a model V2+V3 instead
                     62:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     63:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     64:   the equation model is restricted to two variables only (V2, V3)
                     65:   and the combination for V2 should be codtabm(k,1) instead of
                     66:   (codtabm(k,2), and the code should be
                     67:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     68:   made. All of these should be simplified once a day like we did in
                     69:   hpxij() for example by using precov[nres] which is computed in
                     70:   decoderesult for each nres of each resultline. Loop should be done
                     71:   on the equation model globally by distinguishing only product with
                     72:   age (which are changing with age) and no more on type of
                     73:   covariates, single dummies, single covariates.
                     74: 
1.333     brouard    75:   Revision 1.332  2022/08/21 09:06:25  brouard
                     76:   Summary: Version 0.99r33
                     77: 
                     78:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     79:   reassigning covariates: my first idea was that people will always
                     80:   use the first covariate V1 into the model but in fact they are
                     81:   producing data with many covariates and can use an equation model
                     82:   with some of the covariate; it means that in a model V2+V3 instead
                     83:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     84:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     85:   the equation model is restricted to two variables only (V2, V3)
                     86:   and the combination for V2 should be codtabm(k,1) instead of
                     87:   (codtabm(k,2), and the code should be
                     88:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     89:   made. All of these should be simplified once a day like we did in
                     90:   hpxij() for example by using precov[nres] which is computed in
                     91:   decoderesult for each nres of each resultline. Loop should be done
                     92:   on the equation model globally by distinguishing only product with
                     93:   age (which are changing with age) and no more on type of
                     94:   covariates, single dummies, single covariates.
                     95: 
1.332     brouard    96:   Revision 1.331  2022/08/07 05:40:09  brouard
                     97:   *** empty log message ***
                     98: 
1.331     brouard    99:   Revision 1.330  2022/08/06 07:18:25  brouard
                    100:   Summary: last 0.99r31
                    101: 
                    102:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    103: 
1.330     brouard   104:   Revision 1.329  2022/08/03 17:29:54  brouard
                    105:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    106: 
1.329     brouard   107:   Revision 1.328  2022/07/27 17:40:48  brouard
                    108:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    109: 
1.328     brouard   110:   Revision 1.327  2022/07/27 14:47:35  brouard
                    111:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    112: 
1.327     brouard   113:   Revision 1.326  2022/07/26 17:33:55  brouard
                    114:   Summary: some test with nres=1
                    115: 
1.326     brouard   116:   Revision 1.325  2022/07/25 14:27:23  brouard
                    117:   Summary: r30
                    118: 
                    119:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    120:   coredumped, revealed by Feiuno, thank you.
                    121: 
1.325     brouard   122:   Revision 1.324  2022/07/23 17:44:26  brouard
                    123:   *** empty log message ***
                    124: 
1.324     brouard   125:   Revision 1.323  2022/07/22 12:30:08  brouard
                    126:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    127: 
1.323     brouard   128:   Revision 1.322  2022/07/22 12:27:48  brouard
                    129:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    130: 
1.322     brouard   131:   Revision 1.321  2022/07/22 12:04:24  brouard
                    132:   Summary: r28
                    133: 
                    134:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    135: 
1.321     brouard   136:   Revision 1.320  2022/06/02 05:10:11  brouard
                    137:   *** empty log message ***
                    138: 
1.320     brouard   139:   Revision 1.319  2022/06/02 04:45:11  brouard
                    140:   * imach.c (Module): Adding the Wald tests from the log to the main
                    141:   htm for better display of the maximum likelihood estimators.
                    142: 
1.319     brouard   143:   Revision 1.318  2022/05/24 08:10:59  brouard
                    144:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    145:   of confidencce intervals with product in the equation modelC
                    146: 
1.318     brouard   147:   Revision 1.317  2022/05/15 15:06:23  brouard
                    148:   * imach.c (Module):  Some minor improvements
                    149: 
1.317     brouard   150:   Revision 1.316  2022/05/11 15:11:31  brouard
                    151:   Summary: r27
                    152: 
1.316     brouard   153:   Revision 1.315  2022/05/11 15:06:32  brouard
                    154:   *** empty log message ***
                    155: 
1.315     brouard   156:   Revision 1.314  2022/04/13 17:43:09  brouard
                    157:   * imach.c (Module): Adding link to text data files
                    158: 
1.314     brouard   159:   Revision 1.313  2022/04/11 15:57:42  brouard
                    160:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    161: 
1.313     brouard   162:   Revision 1.312  2022/04/05 21:24:39  brouard
                    163:   *** empty log message ***
                    164: 
1.312     brouard   165:   Revision 1.311  2022/04/05 21:03:51  brouard
                    166:   Summary: Fixed quantitative covariates
                    167: 
                    168:          Fixed covariates (dummy or quantitative)
                    169:        with missing values have never been allowed but are ERRORS and
                    170:        program quits. Standard deviations of fixed covariates were
                    171:        wrongly computed. Mean and standard deviations of time varying
                    172:        covariates are still not computed.
                    173: 
1.311     brouard   174:   Revision 1.310  2022/03/17 08:45:53  brouard
                    175:   Summary: 99r25
                    176: 
                    177:   Improving detection of errors: result lines should be compatible with
                    178:   the model.
                    179: 
1.310     brouard   180:   Revision 1.309  2021/05/20 12:39:14  brouard
                    181:   Summary: Version 0.99r24
                    182: 
1.309     brouard   183:   Revision 1.308  2021/03/31 13:11:57  brouard
                    184:   Summary: Version 0.99r23
                    185: 
                    186: 
                    187:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    188: 
1.308     brouard   189:   Revision 1.307  2021/03/08 18:11:32  brouard
                    190:   Summary: 0.99r22 fixed bug on result:
                    191: 
1.307     brouard   192:   Revision 1.306  2021/02/20 15:44:02  brouard
                    193:   Summary: Version 0.99r21
                    194: 
                    195:   * imach.c (Module): Fix bug on quitting after result lines!
                    196:   (Module): Version 0.99r21
                    197: 
1.306     brouard   198:   Revision 1.305  2021/02/20 15:28:30  brouard
                    199:   * imach.c (Module): Fix bug on quitting after result lines!
                    200: 
1.305     brouard   201:   Revision 1.304  2021/02/12 11:34:20  brouard
                    202:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    203: 
1.304     brouard   204:   Revision 1.303  2021/02/11 19:50:15  brouard
                    205:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    206: 
1.303     brouard   207:   Revision 1.302  2020/02/22 21:00:05  brouard
                    208:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    209:   and life table from the data without any state)
                    210: 
1.302     brouard   211:   Revision 1.301  2019/06/04 13:51:20  brouard
                    212:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    213: 
1.301     brouard   214:   Revision 1.300  2019/05/22 19:09:45  brouard
                    215:   Summary: version 0.99r19 of May 2019
                    216: 
1.300     brouard   217:   Revision 1.299  2019/05/22 18:37:08  brouard
                    218:   Summary: Cleaned 0.99r19
                    219: 
1.299     brouard   220:   Revision 1.298  2019/05/22 18:19:56  brouard
                    221:   *** empty log message ***
                    222: 
1.298     brouard   223:   Revision 1.297  2019/05/22 17:56:10  brouard
                    224:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    225: 
1.297     brouard   226:   Revision 1.296  2019/05/20 13:03:18  brouard
                    227:   Summary: Projection syntax simplified
                    228: 
                    229: 
                    230:   We can now start projections, forward or backward, from the mean date
                    231:   of inteviews up to or down to a number of years of projection:
                    232:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    233:   or
                    234:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    235:   or
                    236:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    237:   or
                    238:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    239: 
1.296     brouard   240:   Revision 1.295  2019/05/18 09:52:50  brouard
                    241:   Summary: doxygen tex bug
                    242: 
1.295     brouard   243:   Revision 1.294  2019/05/16 14:54:33  brouard
                    244:   Summary: There was some wrong lines added
                    245: 
1.294     brouard   246:   Revision 1.293  2019/05/09 15:17:34  brouard
                    247:   *** empty log message ***
                    248: 
1.293     brouard   249:   Revision 1.292  2019/05/09 14:17:20  brouard
                    250:   Summary: Some updates
                    251: 
1.292     brouard   252:   Revision 1.291  2019/05/09 13:44:18  brouard
                    253:   Summary: Before ncovmax
                    254: 
1.291     brouard   255:   Revision 1.290  2019/05/09 13:39:37  brouard
                    256:   Summary: 0.99r18 unlimited number of individuals
                    257: 
                    258:   The number n which was limited to 20,000 cases is now unlimited, from firstobs to lastobs. If the number is too for the virtual memory, probably an error will occur.
                    259: 
1.290     brouard   260:   Revision 1.289  2018/12/13 09:16:26  brouard
                    261:   Summary: Bug for young ages (<-30) will be in r17
                    262: 
1.289     brouard   263:   Revision 1.288  2018/05/02 20:58:27  brouard
                    264:   Summary: Some bugs fixed
                    265: 
1.288     brouard   266:   Revision 1.287  2018/05/01 17:57:25  brouard
                    267:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    268: 
1.287     brouard   269:   Revision 1.286  2018/04/27 14:27:04  brouard
                    270:   Summary: some minor bugs
                    271: 
1.286     brouard   272:   Revision 1.285  2018/04/21 21:02:16  brouard
                    273:   Summary: Some bugs fixed, valgrind tested
                    274: 
1.285     brouard   275:   Revision 1.284  2018/04/20 05:22:13  brouard
                    276:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    277: 
1.284     brouard   278:   Revision 1.283  2018/04/19 14:49:16  brouard
                    279:   Summary: Some minor bugs fixed
                    280: 
1.283     brouard   281:   Revision 1.282  2018/02/27 22:50:02  brouard
                    282:   *** empty log message ***
                    283: 
1.282     brouard   284:   Revision 1.281  2018/02/27 19:25:23  brouard
                    285:   Summary: Adding second argument for quitting
                    286: 
1.281     brouard   287:   Revision 1.280  2018/02/21 07:58:13  brouard
                    288:   Summary: 0.99r15
                    289: 
                    290:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    291: 
1.280     brouard   292:   Revision 1.279  2017/07/20 13:35:01  brouard
                    293:   Summary: temporary working
                    294: 
1.279     brouard   295:   Revision 1.278  2017/07/19 14:09:02  brouard
                    296:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    297: 
1.278     brouard   298:   Revision 1.277  2017/07/17 08:53:49  brouard
                    299:   Summary: BOM files can be read now
                    300: 
1.277     brouard   301:   Revision 1.276  2017/06/30 15:48:31  brouard
                    302:   Summary: Graphs improvements
                    303: 
1.276     brouard   304:   Revision 1.275  2017/06/30 13:39:33  brouard
                    305:   Summary: Saito's color
                    306: 
1.275     brouard   307:   Revision 1.274  2017/06/29 09:47:08  brouard
                    308:   Summary: Version 0.99r14
                    309: 
1.274     brouard   310:   Revision 1.273  2017/06/27 11:06:02  brouard
                    311:   Summary: More documentation on projections
                    312: 
1.273     brouard   313:   Revision 1.272  2017/06/27 10:22:40  brouard
                    314:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    315: 
1.272     brouard   316:   Revision 1.271  2017/06/27 10:17:50  brouard
                    317:   Summary: Some bug with rint
                    318: 
1.271     brouard   319:   Revision 1.270  2017/05/24 05:45:29  brouard
                    320:   *** empty log message ***
                    321: 
1.270     brouard   322:   Revision 1.269  2017/05/23 08:39:25  brouard
                    323:   Summary: Code into subroutine, cleanings
                    324: 
1.269     brouard   325:   Revision 1.268  2017/05/18 20:09:32  brouard
                    326:   Summary: backprojection and confidence intervals of backprevalence
                    327: 
1.268     brouard   328:   Revision 1.267  2017/05/13 10:25:05  brouard
                    329:   Summary: temporary save for backprojection
                    330: 
1.267     brouard   331:   Revision 1.266  2017/05/13 07:26:12  brouard
                    332:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    333: 
1.266     brouard   334:   Revision 1.265  2017/04/26 16:22:11  brouard
                    335:   Summary: imach 0.99r13 Some bugs fixed
                    336: 
1.265     brouard   337:   Revision 1.264  2017/04/26 06:01:29  brouard
                    338:   Summary: Labels in graphs
                    339: 
1.264     brouard   340:   Revision 1.263  2017/04/24 15:23:15  brouard
                    341:   Summary: to save
                    342: 
1.263     brouard   343:   Revision 1.262  2017/04/18 16:48:12  brouard
                    344:   *** empty log message ***
                    345: 
1.262     brouard   346:   Revision 1.261  2017/04/05 10:14:09  brouard
                    347:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    348: 
1.261     brouard   349:   Revision 1.260  2017/04/04 17:46:59  brouard
                    350:   Summary: Gnuplot indexations fixed (humm)
                    351: 
1.260     brouard   352:   Revision 1.259  2017/04/04 13:01:16  brouard
                    353:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    354: 
1.259     brouard   355:   Revision 1.258  2017/04/03 10:17:47  brouard
                    356:   Summary: Version 0.99r12
                    357: 
                    358:   Some cleanings, conformed with updated documentation.
                    359: 
1.258     brouard   360:   Revision 1.257  2017/03/29 16:53:30  brouard
                    361:   Summary: Temp
                    362: 
1.257     brouard   363:   Revision 1.256  2017/03/27 05:50:23  brouard
                    364:   Summary: Temporary
                    365: 
1.256     brouard   366:   Revision 1.255  2017/03/08 16:02:28  brouard
                    367:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    368: 
1.255     brouard   369:   Revision 1.254  2017/03/08 07:13:00  brouard
                    370:   Summary: Fixing data parameter line
                    371: 
1.254     brouard   372:   Revision 1.253  2016/12/15 11:59:41  brouard
                    373:   Summary: 0.99 in progress
                    374: 
1.253     brouard   375:   Revision 1.252  2016/09/15 21:15:37  brouard
                    376:   *** empty log message ***
                    377: 
1.252     brouard   378:   Revision 1.251  2016/09/15 15:01:13  brouard
                    379:   Summary: not working
                    380: 
1.251     brouard   381:   Revision 1.250  2016/09/08 16:07:27  brouard
                    382:   Summary: continue
                    383: 
1.250     brouard   384:   Revision 1.249  2016/09/07 17:14:18  brouard
                    385:   Summary: Starting values from frequencies
                    386: 
1.249     brouard   387:   Revision 1.248  2016/09/07 14:10:18  brouard
                    388:   *** empty log message ***
                    389: 
1.248     brouard   390:   Revision 1.247  2016/09/02 11:11:21  brouard
                    391:   *** empty log message ***
                    392: 
1.247     brouard   393:   Revision 1.246  2016/09/02 08:49:22  brouard
                    394:   *** empty log message ***
                    395: 
1.246     brouard   396:   Revision 1.245  2016/09/02 07:25:01  brouard
                    397:   *** empty log message ***
                    398: 
1.245     brouard   399:   Revision 1.244  2016/09/02 07:17:34  brouard
                    400:   *** empty log message ***
                    401: 
1.244     brouard   402:   Revision 1.243  2016/09/02 06:45:35  brouard
                    403:   *** empty log message ***
                    404: 
1.243     brouard   405:   Revision 1.242  2016/08/30 15:01:20  brouard
                    406:   Summary: Fixing a lots
                    407: 
1.242     brouard   408:   Revision 1.241  2016/08/29 17:17:25  brouard
                    409:   Summary: gnuplot problem in Back projection to fix
                    410: 
1.241     brouard   411:   Revision 1.240  2016/08/29 07:53:18  brouard
                    412:   Summary: Better
                    413: 
1.240     brouard   414:   Revision 1.239  2016/08/26 15:51:03  brouard
                    415:   Summary: Improvement in Powell output in order to copy and paste
                    416: 
                    417:   Author:
                    418: 
1.239     brouard   419:   Revision 1.238  2016/08/26 14:23:35  brouard
                    420:   Summary: Starting tests of 0.99
                    421: 
1.238     brouard   422:   Revision 1.237  2016/08/26 09:20:19  brouard
                    423:   Summary: to valgrind
                    424: 
1.237     brouard   425:   Revision 1.236  2016/08/25 10:50:18  brouard
                    426:   *** empty log message ***
                    427: 
1.236     brouard   428:   Revision 1.235  2016/08/25 06:59:23  brouard
                    429:   *** empty log message ***
                    430: 
1.235     brouard   431:   Revision 1.234  2016/08/23 16:51:20  brouard
                    432:   *** empty log message ***
                    433: 
1.234     brouard   434:   Revision 1.233  2016/08/23 07:40:50  brouard
                    435:   Summary: not working
                    436: 
1.233     brouard   437:   Revision 1.232  2016/08/22 14:20:21  brouard
                    438:   Summary: not working
                    439: 
1.232     brouard   440:   Revision 1.231  2016/08/22 07:17:15  brouard
                    441:   Summary: not working
                    442: 
1.231     brouard   443:   Revision 1.230  2016/08/22 06:55:53  brouard
                    444:   Summary: Not working
                    445: 
1.230     brouard   446:   Revision 1.229  2016/07/23 09:45:53  brouard
                    447:   Summary: Completing for func too
                    448: 
1.229     brouard   449:   Revision 1.228  2016/07/22 17:45:30  brouard
                    450:   Summary: Fixing some arrays, still debugging
                    451: 
1.227     brouard   452:   Revision 1.226  2016/07/12 18:42:34  brouard
                    453:   Summary: temp
                    454: 
1.226     brouard   455:   Revision 1.225  2016/07/12 08:40:03  brouard
                    456:   Summary: saving but not running
                    457: 
1.225     brouard   458:   Revision 1.224  2016/07/01 13:16:01  brouard
                    459:   Summary: Fixes
                    460: 
1.224     brouard   461:   Revision 1.223  2016/02/19 09:23:35  brouard
                    462:   Summary: temporary
                    463: 
1.223     brouard   464:   Revision 1.222  2016/02/17 08:14:50  brouard
                    465:   Summary: Probably last 0.98 stable version 0.98r6
                    466: 
1.222     brouard   467:   Revision 1.221  2016/02/15 23:35:36  brouard
                    468:   Summary: minor bug
                    469: 
1.220     brouard   470:   Revision 1.219  2016/02/15 00:48:12  brouard
                    471:   *** empty log message ***
                    472: 
1.219     brouard   473:   Revision 1.218  2016/02/12 11:29:23  brouard
                    474:   Summary: 0.99 Back projections
                    475: 
1.218     brouard   476:   Revision 1.217  2015/12/23 17:18:31  brouard
                    477:   Summary: Experimental backcast
                    478: 
1.217     brouard   479:   Revision 1.216  2015/12/18 17:32:11  brouard
                    480:   Summary: 0.98r4 Warning and status=-2
                    481: 
                    482:   Version 0.98r4 is now:
                    483:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    484:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    485:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    486: 
1.216     brouard   487:   Revision 1.215  2015/12/16 08:52:24  brouard
                    488:   Summary: 0.98r4 working
                    489: 
1.215     brouard   490:   Revision 1.214  2015/12/16 06:57:54  brouard
                    491:   Summary: temporary not working
                    492: 
1.214     brouard   493:   Revision 1.213  2015/12/11 18:22:17  brouard
                    494:   Summary: 0.98r4
                    495: 
1.213     brouard   496:   Revision 1.212  2015/11/21 12:47:24  brouard
                    497:   Summary: minor typo
                    498: 
1.212     brouard   499:   Revision 1.211  2015/11/21 12:41:11  brouard
                    500:   Summary: 0.98r3 with some graph of projected cross-sectional
                    501: 
                    502:   Author: Nicolas Brouard
                    503: 
1.211     brouard   504:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   505:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   506:   Summary: Adding ftolpl parameter
                    507:   Author: N Brouard
                    508: 
                    509:   We had difficulties to get smoothed confidence intervals. It was due
                    510:   to the period prevalence which wasn't computed accurately. The inner
                    511:   parameter ftolpl is now an outer parameter of the .imach parameter
                    512:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    513:   computation are long.
                    514: 
1.209     brouard   515:   Revision 1.208  2015/11/17 14:31:57  brouard
                    516:   Summary: temporary
                    517: 
1.208     brouard   518:   Revision 1.207  2015/10/27 17:36:57  brouard
                    519:   *** empty log message ***
                    520: 
1.207     brouard   521:   Revision 1.206  2015/10/24 07:14:11  brouard
                    522:   *** empty log message ***
                    523: 
1.206     brouard   524:   Revision 1.205  2015/10/23 15:50:53  brouard
                    525:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    526: 
1.205     brouard   527:   Revision 1.204  2015/10/01 16:20:26  brouard
                    528:   Summary: Some new graphs of contribution to likelihood
                    529: 
1.204     brouard   530:   Revision 1.203  2015/09/30 17:45:14  brouard
                    531:   Summary: looking at better estimation of the hessian
                    532: 
                    533:   Also a better criteria for convergence to the period prevalence And
                    534:   therefore adding the number of years needed to converge. (The
                    535:   prevalence in any alive state shold sum to one
                    536: 
1.203     brouard   537:   Revision 1.202  2015/09/22 19:45:16  brouard
                    538:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    539: 
1.202     brouard   540:   Revision 1.201  2015/09/15 17:34:58  brouard
                    541:   Summary: 0.98r0
                    542: 
                    543:   - Some new graphs like suvival functions
                    544:   - Some bugs fixed like model=1+age+V2.
                    545: 
1.201     brouard   546:   Revision 1.200  2015/09/09 16:53:55  brouard
                    547:   Summary: Big bug thanks to Flavia
                    548: 
                    549:   Even model=1+age+V2. did not work anymore
                    550: 
1.200     brouard   551:   Revision 1.199  2015/09/07 14:09:23  brouard
                    552:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    553: 
1.199     brouard   554:   Revision 1.198  2015/09/03 07:14:39  brouard
                    555:   Summary: 0.98q5 Flavia
                    556: 
1.198     brouard   557:   Revision 1.197  2015/09/01 18:24:39  brouard
                    558:   *** empty log message ***
                    559: 
1.197     brouard   560:   Revision 1.196  2015/08/18 23:17:52  brouard
                    561:   Summary: 0.98q5
                    562: 
1.196     brouard   563:   Revision 1.195  2015/08/18 16:28:39  brouard
                    564:   Summary: Adding a hack for testing purpose
                    565: 
                    566:   After reading the title, ftol and model lines, if the comment line has
                    567:   a q, starting with #q, the answer at the end of the run is quit. It
                    568:   permits to run test files in batch with ctest. The former workaround was
                    569:   $ echo q | imach foo.imach
                    570: 
1.195     brouard   571:   Revision 1.194  2015/08/18 13:32:00  brouard
                    572:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    573: 
1.194     brouard   574:   Revision 1.193  2015/08/04 07:17:42  brouard
                    575:   Summary: 0.98q4
                    576: 
1.193     brouard   577:   Revision 1.192  2015/07/16 16:49:02  brouard
                    578:   Summary: Fixing some outputs
                    579: 
1.192     brouard   580:   Revision 1.191  2015/07/14 10:00:33  brouard
                    581:   Summary: Some fixes
                    582: 
1.191     brouard   583:   Revision 1.190  2015/05/05 08:51:13  brouard
                    584:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    585: 
                    586:   Fix 1+age+.
                    587: 
1.190     brouard   588:   Revision 1.189  2015/04/30 14:45:16  brouard
                    589:   Summary: 0.98q2
                    590: 
1.189     brouard   591:   Revision 1.188  2015/04/30 08:27:53  brouard
                    592:   *** empty log message ***
                    593: 
1.188     brouard   594:   Revision 1.187  2015/04/29 09:11:15  brouard
                    595:   *** empty log message ***
                    596: 
1.187     brouard   597:   Revision 1.186  2015/04/23 12:01:52  brouard
                    598:   Summary: V1*age is working now, version 0.98q1
                    599: 
                    600:   Some codes had been disabled in order to simplify and Vn*age was
                    601:   working in the optimization phase, ie, giving correct MLE parameters,
                    602:   but, as usual, outputs were not correct and program core dumped.
                    603: 
1.186     brouard   604:   Revision 1.185  2015/03/11 13:26:42  brouard
                    605:   Summary: Inclusion of compile and links command line for Intel Compiler
                    606: 
1.185     brouard   607:   Revision 1.184  2015/03/11 11:52:39  brouard
                    608:   Summary: Back from Windows 8. Intel Compiler
                    609: 
1.184     brouard   610:   Revision 1.183  2015/03/10 20:34:32  brouard
                    611:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    612: 
                    613:   We use directest instead of original Powell test; probably no
                    614:   incidence on the results, but better justifications;
                    615:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    616:   wrong results.
                    617: 
1.183     brouard   618:   Revision 1.182  2015/02/12 08:19:57  brouard
                    619:   Summary: Trying to keep directest which seems simpler and more general
                    620:   Author: Nicolas Brouard
                    621: 
1.182     brouard   622:   Revision 1.181  2015/02/11 23:22:24  brouard
                    623:   Summary: Comments on Powell added
                    624: 
                    625:   Author:
                    626: 
1.181     brouard   627:   Revision 1.180  2015/02/11 17:33:45  brouard
                    628:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    629: 
1.180     brouard   630:   Revision 1.179  2015/01/04 09:57:06  brouard
                    631:   Summary: back to OS/X
                    632: 
1.179     brouard   633:   Revision 1.178  2015/01/04 09:35:48  brouard
                    634:   *** empty log message ***
                    635: 
1.178     brouard   636:   Revision 1.177  2015/01/03 18:40:56  brouard
                    637:   Summary: Still testing ilc32 on OSX
                    638: 
1.177     brouard   639:   Revision 1.176  2015/01/03 16:45:04  brouard
                    640:   *** empty log message ***
                    641: 
1.176     brouard   642:   Revision 1.175  2015/01/03 16:33:42  brouard
                    643:   *** empty log message ***
                    644: 
1.175     brouard   645:   Revision 1.174  2015/01/03 16:15:49  brouard
                    646:   Summary: Still in cross-compilation
                    647: 
1.174     brouard   648:   Revision 1.173  2015/01/03 12:06:26  brouard
                    649:   Summary: trying to detect cross-compilation
                    650: 
1.173     brouard   651:   Revision 1.172  2014/12/27 12:07:47  brouard
                    652:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    653: 
1.172     brouard   654:   Revision 1.171  2014/12/23 13:26:59  brouard
                    655:   Summary: Back from Visual C
                    656: 
                    657:   Still problem with utsname.h on Windows
                    658: 
1.171     brouard   659:   Revision 1.170  2014/12/23 11:17:12  brouard
                    660:   Summary: Cleaning some \%% back to %%
                    661: 
                    662:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    663: 
1.170     brouard   664:   Revision 1.169  2014/12/22 23:08:31  brouard
                    665:   Summary: 0.98p
                    666: 
                    667:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    668: 
1.169     brouard   669:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   670:   Summary: update
1.169     brouard   671: 
1.168     brouard   672:   Revision 1.167  2014/12/22 13:50:56  brouard
                    673:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    674: 
                    675:   Testing on Linux 64
                    676: 
1.167     brouard   677:   Revision 1.166  2014/12/22 11:40:47  brouard
                    678:   *** empty log message ***
                    679: 
1.166     brouard   680:   Revision 1.165  2014/12/16 11:20:36  brouard
                    681:   Summary: After compiling on Visual C
                    682: 
                    683:   * imach.c (Module): Merging 1.61 to 1.162
                    684: 
1.165     brouard   685:   Revision 1.164  2014/12/16 10:52:11  brouard
                    686:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    687: 
                    688:   * imach.c (Module): Merging 1.61 to 1.162
                    689: 
1.164     brouard   690:   Revision 1.163  2014/12/16 10:30:11  brouard
                    691:   * imach.c (Module): Merging 1.61 to 1.162
                    692: 
1.163     brouard   693:   Revision 1.162  2014/09/25 11:43:39  brouard
                    694:   Summary: temporary backup 0.99!
                    695: 
1.162     brouard   696:   Revision 1.1  2014/09/16 11:06:58  brouard
                    697:   Summary: With some code (wrong) for nlopt
                    698: 
                    699:   Author:
                    700: 
                    701:   Revision 1.161  2014/09/15 20:41:41  brouard
                    702:   Summary: Problem with macro SQR on Intel compiler
                    703: 
1.161     brouard   704:   Revision 1.160  2014/09/02 09:24:05  brouard
                    705:   *** empty log message ***
                    706: 
1.160     brouard   707:   Revision 1.159  2014/09/01 10:34:10  brouard
                    708:   Summary: WIN32
                    709:   Author: Brouard
                    710: 
1.159     brouard   711:   Revision 1.158  2014/08/27 17:11:51  brouard
                    712:   *** empty log message ***
                    713: 
1.158     brouard   714:   Revision 1.157  2014/08/27 16:26:55  brouard
                    715:   Summary: Preparing windows Visual studio version
                    716:   Author: Brouard
                    717: 
                    718:   In order to compile on Visual studio, time.h is now correct and time_t
                    719:   and tm struct should be used. difftime should be used but sometimes I
                    720:   just make the differences in raw time format (time(&now).
                    721:   Trying to suppress #ifdef LINUX
                    722:   Add xdg-open for __linux in order to open default browser.
                    723: 
1.157     brouard   724:   Revision 1.156  2014/08/25 20:10:10  brouard
                    725:   *** empty log message ***
                    726: 
1.156     brouard   727:   Revision 1.155  2014/08/25 18:32:34  brouard
                    728:   Summary: New compile, minor changes
                    729:   Author: Brouard
                    730: 
1.155     brouard   731:   Revision 1.154  2014/06/20 17:32:08  brouard
                    732:   Summary: Outputs now all graphs of convergence to period prevalence
                    733: 
1.154     brouard   734:   Revision 1.153  2014/06/20 16:45:46  brouard
                    735:   Summary: If 3 live state, convergence to period prevalence on same graph
                    736:   Author: Brouard
                    737: 
1.153     brouard   738:   Revision 1.152  2014/06/18 17:54:09  brouard
                    739:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    740: 
1.152     brouard   741:   Revision 1.151  2014/06/18 16:43:30  brouard
                    742:   *** empty log message ***
                    743: 
1.151     brouard   744:   Revision 1.150  2014/06/18 16:42:35  brouard
                    745:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    746:   Author: brouard
                    747: 
1.150     brouard   748:   Revision 1.149  2014/06/18 15:51:14  brouard
                    749:   Summary: Some fixes in parameter files errors
                    750:   Author: Nicolas Brouard
                    751: 
1.149     brouard   752:   Revision 1.148  2014/06/17 17:38:48  brouard
                    753:   Summary: Nothing new
                    754:   Author: Brouard
                    755: 
                    756:   Just a new packaging for OS/X version 0.98nS
                    757: 
1.148     brouard   758:   Revision 1.147  2014/06/16 10:33:11  brouard
                    759:   *** empty log message ***
                    760: 
1.147     brouard   761:   Revision 1.146  2014/06/16 10:20:28  brouard
                    762:   Summary: Merge
                    763:   Author: Brouard
                    764: 
                    765:   Merge, before building revised version.
                    766: 
1.146     brouard   767:   Revision 1.145  2014/06/10 21:23:15  brouard
                    768:   Summary: Debugging with valgrind
                    769:   Author: Nicolas Brouard
                    770: 
                    771:   Lot of changes in order to output the results with some covariates
                    772:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    773:   improve the code.
                    774:   No more memory valgrind error but a lot has to be done in order to
                    775:   continue the work of splitting the code into subroutines.
                    776:   Also, decodemodel has been improved. Tricode is still not
                    777:   optimal. nbcode should be improved. Documentation has been added in
                    778:   the source code.
                    779: 
1.144     brouard   780:   Revision 1.143  2014/01/26 09:45:38  brouard
                    781:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    782: 
                    783:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    784:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    785: 
1.143     brouard   786:   Revision 1.142  2014/01/26 03:57:36  brouard
                    787:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    788: 
                    789:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    790: 
1.142     brouard   791:   Revision 1.141  2014/01/26 02:42:01  brouard
                    792:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    793: 
1.141     brouard   794:   Revision 1.140  2011/09/02 10:37:54  brouard
                    795:   Summary: times.h is ok with mingw32 now.
                    796: 
1.140     brouard   797:   Revision 1.139  2010/06/14 07:50:17  brouard
                    798:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    799:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    800: 
1.139     brouard   801:   Revision 1.138  2010/04/30 18:19:40  brouard
                    802:   *** empty log message ***
                    803: 
1.138     brouard   804:   Revision 1.137  2010/04/29 18:11:38  brouard
                    805:   (Module): Checking covariates for more complex models
                    806:   than V1+V2. A lot of change to be done. Unstable.
                    807: 
1.137     brouard   808:   Revision 1.136  2010/04/26 20:30:53  brouard
                    809:   (Module): merging some libgsl code. Fixing computation
                    810:   of likelione (using inter/intrapolation if mle = 0) in order to
                    811:   get same likelihood as if mle=1.
                    812:   Some cleaning of code and comments added.
                    813: 
1.136     brouard   814:   Revision 1.135  2009/10/29 15:33:14  brouard
                    815:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    816: 
1.135     brouard   817:   Revision 1.134  2009/10/29 13:18:53  brouard
                    818:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    819: 
1.134     brouard   820:   Revision 1.133  2009/07/06 10:21:25  brouard
                    821:   just nforces
                    822: 
1.133     brouard   823:   Revision 1.132  2009/07/06 08:22:05  brouard
                    824:   Many tings
                    825: 
1.132     brouard   826:   Revision 1.131  2009/06/20 16:22:47  brouard
                    827:   Some dimensions resccaled
                    828: 
1.131     brouard   829:   Revision 1.130  2009/05/26 06:44:34  brouard
                    830:   (Module): Max Covariate is now set to 20 instead of 8. A
                    831:   lot of cleaning with variables initialized to 0. Trying to make
                    832:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    833: 
1.130     brouard   834:   Revision 1.129  2007/08/31 13:49:27  lievre
                    835:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    836: 
1.129     lievre    837:   Revision 1.128  2006/06/30 13:02:05  brouard
                    838:   (Module): Clarifications on computing e.j
                    839: 
1.128     brouard   840:   Revision 1.127  2006/04/28 18:11:50  brouard
                    841:   (Module): Yes the sum of survivors was wrong since
                    842:   imach-114 because nhstepm was no more computed in the age
                    843:   loop. Now we define nhstepma in the age loop.
                    844:   (Module): In order to speed up (in case of numerous covariates) we
                    845:   compute health expectancies (without variances) in a first step
                    846:   and then all the health expectancies with variances or standard
                    847:   deviation (needs data from the Hessian matrices) which slows the
                    848:   computation.
                    849:   In the future we should be able to stop the program is only health
                    850:   expectancies and graph are needed without standard deviations.
                    851: 
1.127     brouard   852:   Revision 1.126  2006/04/28 17:23:28  brouard
                    853:   (Module): Yes the sum of survivors was wrong since
                    854:   imach-114 because nhstepm was no more computed in the age
                    855:   loop. Now we define nhstepma in the age loop.
                    856:   Version 0.98h
                    857: 
1.126     brouard   858:   Revision 1.125  2006/04/04 15:20:31  lievre
                    859:   Errors in calculation of health expectancies. Age was not initialized.
                    860:   Forecasting file added.
                    861: 
                    862:   Revision 1.124  2006/03/22 17:13:53  lievre
                    863:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    864:   The log-likelihood is printed in the log file
                    865: 
                    866:   Revision 1.123  2006/03/20 10:52:43  brouard
                    867:   * imach.c (Module): <title> changed, corresponds to .htm file
                    868:   name. <head> headers where missing.
                    869: 
                    870:   * imach.c (Module): Weights can have a decimal point as for
                    871:   English (a comma might work with a correct LC_NUMERIC environment,
                    872:   otherwise the weight is truncated).
                    873:   Modification of warning when the covariates values are not 0 or
                    874:   1.
                    875:   Version 0.98g
                    876: 
                    877:   Revision 1.122  2006/03/20 09:45:41  brouard
                    878:   (Module): Weights can have a decimal point as for
                    879:   English (a comma might work with a correct LC_NUMERIC environment,
                    880:   otherwise the weight is truncated).
                    881:   Modification of warning when the covariates values are not 0 or
                    882:   1.
                    883:   Version 0.98g
                    884: 
                    885:   Revision 1.121  2006/03/16 17:45:01  lievre
                    886:   * imach.c (Module): Comments concerning covariates added
                    887: 
                    888:   * imach.c (Module): refinements in the computation of lli if
                    889:   status=-2 in order to have more reliable computation if stepm is
                    890:   not 1 month. Version 0.98f
                    891: 
                    892:   Revision 1.120  2006/03/16 15:10:38  lievre
                    893:   (Module): refinements in the computation of lli if
                    894:   status=-2 in order to have more reliable computation if stepm is
                    895:   not 1 month. Version 0.98f
                    896: 
                    897:   Revision 1.119  2006/03/15 17:42:26  brouard
                    898:   (Module): Bug if status = -2, the loglikelihood was
                    899:   computed as likelihood omitting the logarithm. Version O.98e
                    900: 
                    901:   Revision 1.118  2006/03/14 18:20:07  brouard
                    902:   (Module): varevsij Comments added explaining the second
                    903:   table of variances if popbased=1 .
                    904:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    905:   (Module): Function pstamp added
                    906:   (Module): Version 0.98d
                    907: 
                    908:   Revision 1.117  2006/03/14 17:16:22  brouard
                    909:   (Module): varevsij Comments added explaining the second
                    910:   table of variances if popbased=1 .
                    911:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    912:   (Module): Function pstamp added
                    913:   (Module): Version 0.98d
                    914: 
                    915:   Revision 1.116  2006/03/06 10:29:27  brouard
                    916:   (Module): Variance-covariance wrong links and
                    917:   varian-covariance of ej. is needed (Saito).
                    918: 
                    919:   Revision 1.115  2006/02/27 12:17:45  brouard
                    920:   (Module): One freematrix added in mlikeli! 0.98c
                    921: 
                    922:   Revision 1.114  2006/02/26 12:57:58  brouard
                    923:   (Module): Some improvements in processing parameter
                    924:   filename with strsep.
                    925: 
                    926:   Revision 1.113  2006/02/24 14:20:24  brouard
                    927:   (Module): Memory leaks checks with valgrind and:
                    928:   datafile was not closed, some imatrix were not freed and on matrix
                    929:   allocation too.
                    930: 
                    931:   Revision 1.112  2006/01/30 09:55:26  brouard
                    932:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    933: 
                    934:   Revision 1.111  2006/01/25 20:38:18  brouard
                    935:   (Module): Lots of cleaning and bugs added (Gompertz)
                    936:   (Module): Comments can be added in data file. Missing date values
                    937:   can be a simple dot '.'.
                    938: 
                    939:   Revision 1.110  2006/01/25 00:51:50  brouard
                    940:   (Module): Lots of cleaning and bugs added (Gompertz)
                    941: 
                    942:   Revision 1.109  2006/01/24 19:37:15  brouard
                    943:   (Module): Comments (lines starting with a #) are allowed in data.
                    944: 
                    945:   Revision 1.108  2006/01/19 18:05:42  lievre
                    946:   Gnuplot problem appeared...
                    947:   To be fixed
                    948: 
                    949:   Revision 1.107  2006/01/19 16:20:37  brouard
                    950:   Test existence of gnuplot in imach path
                    951: 
                    952:   Revision 1.106  2006/01/19 13:24:36  brouard
                    953:   Some cleaning and links added in html output
                    954: 
                    955:   Revision 1.105  2006/01/05 20:23:19  lievre
                    956:   *** empty log message ***
                    957: 
                    958:   Revision 1.104  2005/09/30 16:11:43  lievre
                    959:   (Module): sump fixed, loop imx fixed, and simplifications.
                    960:   (Module): If the status is missing at the last wave but we know
                    961:   that the person is alive, then we can code his/her status as -2
                    962:   (instead of missing=-1 in earlier versions) and his/her
                    963:   contributions to the likelihood is 1 - Prob of dying from last
                    964:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    965:   the healthy state at last known wave). Version is 0.98
                    966: 
                    967:   Revision 1.103  2005/09/30 15:54:49  lievre
                    968:   (Module): sump fixed, loop imx fixed, and simplifications.
                    969: 
                    970:   Revision 1.102  2004/09/15 17:31:30  brouard
                    971:   Add the possibility to read data file including tab characters.
                    972: 
                    973:   Revision 1.101  2004/09/15 10:38:38  brouard
                    974:   Fix on curr_time
                    975: 
                    976:   Revision 1.100  2004/07/12 18:29:06  brouard
                    977:   Add version for Mac OS X. Just define UNIX in Makefile
                    978: 
                    979:   Revision 1.99  2004/06/05 08:57:40  brouard
                    980:   *** empty log message ***
                    981: 
                    982:   Revision 1.98  2004/05/16 15:05:56  brouard
                    983:   New version 0.97 . First attempt to estimate force of mortality
                    984:   directly from the data i.e. without the need of knowing the health
                    985:   state at each age, but using a Gompertz model: log u =a + b*age .
                    986:   This is the basic analysis of mortality and should be done before any
                    987:   other analysis, in order to test if the mortality estimated from the
                    988:   cross-longitudinal survey is different from the mortality estimated
                    989:   from other sources like vital statistic data.
                    990: 
                    991:   The same imach parameter file can be used but the option for mle should be -3.
                    992: 
1.324     brouard   993:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   994:   former routines in order to include the new code within the former code.
                    995: 
                    996:   The output is very simple: only an estimate of the intercept and of
                    997:   the slope with 95% confident intervals.
                    998: 
                    999:   Current limitations:
                   1000:   A) Even if you enter covariates, i.e. with the
                   1001:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1002:   B) There is no computation of Life Expectancy nor Life Table.
                   1003: 
                   1004:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1005:   Version 0.96d. Population forecasting command line is (temporarily)
                   1006:   suppressed.
                   1007: 
                   1008:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1009:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1010:   rewritten within the same printf. Workaround: many printfs.
                   1011: 
                   1012:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1013:   * imach.c (Repository):
                   1014:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1015:   matrix (cov(a12,c31) instead of numbers.
                   1016: 
                   1017:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1018:   Just cleaning
                   1019: 
                   1020:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1021:   (Module): On windows (cygwin) function asctime_r doesn't
                   1022:   exist so I changed back to asctime which exists.
                   1023:   (Module): Version 0.96b
                   1024: 
                   1025:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1026:   (Module): On windows (cygwin) function asctime_r doesn't
                   1027:   exist so I changed back to asctime which exists.
                   1028: 
                   1029:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1030:   * imach.c (Repository): Duplicated warning errors corrected.
                   1031:   (Repository): Elapsed time after each iteration is now output. It
                   1032:   helps to forecast when convergence will be reached. Elapsed time
                   1033:   is stamped in powell.  We created a new html file for the graphs
                   1034:   concerning matrix of covariance. It has extension -cov.htm.
                   1035: 
                   1036:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1037:   (Module): Some bugs corrected for windows. Also, when
                   1038:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1039:   of the covariance matrix to be input.
                   1040: 
                   1041:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1042:   (Module): Some bugs corrected for windows. Also, when
                   1043:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1044:   of the covariance matrix to be input.
                   1045: 
                   1046:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1047:   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.
                   1048: 
                   1049:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1050:   Version 0.96
                   1051: 
                   1052:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1053:   (Module): Change position of html and gnuplot routines and added
                   1054:   routine fileappend.
                   1055: 
                   1056:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1057:   * imach.c (Repository): Check when date of death was earlier that
                   1058:   current date of interview. It may happen when the death was just
                   1059:   prior to the death. In this case, dh was negative and likelihood
                   1060:   was wrong (infinity). We still send an "Error" but patch by
                   1061:   assuming that the date of death was just one stepm after the
                   1062:   interview.
                   1063:   (Repository): Because some people have very long ID (first column)
                   1064:   we changed int to long in num[] and we added a new lvector for
                   1065:   memory allocation. But we also truncated to 8 characters (left
                   1066:   truncation)
                   1067:   (Repository): No more line truncation errors.
                   1068: 
                   1069:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1070:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1071:   place. It differs from routine "prevalence" which may be called
                   1072:   many times. Probs is memory consuming and must be used with
                   1073:   parcimony.
                   1074:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1075: 
                   1076:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1077:   *** empty log message ***
                   1078: 
                   1079:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1080:   Add log in  imach.c and  fullversion number is now printed.
                   1081: 
                   1082: */
                   1083: /*
                   1084:    Interpolated Markov Chain
                   1085: 
                   1086:   Short summary of the programme:
                   1087:   
1.227     brouard  1088:   This program computes Healthy Life Expectancies or State-specific
                   1089:   (if states aren't health statuses) Expectancies from
                   1090:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1091: 
                   1092:   -1- a first survey ("cross") where individuals from different ages
                   1093:   are interviewed on their health status or degree of disability (in
                   1094:   the case of a health survey which is our main interest)
                   1095: 
                   1096:   -2- at least a second wave of interviews ("longitudinal") which
                   1097:   measure each change (if any) in individual health status.  Health
                   1098:   expectancies are computed from the time spent in each health state
                   1099:   according to a model. More health states you consider, more time is
                   1100:   necessary to reach the Maximum Likelihood of the parameters involved
                   1101:   in the model.  The simplest model is the multinomial logistic model
                   1102:   where pij is the probability to be observed in state j at the second
                   1103:   wave conditional to be observed in state i at the first
                   1104:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1105:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1106:   have a more complex model than "constant and age", you should modify
                   1107:   the program where the markup *Covariates have to be included here
                   1108:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1109:   convergence.
                   1110: 
                   1111:   The advantage of this computer programme, compared to a simple
                   1112:   multinomial logistic model, is clear when the delay between waves is not
                   1113:   identical for each individual. Also, if a individual missed an
                   1114:   intermediate interview, the information is lost, but taken into
                   1115:   account using an interpolation or extrapolation.  
                   1116: 
                   1117:   hPijx is the probability to be observed in state i at age x+h
                   1118:   conditional to the observed state i at age x. The delay 'h' can be
                   1119:   split into an exact number (nh*stepm) of unobserved intermediate
                   1120:   states. This elementary transition (by month, quarter,
                   1121:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1122:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1123:   and the contribution of each individual to the likelihood is simply
                   1124:   hPijx.
                   1125: 
                   1126:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1127:   of the life expectancies. It also computes the period (stable) prevalence.
                   1128: 
                   1129: Back prevalence and projections:
1.227     brouard  1130: 
                   1131:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1132:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1133:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1134:    mobilavproj)
                   1135: 
                   1136:     Computes the back prevalence limit for any combination of
                   1137:     covariate values k at any age between ageminpar and agemaxpar and
                   1138:     returns it in **bprlim. In the loops,
                   1139: 
                   1140:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1141:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1142: 
                   1143:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1144:    Computes for any combination of covariates k and any age between bage and fage 
                   1145:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1146:                        oldm=oldms;savm=savms;
1.227     brouard  1147: 
1.267     brouard  1148:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1149:      Computes the transition matrix starting at age 'age' over
                   1150:      'nhstepm*hstepm*stepm' months (i.e. until
                   1151:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1152:      nhstepm*hstepm matrices. 
                   1153: 
                   1154:      Returns p3mat[i][j][h] after calling
                   1155:      p3mat[i][j][h]=matprod2(newm,
                   1156:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1157:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1158:      oldm);
1.226     brouard  1159: 
                   1160: Important routines
                   1161: 
                   1162: - func (or funcone), computes logit (pij) distinguishing
                   1163:   o fixed variables (single or product dummies or quantitative);
                   1164:   o varying variables by:
                   1165:    (1) wave (single, product dummies, quantitative), 
                   1166:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1167:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1168:        % varying dummy (not done) or quantitative (not done);
                   1169: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1170:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1171: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1172:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1173:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1174: 
1.226     brouard  1175: 
                   1176:   
1.324     brouard  1177:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1178:            Institut national d'études démographiques, Paris.
1.126     brouard  1179:   This software have been partly granted by Euro-REVES, a concerted action
                   1180:   from the European Union.
                   1181:   It is copyrighted identically to a GNU software product, ie programme and
                   1182:   software can be distributed freely for non commercial use. Latest version
                   1183:   can be accessed at http://euroreves.ined.fr/imach .
                   1184: 
                   1185:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1186:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1187:   
                   1188:   **********************************************************************/
                   1189: /*
                   1190:   main
                   1191:   read parameterfile
                   1192:   read datafile
                   1193:   concatwav
                   1194:   freqsummary
                   1195:   if (mle >= 1)
                   1196:     mlikeli
                   1197:   print results files
                   1198:   if mle==1 
                   1199:      computes hessian
                   1200:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1201:       begin-prev-date,...
                   1202:   open gnuplot file
                   1203:   open html file
1.145     brouard  1204:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1205:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1206:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1207:     freexexit2 possible for memory heap.
                   1208: 
                   1209:   h Pij x                         | pij_nom  ficrestpij
                   1210:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1211:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1212:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1213: 
                   1214:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1215:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1216:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1217:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1218:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1219: 
1.126     brouard  1220:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1221:   health expectancies
                   1222:   Variance-covariance of DFLE
                   1223:   prevalence()
                   1224:    movingaverage()
                   1225:   varevsij() 
                   1226:   if popbased==1 varevsij(,popbased)
                   1227:   total life expectancies
                   1228:   Variance of period (stable) prevalence
                   1229:  end
                   1230: */
                   1231: 
1.187     brouard  1232: /* #define DEBUG */
                   1233: /* #define DEBUGBRENT */
1.203     brouard  1234: /* #define DEBUGLINMIN */
                   1235: /* #define DEBUGHESS */
                   1236: #define DEBUGHESSIJ
1.224     brouard  1237: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1238: #define POWELL /* Instead of NLOPT */
1.224     brouard  1239: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1240: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1241: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1242: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1243: 
                   1244: #include <math.h>
                   1245: #include <stdio.h>
                   1246: #include <stdlib.h>
                   1247: #include <string.h>
1.226     brouard  1248: #include <ctype.h>
1.159     brouard  1249: 
                   1250: #ifdef _WIN32
                   1251: #include <io.h>
1.172     brouard  1252: #include <windows.h>
                   1253: #include <tchar.h>
1.159     brouard  1254: #else
1.126     brouard  1255: #include <unistd.h>
1.159     brouard  1256: #endif
1.126     brouard  1257: 
                   1258: #include <limits.h>
                   1259: #include <sys/types.h>
1.171     brouard  1260: 
                   1261: #if defined(__GNUC__)
                   1262: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1263: #endif
                   1264: 
1.126     brouard  1265: #include <sys/stat.h>
                   1266: #include <errno.h>
1.159     brouard  1267: /* extern int errno; */
1.126     brouard  1268: 
1.157     brouard  1269: /* #ifdef LINUX */
                   1270: /* #include <time.h> */
                   1271: /* #include "timeval.h" */
                   1272: /* #else */
                   1273: /* #include <sys/time.h> */
                   1274: /* #endif */
                   1275: 
1.126     brouard  1276: #include <time.h>
                   1277: 
1.136     brouard  1278: #ifdef GSL
                   1279: #include <gsl/gsl_errno.h>
                   1280: #include <gsl/gsl_multimin.h>
                   1281: #endif
                   1282: 
1.167     brouard  1283: 
1.162     brouard  1284: #ifdef NLOPT
                   1285: #include <nlopt.h>
                   1286: typedef struct {
                   1287:   double (* function)(double [] );
                   1288: } myfunc_data ;
                   1289: #endif
                   1290: 
1.126     brouard  1291: /* #include <libintl.h> */
                   1292: /* #define _(String) gettext (String) */
                   1293: 
1.251     brouard  1294: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1295: 
                   1296: #define GNUPLOTPROGRAM "gnuplot"
1.343   ! brouard  1297: #define GNUPLOTVERSION 5.1
        !          1298: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1299: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1300: #define FILENAMELENGTH 256
1.126     brouard  1301: 
                   1302: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1303: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1304: 
1.144     brouard  1305: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1306: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1307: 
                   1308: #define NINTERVMAX 8
1.144     brouard  1309: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1310: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1311: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1312: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1313: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1314: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1315: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1316: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1317: /* #define AGESUP 130 */
1.288     brouard  1318: /* #define AGESUP 150 */
                   1319: #define AGESUP 200
1.268     brouard  1320: #define AGEINF 0
1.218     brouard  1321: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1322: #define AGEBASE 40
1.194     brouard  1323: #define AGEOVERFLOW 1.e20
1.164     brouard  1324: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1325: #ifdef _WIN32
                   1326: #define DIRSEPARATOR '\\'
                   1327: #define CHARSEPARATOR "\\"
                   1328: #define ODIRSEPARATOR '/'
                   1329: #else
1.126     brouard  1330: #define DIRSEPARATOR '/'
                   1331: #define CHARSEPARATOR "/"
                   1332: #define ODIRSEPARATOR '\\'
                   1333: #endif
                   1334: 
1.343   ! brouard  1335: /* $Id: imach.c,v 1.342 2022/09/11 19:54:09 brouard Exp $ */
1.126     brouard  1336: /* $State: Exp $ */
1.196     brouard  1337: #include "version.h"
                   1338: char version[]=__IMACH_VERSION__;
1.337     brouard  1339: char copyright[]="September 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.343   ! brouard  1340: char fullversion[]="$Revision: 1.342 $ $Date: 2022/09/11 19:54:09 $"; 
1.126     brouard  1341: char strstart[80];
                   1342: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1343: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1344: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1345: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1346: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1347: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1348: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
1.330     brouard  1349: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.335     brouard  1350: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1351: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1352: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1353: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1354: int cptcoveff=0; /* Total number of single dummy covariates (fixed or time varying) to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1355: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1356: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1357: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1358: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1359: int nsd=0; /**< Total number of single dummy variables (output) */
                   1360: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1361: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1362: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1363: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1364: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1365: int cptcov=0; /* Working variable */
1.334     brouard  1366: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1367: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1368: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1369: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1370: int nlstate=2; /* Number of live states */
                   1371: int ndeath=1; /* Number of dead states */
1.130     brouard  1372: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1373: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1374: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1375: int popbased=0;
                   1376: 
                   1377: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1378: int maxwav=0; /* Maxim number of waves */
                   1379: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1380: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1381: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1382:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1383: int mle=1, weightopt=0;
1.126     brouard  1384: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1385: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1386: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1387:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1388: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1389: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1390: 
1.130     brouard  1391: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1392: double **matprod2(); /* test */
1.126     brouard  1393: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1394: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1395: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1396: 
1.136     brouard  1397: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1398: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1399: FILE *ficlog, *ficrespow;
1.130     brouard  1400: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1401: double fretone; /* Only one call to likelihood */
1.130     brouard  1402: long ipmx=0; /* Number of contributions */
1.126     brouard  1403: double sw; /* Sum of weights */
                   1404: char filerespow[FILENAMELENGTH];
                   1405: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1406: FILE *ficresilk;
                   1407: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1408: FILE *ficresprobmorprev;
                   1409: FILE *fichtm, *fichtmcov; /* Html File */
                   1410: FILE *ficreseij;
                   1411: char filerese[FILENAMELENGTH];
                   1412: FILE *ficresstdeij;
                   1413: char fileresstde[FILENAMELENGTH];
                   1414: FILE *ficrescveij;
                   1415: char filerescve[FILENAMELENGTH];
                   1416: FILE  *ficresvij;
                   1417: char fileresv[FILENAMELENGTH];
1.269     brouard  1418: 
1.126     brouard  1419: char title[MAXLINE];
1.234     brouard  1420: char model[MAXLINE]; /**< The model line */
1.217     brouard  1421: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1422: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1423: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1424: char command[FILENAMELENGTH];
                   1425: int  outcmd=0;
                   1426: 
1.217     brouard  1427: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1428: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1429: char filelog[FILENAMELENGTH]; /* Log file */
                   1430: char filerest[FILENAMELENGTH];
                   1431: char fileregp[FILENAMELENGTH];
                   1432: char popfile[FILENAMELENGTH];
                   1433: 
                   1434: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1435: 
1.157     brouard  1436: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1437: /* struct timezone tzp; */
                   1438: /* extern int gettimeofday(); */
                   1439: struct tm tml, *gmtime(), *localtime();
                   1440: 
                   1441: extern time_t time();
                   1442: 
                   1443: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1444: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1445: struct tm tm;
                   1446: 
1.126     brouard  1447: char strcurr[80], strfor[80];
                   1448: 
                   1449: char *endptr;
                   1450: long lval;
                   1451: double dval;
                   1452: 
                   1453: #define NR_END 1
                   1454: #define FREE_ARG char*
                   1455: #define FTOL 1.0e-10
                   1456: 
                   1457: #define NRANSI 
1.240     brouard  1458: #define ITMAX 200
                   1459: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1460: 
                   1461: #define TOL 2.0e-4 
                   1462: 
                   1463: #define CGOLD 0.3819660 
                   1464: #define ZEPS 1.0e-10 
                   1465: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1466: 
                   1467: #define GOLD 1.618034 
                   1468: #define GLIMIT 100.0 
                   1469: #define TINY 1.0e-20 
                   1470: 
                   1471: static double maxarg1,maxarg2;
                   1472: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1473: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1474:   
                   1475: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1476: #define rint(a) floor(a+0.5)
1.166     brouard  1477: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1478: #define mytinydouble 1.0e-16
1.166     brouard  1479: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1480: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1481: /* static double dsqrarg; */
                   1482: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1483: static double sqrarg;
                   1484: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1485: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1486: int agegomp= AGEGOMP;
                   1487: 
                   1488: int imx; 
                   1489: int stepm=1;
                   1490: /* Stepm, step in month: minimum step interpolation*/
                   1491: 
                   1492: int estepm;
                   1493: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1494: 
                   1495: int m,nb;
                   1496: long *num;
1.197     brouard  1497: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1498: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1499:                   covariate for which somebody answered excluding 
                   1500:                   undefined. Usually 2: 0 and 1. */
                   1501: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1502:                             covariate for which somebody answered including 
                   1503:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1504: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1505: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1506: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1507: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
1.126     brouard  1508: double *ageexmed,*agecens;
                   1509: double dateintmean=0;
1.296     brouard  1510:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1511:   double anprojf, mprojf, jprojf;
1.126     brouard  1512: 
1.296     brouard  1513:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1514:   double anbackf, mbackf, jbackf;
                   1515:   double jintmean,mintmean,aintmean;  
1.126     brouard  1516: double *weight;
                   1517: int **s; /* Status */
1.141     brouard  1518: double *agedc;
1.145     brouard  1519: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1520:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1521:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1522: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1523: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1524: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1525: double  idx; 
                   1526: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1527: /* Some documentation */
                   1528:       /*   Design original data
                   1529:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1530:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1531:        *                                                             ntv=3     nqtv=1
1.330     brouard  1532:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1533:        * For time varying covariate, quanti or dummies
                   1534:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1535:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1536:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1537:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1538:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1539:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1540:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1541:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1542:        */
                   1543: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1544: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
                   1545:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1546:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1547: */
1.343   ! brouard  1548: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1 */
        !          1549: /*    kmodel  1  2   3   4     5    6    7     8    9 */
1.319     brouard  1550: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1551:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1552:                                                          /* product */
                   1553: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1554:                                                          /*(single or product without age), 2 dummy*/
                   1555:                                                          /* with age product, 3 quant with age product*/
                   1556: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1557: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1558: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1559: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1560: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1561: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1562: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1563: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1564: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1565: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1566: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1567: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1568: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1569: /* Tvardk[4][1]=4;Tvardk[4][2]=3;Tvardk[7][1]=1;Tvardk[7][2]=2 */ /* Variables of a prod at position in the model equation*/
1.319     brouard  1570: /* TvarF TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
1.320     brouard  1571: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1572: /* Type                    */
                   1573: /* V         1  2  3  4  5 */
                   1574: /*           F  F  V  V  V */
                   1575: /*           D  Q  D  D  Q */
                   1576: /*                         */
                   1577: int *TvarsD;
1.330     brouard  1578: int *TnsdVar;
1.234     brouard  1579: int *TvarsDind;
                   1580: int *TvarsQ;
                   1581: int *TvarsQind;
                   1582: 
1.318     brouard  1583: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1584: int nresult=0;
1.258     brouard  1585: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1586: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1587: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1588: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1589: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1590: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1591: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1592: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1593: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1594: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1595: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1596: 
                   1597: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
                   1598:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1599:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1600: */
1.234     brouard  1601: /* int *TDvar; /\**< TDvar[1]=4,  TDvarF[2]=3, TDvar[3]=6  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
1.232     brouard  1602: int *TvarF; /**< TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1603: int *TvarFind; /**< TvarFind[1]=6,  TvarFind[2]=7, Tvarind[3]=9  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1604: int *TvarV; /**< TvarV[1]=Tvar[1]=5, TvarV[2]=Tvar[2]=4  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1605: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1606: int *TvarA; /**< TvarA[1]=Tvar[5]=5, TvarA[2]=Tvar[8]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1607: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  1608: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1609: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1610: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1611: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1612: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1613: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1614: int *TvarVQ; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   1615: int *TvarVQind; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
1.339     brouard  1616: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1617: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1618:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1619:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   1620:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1621:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
                   1622:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1623: int *Tvarsel; /**< Selected covariates for output */
                   1624: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1625: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1626: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1627: int *Dummy; /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.238     brouard  1628: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1629: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1630: int *Tage;
1.227     brouard  1631: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1632: int *Tmodelind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.230     brouard  1633: int *TmodelInvind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/ 
                   1634: int *TmodelInvQind; /** Tmodelqind[1]=1 for V5(quantitative varying) position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1  */
1.145     brouard  1635: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1636: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1637: int **Tvard;
1.330     brouard  1638: int **Tvardk;
1.227     brouard  1639: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1640: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1641: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1642:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1643:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1644: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1645: double *lsurv, *lpop, *tpop;
                   1646: 
1.231     brouard  1647: #define FD 1; /* Fixed dummy covariate */
                   1648: #define FQ 2; /* Fixed quantitative covariate */
                   1649: #define FP 3; /* Fixed product covariate */
                   1650: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1651: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1652: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1653: #define VD 10; /* Varying dummy covariate */
                   1654: #define VQ 11; /* Varying quantitative covariate */
                   1655: #define VP 12; /* Varying product covariate */
                   1656: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1657: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1658: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1659: #define APFD 16; /* Age product * fixed dummy covariate */
                   1660: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1661: #define APVD 18; /* Age product * varying dummy covariate */
                   1662: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1663: 
                   1664: #define FTYPE 1; /* Fixed covariate */
                   1665: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1666: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1667: 
                   1668: struct kmodel{
                   1669:        int maintype; /* main type */
                   1670:        int subtype; /* subtype */
                   1671: };
                   1672: struct kmodel modell[NCOVMAX];
                   1673: 
1.143     brouard  1674: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1675: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1676: 
                   1677: /**************** split *************************/
                   1678: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1679: {
                   1680:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1681:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1682:   */ 
                   1683:   char *ss;                            /* pointer */
1.186     brouard  1684:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1685: 
                   1686:   l1 = strlen(path );                  /* length of path */
                   1687:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1688:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1689:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1690:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1691:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1692:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1693:     /* get current working directory */
                   1694:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1695: #ifdef WIN32
                   1696:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1697: #else
                   1698:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1699: #endif
1.126     brouard  1700:       return( GLOCK_ERROR_GETCWD );
                   1701:     }
                   1702:     /* got dirc from getcwd*/
                   1703:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1704:   } else {                             /* strip directory from path */
1.126     brouard  1705:     ss++;                              /* after this, the filename */
                   1706:     l2 = strlen( ss );                 /* length of filename */
                   1707:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1708:     strcpy( name, ss );                /* save file name */
                   1709:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1710:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1711:     printf(" DIRC2 = %s \n",dirc);
                   1712:   }
                   1713:   /* We add a separator at the end of dirc if not exists */
                   1714:   l1 = strlen( dirc );                 /* length of directory */
                   1715:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1716:     dirc[l1] =  DIRSEPARATOR;
                   1717:     dirc[l1+1] = 0; 
                   1718:     printf(" DIRC3 = %s \n",dirc);
                   1719:   }
                   1720:   ss = strrchr( name, '.' );           /* find last / */
                   1721:   if (ss >0){
                   1722:     ss++;
                   1723:     strcpy(ext,ss);                    /* save extension */
                   1724:     l1= strlen( name);
                   1725:     l2= strlen(ss)+1;
                   1726:     strncpy( finame, name, l1-l2);
                   1727:     finame[l1-l2]= 0;
                   1728:   }
                   1729: 
                   1730:   return( 0 );                         /* we're done */
                   1731: }
                   1732: 
                   1733: 
                   1734: /******************************************/
                   1735: 
                   1736: void replace_back_to_slash(char *s, char*t)
                   1737: {
                   1738:   int i;
                   1739:   int lg=0;
                   1740:   i=0;
                   1741:   lg=strlen(t);
                   1742:   for(i=0; i<= lg; i++) {
                   1743:     (s[i] = t[i]);
                   1744:     if (t[i]== '\\') s[i]='/';
                   1745:   }
                   1746: }
                   1747: 
1.132     brouard  1748: char *trimbb(char *out, char *in)
1.137     brouard  1749: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1750:   char *s;
                   1751:   s=out;
                   1752:   while (*in != '\0'){
1.137     brouard  1753:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1754:       in++;
                   1755:     }
                   1756:     *out++ = *in++;
                   1757:   }
                   1758:   *out='\0';
                   1759:   return s;
                   1760: }
                   1761: 
1.187     brouard  1762: /* char *substrchaine(char *out, char *in, char *chain) */
                   1763: /* { */
                   1764: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1765: /*   char *s, *t; */
                   1766: /*   t=in;s=out; */
                   1767: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1768: /*     *out++ = *in++; */
                   1769: /*   } */
                   1770: 
                   1771: /*   /\* *in matches *chain *\/ */
                   1772: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1773: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1774: /*   } */
                   1775: /*   in--; chain--; */
                   1776: /*   while ( (*in != '\0')){ */
                   1777: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1778: /*     *out++ = *in++; */
                   1779: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1780: /*   } */
                   1781: /*   *out='\0'; */
                   1782: /*   out=s; */
                   1783: /*   return out; */
                   1784: /* } */
                   1785: char *substrchaine(char *out, char *in, char *chain)
                   1786: {
                   1787:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1788:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1789: 
                   1790:   char *strloc;
                   1791: 
                   1792:   strcpy (out, in); 
                   1793:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1794:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1795:   if(strloc != NULL){ 
                   1796:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1797:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1798:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1799:   }
                   1800:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1801:   return out;
                   1802: }
                   1803: 
                   1804: 
1.145     brouard  1805: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1806: {
1.187     brouard  1807:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1808:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1809:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1810:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1811:   */
1.160     brouard  1812:   char *s, *t;
1.145     brouard  1813:   t=in;s=in;
                   1814:   while ((*in != occ) && (*in != '\0')){
                   1815:     *alocc++ = *in++;
                   1816:   }
                   1817:   if( *in == occ){
                   1818:     *(alocc)='\0';
                   1819:     s=++in;
                   1820:   }
                   1821:  
                   1822:   if (s == t) {/* occ not found */
                   1823:     *(alocc-(in-s))='\0';
                   1824:     in=s;
                   1825:   }
                   1826:   while ( *in != '\0'){
                   1827:     *blocc++ = *in++;
                   1828:   }
                   1829: 
                   1830:   *blocc='\0';
                   1831:   return t;
                   1832: }
1.137     brouard  1833: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1834: {
1.187     brouard  1835:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1836:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1837:      gives blocc="abcdef2ghi" and alocc="j".
                   1838:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1839:   */
                   1840:   char *s, *t;
                   1841:   t=in;s=in;
                   1842:   while (*in != '\0'){
                   1843:     while( *in == occ){
                   1844:       *blocc++ = *in++;
                   1845:       s=in;
                   1846:     }
                   1847:     *blocc++ = *in++;
                   1848:   }
                   1849:   if (s == t) /* occ not found */
                   1850:     *(blocc-(in-s))='\0';
                   1851:   else
                   1852:     *(blocc-(in-s)-1)='\0';
                   1853:   in=s;
                   1854:   while ( *in != '\0'){
                   1855:     *alocc++ = *in++;
                   1856:   }
                   1857: 
                   1858:   *alocc='\0';
                   1859:   return s;
                   1860: }
                   1861: 
1.126     brouard  1862: int nbocc(char *s, char occ)
                   1863: {
                   1864:   int i,j=0;
                   1865:   int lg=20;
                   1866:   i=0;
                   1867:   lg=strlen(s);
                   1868:   for(i=0; i<= lg; i++) {
1.234     brouard  1869:     if  (s[i] == occ ) j++;
1.126     brouard  1870:   }
                   1871:   return j;
                   1872: }
                   1873: 
1.137     brouard  1874: /* void cutv(char *u,char *v, char*t, char occ) */
                   1875: /* { */
                   1876: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1877: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1878: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1879: /*   int i,lg,j,p=0; */
                   1880: /*   i=0; */
                   1881: /*   lg=strlen(t); */
                   1882: /*   for(j=0; j<=lg-1; j++) { */
                   1883: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1884: /*   } */
1.126     brouard  1885: 
1.137     brouard  1886: /*   for(j=0; j<p; j++) { */
                   1887: /*     (u[j] = t[j]); */
                   1888: /*   } */
                   1889: /*      u[p]='\0'; */
1.126     brouard  1890: 
1.137     brouard  1891: /*    for(j=0; j<= lg; j++) { */
                   1892: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1893: /*   } */
                   1894: /* } */
1.126     brouard  1895: 
1.160     brouard  1896: #ifdef _WIN32
                   1897: char * strsep(char **pp, const char *delim)
                   1898: {
                   1899:   char *p, *q;
                   1900:          
                   1901:   if ((p = *pp) == NULL)
                   1902:     return 0;
                   1903:   if ((q = strpbrk (p, delim)) != NULL)
                   1904:   {
                   1905:     *pp = q + 1;
                   1906:     *q = '\0';
                   1907:   }
                   1908:   else
                   1909:     *pp = 0;
                   1910:   return p;
                   1911: }
                   1912: #endif
                   1913: 
1.126     brouard  1914: /********************** nrerror ********************/
                   1915: 
                   1916: void nrerror(char error_text[])
                   1917: {
                   1918:   fprintf(stderr,"ERREUR ...\n");
                   1919:   fprintf(stderr,"%s\n",error_text);
                   1920:   exit(EXIT_FAILURE);
                   1921: }
                   1922: /*********************** vector *******************/
                   1923: double *vector(int nl, int nh)
                   1924: {
                   1925:   double *v;
                   1926:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1927:   if (!v) nrerror("allocation failure in vector");
                   1928:   return v-nl+NR_END;
                   1929: }
                   1930: 
                   1931: /************************ free vector ******************/
                   1932: void free_vector(double*v, int nl, int nh)
                   1933: {
                   1934:   free((FREE_ARG)(v+nl-NR_END));
                   1935: }
                   1936: 
                   1937: /************************ivector *******************************/
                   1938: int *ivector(long nl,long nh)
                   1939: {
                   1940:   int *v;
                   1941:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1942:   if (!v) nrerror("allocation failure in ivector");
                   1943:   return v-nl+NR_END;
                   1944: }
                   1945: 
                   1946: /******************free ivector **************************/
                   1947: void free_ivector(int *v, long nl, long nh)
                   1948: {
                   1949:   free((FREE_ARG)(v+nl-NR_END));
                   1950: }
                   1951: 
                   1952: /************************lvector *******************************/
                   1953: long *lvector(long nl,long nh)
                   1954: {
                   1955:   long *v;
                   1956:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1957:   if (!v) nrerror("allocation failure in ivector");
                   1958:   return v-nl+NR_END;
                   1959: }
                   1960: 
                   1961: /******************free lvector **************************/
                   1962: void free_lvector(long *v, long nl, long nh)
                   1963: {
                   1964:   free((FREE_ARG)(v+nl-NR_END));
                   1965: }
                   1966: 
                   1967: /******************* imatrix *******************************/
                   1968: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1969:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1970: { 
                   1971:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1972:   int **m; 
                   1973:   
                   1974:   /* allocate pointers to rows */ 
                   1975:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1976:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1977:   m += NR_END; 
                   1978:   m -= nrl; 
                   1979:   
                   1980:   
                   1981:   /* allocate rows and set pointers to them */ 
                   1982:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1983:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1984:   m[nrl] += NR_END; 
                   1985:   m[nrl] -= ncl; 
                   1986:   
                   1987:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1988:   
                   1989:   /* return pointer to array of pointers to rows */ 
                   1990:   return m; 
                   1991: } 
                   1992: 
                   1993: /****************** free_imatrix *************************/
                   1994: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1995:       int **m;
                   1996:       long nch,ncl,nrh,nrl; 
                   1997:      /* free an int matrix allocated by imatrix() */ 
                   1998: { 
                   1999:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2000:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2001: } 
                   2002: 
                   2003: /******************* matrix *******************************/
                   2004: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2005: {
                   2006:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2007:   double **m;
                   2008: 
                   2009:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2010:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2011:   m += NR_END;
                   2012:   m -= nrl;
                   2013: 
                   2014:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2015:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2016:   m[nrl] += NR_END;
                   2017:   m[nrl] -= ncl;
                   2018: 
                   2019:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2020:   return m;
1.145     brouard  2021:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2022: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2023: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2024:    */
                   2025: }
                   2026: 
                   2027: /*************************free matrix ************************/
                   2028: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2029: {
                   2030:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2031:   free((FREE_ARG)(m+nrl-NR_END));
                   2032: }
                   2033: 
                   2034: /******************* ma3x *******************************/
                   2035: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2036: {
                   2037:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2038:   double ***m;
                   2039: 
                   2040:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2041:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2042:   m += NR_END;
                   2043:   m -= nrl;
                   2044: 
                   2045:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2046:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2047:   m[nrl] += NR_END;
                   2048:   m[nrl] -= ncl;
                   2049: 
                   2050:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2051: 
                   2052:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2053:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2054:   m[nrl][ncl] += NR_END;
                   2055:   m[nrl][ncl] -= nll;
                   2056:   for (j=ncl+1; j<=nch; j++) 
                   2057:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2058:   
                   2059:   for (i=nrl+1; i<=nrh; i++) {
                   2060:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2061:     for (j=ncl+1; j<=nch; j++) 
                   2062:       m[i][j]=m[i][j-1]+nlay;
                   2063:   }
                   2064:   return m; 
                   2065:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2066:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2067:   */
                   2068: }
                   2069: 
                   2070: /*************************free ma3x ************************/
                   2071: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2072: {
                   2073:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2074:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2075:   free((FREE_ARG)(m+nrl-NR_END));
                   2076: }
                   2077: 
                   2078: /*************** function subdirf ***********/
                   2079: char *subdirf(char fileres[])
                   2080: {
                   2081:   /* Caution optionfilefiname is hidden */
                   2082:   strcpy(tmpout,optionfilefiname);
                   2083:   strcat(tmpout,"/"); /* Add to the right */
                   2084:   strcat(tmpout,fileres);
                   2085:   return tmpout;
                   2086: }
                   2087: 
                   2088: /*************** function subdirf2 ***********/
                   2089: char *subdirf2(char fileres[], char *preop)
                   2090: {
1.314     brouard  2091:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2092:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2093:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2094:   /* Caution optionfilefiname is hidden */
                   2095:   strcpy(tmpout,optionfilefiname);
                   2096:   strcat(tmpout,"/");
                   2097:   strcat(tmpout,preop);
                   2098:   strcat(tmpout,fileres);
                   2099:   return tmpout;
                   2100: }
                   2101: 
                   2102: /*************** function subdirf3 ***********/
                   2103: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2104: {
                   2105:   
                   2106:   /* Caution optionfilefiname is hidden */
                   2107:   strcpy(tmpout,optionfilefiname);
                   2108:   strcat(tmpout,"/");
                   2109:   strcat(tmpout,preop);
                   2110:   strcat(tmpout,preop2);
                   2111:   strcat(tmpout,fileres);
                   2112:   return tmpout;
                   2113: }
1.213     brouard  2114:  
                   2115: /*************** function subdirfext ***********/
                   2116: char *subdirfext(char fileres[], char *preop, char *postop)
                   2117: {
                   2118:   
                   2119:   strcpy(tmpout,preop);
                   2120:   strcat(tmpout,fileres);
                   2121:   strcat(tmpout,postop);
                   2122:   return tmpout;
                   2123: }
1.126     brouard  2124: 
1.213     brouard  2125: /*************** function subdirfext3 ***********/
                   2126: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2127: {
                   2128:   
                   2129:   /* Caution optionfilefiname is hidden */
                   2130:   strcpy(tmpout,optionfilefiname);
                   2131:   strcat(tmpout,"/");
                   2132:   strcat(tmpout,preop);
                   2133:   strcat(tmpout,fileres);
                   2134:   strcat(tmpout,postop);
                   2135:   return tmpout;
                   2136: }
                   2137:  
1.162     brouard  2138: char *asc_diff_time(long time_sec, char ascdiff[])
                   2139: {
                   2140:   long sec_left, days, hours, minutes;
                   2141:   days = (time_sec) / (60*60*24);
                   2142:   sec_left = (time_sec) % (60*60*24);
                   2143:   hours = (sec_left) / (60*60) ;
                   2144:   sec_left = (sec_left) %(60*60);
                   2145:   minutes = (sec_left) /60;
                   2146:   sec_left = (sec_left) % (60);
                   2147:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2148:   return ascdiff;
                   2149: }
                   2150: 
1.126     brouard  2151: /***************** f1dim *************************/
                   2152: extern int ncom; 
                   2153: extern double *pcom,*xicom;
                   2154: extern double (*nrfunc)(double []); 
                   2155:  
                   2156: double f1dim(double x) 
                   2157: { 
                   2158:   int j; 
                   2159:   double f;
                   2160:   double *xt; 
                   2161:  
                   2162:   xt=vector(1,ncom); 
                   2163:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2164:   f=(*nrfunc)(xt); 
                   2165:   free_vector(xt,1,ncom); 
                   2166:   return f; 
                   2167: } 
                   2168: 
                   2169: /*****************brent *************************/
                   2170: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2171: {
                   2172:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2173:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2174:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2175:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2176:    * returned function value. 
                   2177:   */
1.126     brouard  2178:   int iter; 
                   2179:   double a,b,d,etemp;
1.159     brouard  2180:   double fu=0,fv,fw,fx;
1.164     brouard  2181:   double ftemp=0.;
1.126     brouard  2182:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2183:   double e=0.0; 
                   2184:  
                   2185:   a=(ax < cx ? ax : cx); 
                   2186:   b=(ax > cx ? ax : cx); 
                   2187:   x=w=v=bx; 
                   2188:   fw=fv=fx=(*f)(x); 
                   2189:   for (iter=1;iter<=ITMAX;iter++) { 
                   2190:     xm=0.5*(a+b); 
                   2191:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2192:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2193:     printf(".");fflush(stdout);
                   2194:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2195: #ifdef DEBUGBRENT
1.126     brouard  2196:     printf("br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
                   2197:     fprintf(ficlog,"br %d,x=%.10e xm=%.10e b=%.10e a=%.10e tol=%.10e tol1=%.10e tol2=%.10e x-xm=%.10e fx=%.12e fu=%.12e,fw=%.12e,ftemp=%.12e,ftol=%.12e\n",iter,x,xm,b,a,tol,tol1,tol2,(x-xm),fx,fu,fw,ftemp,ftol);
                   2198:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2199: #endif
                   2200:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2201:       *xmin=x; 
                   2202:       return fx; 
                   2203:     } 
                   2204:     ftemp=fu;
                   2205:     if (fabs(e) > tol1) { 
                   2206:       r=(x-w)*(fx-fv); 
                   2207:       q=(x-v)*(fx-fw); 
                   2208:       p=(x-v)*q-(x-w)*r; 
                   2209:       q=2.0*(q-r); 
                   2210:       if (q > 0.0) p = -p; 
                   2211:       q=fabs(q); 
                   2212:       etemp=e; 
                   2213:       e=d; 
                   2214:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2215:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2216:       else { 
1.224     brouard  2217:                                d=p/q; 
                   2218:                                u=x+d; 
                   2219:                                if (u-a < tol2 || b-u < tol2) 
                   2220:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2221:       } 
                   2222:     } else { 
                   2223:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2224:     } 
                   2225:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2226:     fu=(*f)(u); 
                   2227:     if (fu <= fx) { 
                   2228:       if (u >= x) a=x; else b=x; 
                   2229:       SHFT(v,w,x,u) 
1.183     brouard  2230:       SHFT(fv,fw,fx,fu) 
                   2231:     } else { 
                   2232:       if (u < x) a=u; else b=u; 
                   2233:       if (fu <= fw || w == x) { 
1.224     brouard  2234:                                v=w; 
                   2235:                                w=u; 
                   2236:                                fv=fw; 
                   2237:                                fw=fu; 
1.183     brouard  2238:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2239:                                v=u; 
                   2240:                                fv=fu; 
1.183     brouard  2241:       } 
                   2242:     } 
1.126     brouard  2243:   } 
                   2244:   nrerror("Too many iterations in brent"); 
                   2245:   *xmin=x; 
                   2246:   return fx; 
                   2247: } 
                   2248: 
                   2249: /****************** mnbrak ***********************/
                   2250: 
                   2251: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2252:            double (*func)(double)) 
1.183     brouard  2253: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2254: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2255: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2256: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2257:    */
1.126     brouard  2258:   double ulim,u,r,q, dum;
                   2259:   double fu; 
1.187     brouard  2260: 
                   2261:   double scale=10.;
                   2262:   int iterscale=0;
                   2263: 
                   2264:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2265:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2266: 
                   2267: 
                   2268:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2269:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2270:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2271:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2272:   /* } */
                   2273: 
1.126     brouard  2274:   if (*fb > *fa) { 
                   2275:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2276:     SHFT(dum,*fb,*fa,dum) 
                   2277:   } 
1.126     brouard  2278:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2279:   *fc=(*func)(*cx); 
1.183     brouard  2280: #ifdef DEBUG
1.224     brouard  2281:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2282:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
1.183     brouard  2283: #endif
1.224     brouard  2284:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
1.126     brouard  2285:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2286:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2287:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2288:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2289:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2290:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2291:       fu=(*func)(u); 
1.163     brouard  2292: #ifdef DEBUG
                   2293:       /* f(x)=A(x-u)**2+f(u) */
                   2294:       double A, fparabu; 
                   2295:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2296:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2297:       printf("\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
                   2298:       fprintf(ficlog,"\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
1.183     brouard  2299:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2300:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2301:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2302:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2303: #endif 
1.184     brouard  2304: #ifdef MNBRAKORIGINAL
1.183     brouard  2305: #else
1.191     brouard  2306: /*       if (fu > *fc) { */
                   2307: /* #ifdef DEBUG */
                   2308: /*       printf("mnbrak4  fu > fc \n"); */
                   2309: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2310: /* #endif */
                   2311: /*     /\* SHFT(u,*cx,*cx,u) /\\* ie a=c, c=u and u=c; in that case, next SHFT(a,b,c,u) will give a=b=b, b=c=u, c=u=c and *\\/  *\/ */
                   2312: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2313: /*     dum=u; /\* Shifting c and u *\/ */
                   2314: /*     u = *cx; */
                   2315: /*     *cx = dum; */
                   2316: /*     dum = fu; */
                   2317: /*     fu = *fc; */
                   2318: /*     *fc =dum; */
                   2319: /*       } else { /\* end *\/ */
                   2320: /* #ifdef DEBUG */
                   2321: /*       printf("mnbrak3  fu < fc \n"); */
                   2322: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2323: /* #endif */
                   2324: /*     dum=u; /\* Shifting c and u *\/ */
                   2325: /*     u = *cx; */
                   2326: /*     *cx = dum; */
                   2327: /*     dum = fu; */
                   2328: /*     fu = *fc; */
                   2329: /*     *fc =dum; */
                   2330: /*       } */
1.224     brouard  2331: #ifdef DEBUGMNBRAK
                   2332:                 double A, fparabu; 
                   2333:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2334:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2335:      printf("\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
                   2336:      fprintf(ficlog,"\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
1.183     brouard  2337: #endif
1.191     brouard  2338:       dum=u; /* Shifting c and u */
                   2339:       u = *cx;
                   2340:       *cx = dum;
                   2341:       dum = fu;
                   2342:       fu = *fc;
                   2343:       *fc =dum;
1.183     brouard  2344: #endif
1.162     brouard  2345:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2346: #ifdef DEBUG
1.224     brouard  2347:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2348:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2349: #endif
1.126     brouard  2350:       fu=(*func)(u); 
                   2351:       if (fu < *fc) { 
1.183     brouard  2352: #ifdef DEBUG
1.224     brouard  2353:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2354:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2355: #endif
                   2356:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2357:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2358: #ifdef DEBUG
                   2359:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2360: #endif
                   2361:       } 
1.162     brouard  2362:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2363: #ifdef DEBUG
1.224     brouard  2364:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2365:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2366: #endif
1.126     brouard  2367:       u=ulim; 
                   2368:       fu=(*func)(u); 
1.183     brouard  2369:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2370: #ifdef DEBUG
1.224     brouard  2371:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2372:       fprintf(ficlog,"\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
1.183     brouard  2373: #endif
1.126     brouard  2374:       u=(*cx)+GOLD*(*cx-*bx); 
                   2375:       fu=(*func)(u); 
1.224     brouard  2376: #ifdef DEBUG
                   2377:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2378:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2379: #endif
1.183     brouard  2380:     } /* end tests */
1.126     brouard  2381:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2382:     SHFT(*fa,*fb,*fc,fu) 
                   2383: #ifdef DEBUG
1.224     brouard  2384:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2385:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
1.183     brouard  2386: #endif
                   2387:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1.126     brouard  2388: } 
                   2389: 
                   2390: /*************** linmin ************************/
1.162     brouard  2391: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2392: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2393: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2394: the value of func at the returned location p . This is actually all accomplished by calling the
                   2395: routines mnbrak and brent .*/
1.126     brouard  2396: int ncom; 
                   2397: double *pcom,*xicom;
                   2398: double (*nrfunc)(double []); 
                   2399:  
1.224     brouard  2400: #ifdef LINMINORIGINAL
1.126     brouard  2401: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2402: #else
                   2403: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2404: #endif
1.126     brouard  2405: { 
                   2406:   double brent(double ax, double bx, double cx, 
                   2407:               double (*f)(double), double tol, double *xmin); 
                   2408:   double f1dim(double x); 
                   2409:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2410:              double *fc, double (*func)(double)); 
                   2411:   int j; 
                   2412:   double xx,xmin,bx,ax; 
                   2413:   double fx,fb,fa;
1.187     brouard  2414: 
1.203     brouard  2415: #ifdef LINMINORIGINAL
                   2416: #else
                   2417:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2418: #endif
                   2419:   
1.126     brouard  2420:   ncom=n; 
                   2421:   pcom=vector(1,n); 
                   2422:   xicom=vector(1,n); 
                   2423:   nrfunc=func; 
                   2424:   for (j=1;j<=n;j++) { 
                   2425:     pcom[j]=p[j]; 
1.202     brouard  2426:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2427:   } 
1.187     brouard  2428: 
1.203     brouard  2429: #ifdef LINMINORIGINAL
                   2430:   xx=1.;
                   2431: #else
                   2432:   axs=0.0;
                   2433:   xxs=1.;
                   2434:   do{
                   2435:     xx= xxs;
                   2436: #endif
1.187     brouard  2437:     ax=0.;
                   2438:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2439:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2440:     /* xt[x,j]=pcom[j]+x*xicom[j]  f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and  f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j))   */
                   2441:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2442:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2443:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2444:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
1.203     brouard  2445: #ifdef LINMINORIGINAL
                   2446: #else
                   2447:     if (fx != fx){
1.224     brouard  2448:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2449:                        printf("|");
                   2450:                        fprintf(ficlog,"|");
1.203     brouard  2451: #ifdef DEBUGLINMIN
1.224     brouard  2452:                        printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n",  axs, xxs, fx,fb, fa, xx, ax, bx);
1.203     brouard  2453: #endif
                   2454:     }
1.224     brouard  2455:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2456: #endif
                   2457:   
1.191     brouard  2458: #ifdef DEBUGLINMIN
                   2459:   printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
1.202     brouard  2460:   fprintf(ficlog,"\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
1.191     brouard  2461: #endif
1.224     brouard  2462: #ifdef LINMINORIGINAL
                   2463: #else
1.317     brouard  2464:   if(fb == fx){ /* Flat function in the direction */
                   2465:     xmin=xx;
1.224     brouard  2466:     *flat=1;
1.317     brouard  2467:   }else{
1.224     brouard  2468:     *flat=0;
                   2469: #endif
                   2470:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2471:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2472:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2473:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2474:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2475:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2476: #ifdef DEBUG
1.224     brouard  2477:   printf("retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
                   2478:   fprintf(ficlog,"retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
                   2479: #endif
                   2480: #ifdef LINMINORIGINAL
                   2481: #else
                   2482:                        }
1.126     brouard  2483: #endif
1.191     brouard  2484: #ifdef DEBUGLINMIN
                   2485:   printf("linmin end ");
1.202     brouard  2486:   fprintf(ficlog,"linmin end ");
1.191     brouard  2487: #endif
1.126     brouard  2488:   for (j=1;j<=n;j++) { 
1.203     brouard  2489: #ifdef LINMINORIGINAL
                   2490:     xi[j] *= xmin; 
                   2491: #else
                   2492: #ifdef DEBUGLINMIN
                   2493:     if(xxs <1.0)
                   2494:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2495: #endif
                   2496:     xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
                   2497: #ifdef DEBUGLINMIN
                   2498:     if(xxs <1.0)
                   2499:       printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs );
                   2500: #endif
                   2501: #endif
1.187     brouard  2502:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2503:   } 
1.191     brouard  2504: #ifdef DEBUGLINMIN
1.203     brouard  2505:   printf("\n");
1.191     brouard  2506:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2507:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.191     brouard  2508:   for (j=1;j<=n;j++) { 
1.202     brouard  2509:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2510:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2511:     if(j % ncovmodel == 0){
1.191     brouard  2512:       printf("\n");
1.202     brouard  2513:       fprintf(ficlog,"\n");
                   2514:     }
1.191     brouard  2515:   }
1.203     brouard  2516: #else
1.191     brouard  2517: #endif
1.126     brouard  2518:   free_vector(xicom,1,n); 
                   2519:   free_vector(pcom,1,n); 
                   2520: } 
                   2521: 
                   2522: 
                   2523: /*************** powell ************************/
1.162     brouard  2524: /*
1.317     brouard  2525: Minimization of a function func of n variables. Input consists in an initial starting point
                   2526: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2527: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2528: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2529: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2530: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2531:  */
1.224     brouard  2532: #ifdef LINMINORIGINAL
                   2533: #else
                   2534:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2535:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2536: #endif
1.126     brouard  2537: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2538:            double (*func)(double [])) 
                   2539: { 
1.224     brouard  2540: #ifdef LINMINORIGINAL
                   2541:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2542:              double (*func)(double [])); 
1.224     brouard  2543: #else 
1.241     brouard  2544:  void linmin(double p[], double xi[], int n, double *fret,
                   2545:             double (*func)(double []),int *flat); 
1.224     brouard  2546: #endif
1.239     brouard  2547:  int i,ibig,j,jk,k; 
1.126     brouard  2548:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2549:   double directest;
1.126     brouard  2550:   double fp,fptt;
                   2551:   double *xits;
                   2552:   int niterf, itmp;
                   2553: 
                   2554:   pt=vector(1,n); 
                   2555:   ptt=vector(1,n); 
                   2556:   xit=vector(1,n); 
                   2557:   xits=vector(1,n); 
                   2558:   *fret=(*func)(p); 
                   2559:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2560:   rcurr_time = time(NULL);
                   2561:   fp=(*fret); /* Initialisation */
1.126     brouard  2562:   for (*iter=1;;++(*iter)) { 
                   2563:     ibig=0; 
                   2564:     del=0.0; 
1.157     brouard  2565:     rlast_time=rcurr_time;
                   2566:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2567:     rcurr_time = time(NULL);  
                   2568:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2569:     /* printf("\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout); */
                   2570:     /* fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog); */
                   2571:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2572:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2573: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2574:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2575:     for (i=1;i<=n;i++) {
1.126     brouard  2576:       fprintf(ficrespow," %.12lf", p[i]);
                   2577:     }
1.239     brouard  2578:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2579:     printf("\n#model=  1      +     age ");
                   2580:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2581:     if(nagesqr==1){
1.241     brouard  2582:        printf("  + age*age  ");
                   2583:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2584:     }
                   2585:     for(j=1;j <=ncovmodel-2;j++){
                   2586:       if(Typevar[j]==0) {
                   2587:        printf("  +      V%d  ",Tvar[j]);
                   2588:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2589:       }else if(Typevar[j]==1) {
                   2590:        printf("  +    V%d*age ",Tvar[j]);
                   2591:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2592:       }else if(Typevar[j]==2) {
                   2593:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2594:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2595:       }
                   2596:     }
1.126     brouard  2597:     printf("\n");
1.239     brouard  2598: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2599: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2600:     fprintf(ficlog,"\n");
1.239     brouard  2601:     for(i=1,jk=1; i <=nlstate; i++){
                   2602:       for(k=1; k <=(nlstate+ndeath); k++){
                   2603:        if (k != i) {
                   2604:          printf("%d%d ",i,k);
                   2605:          fprintf(ficlog,"%d%d ",i,k);
                   2606:          for(j=1; j <=ncovmodel; j++){
                   2607:            printf("%12.7f ",p[jk]);
                   2608:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2609:            jk++; 
                   2610:          }
                   2611:          printf("\n");
                   2612:          fprintf(ficlog,"\n");
                   2613:        }
                   2614:       }
                   2615:     }
1.241     brouard  2616:     if(*iter <=3 && *iter >1){
1.157     brouard  2617:       tml = *localtime(&rcurr_time);
                   2618:       strcpy(strcurr,asctime(&tml));
                   2619:       rforecast_time=rcurr_time; 
1.126     brouard  2620:       itmp = strlen(strcurr);
                   2621:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2622:        strcurr[itmp-1]='\0';
1.162     brouard  2623:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2624:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2625:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2626:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2627:        forecast_time = *localtime(&rforecast_time);
                   2628:        strcpy(strfor,asctime(&forecast_time));
                   2629:        itmp = strlen(strfor);
                   2630:        if(strfor[itmp-1]=='\n')
                   2631:          strfor[itmp-1]='\0';
                   2632:        printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   2633:        fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  2634:       }
                   2635:     }
1.187     brouard  2636:     for (i=1;i<=n;i++) { /* For each direction i */
                   2637:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2638:       fptt=(*fret); 
                   2639: #ifdef DEBUG
1.203     brouard  2640:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2641:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2642: #endif
1.203     brouard  2643:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2644:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2645: #ifdef LINMINORIGINAL
1.188     brouard  2646:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2647: #else
                   2648:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2649:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2650: #endif
                   2651:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2652:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2653:                                /* because that direction will be replaced unless the gain del is small */
                   2654:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2655:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2656:                                /* with the new direction. */
                   2657:                                del=fabs(fptt-(*fret)); 
                   2658:                                ibig=i; 
1.126     brouard  2659:       } 
                   2660: #ifdef DEBUG
                   2661:       printf("%d %.12e",i,(*fret));
                   2662:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2663:       for (j=1;j<=n;j++) {
1.224     brouard  2664:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2665:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2666:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2667:       }
                   2668:       for(j=1;j<=n;j++) {
1.225     brouard  2669:                                printf(" p(%d)=%.12e",j,p[j]);
                   2670:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2671:       }
                   2672:       printf("\n");
                   2673:       fprintf(ficlog,"\n");
                   2674: #endif
1.187     brouard  2675:     } /* end loop on each direction i */
                   2676:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2677:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2678:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2679:     for(j=1;j<=n;j++) {
                   2680:       if(flatdir[j] >0){
                   2681:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2682:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2683:       }
1.319     brouard  2684:       /* printf("\n"); */
                   2685:       /* fprintf(ficlog,"\n"); */
                   2686:     }
1.243     brouard  2687:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2688:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2689:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2690:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2691:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2692:       /* decreased of more than 3.84  */
                   2693:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2694:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2695:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2696:                        
1.188     brouard  2697:       /* Starting the program with initial values given by a former maximization will simply change */
                   2698:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2699:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2700:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2701: #ifdef DEBUG
                   2702:       int k[2],l;
                   2703:       k[0]=1;
                   2704:       k[1]=-1;
                   2705:       printf("Max: %.12e",(*func)(p));
                   2706:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2707:       for (j=1;j<=n;j++) {
                   2708:        printf(" %.12e",p[j]);
                   2709:        fprintf(ficlog," %.12e",p[j]);
                   2710:       }
                   2711:       printf("\n");
                   2712:       fprintf(ficlog,"\n");
                   2713:       for(l=0;l<=1;l++) {
                   2714:        for (j=1;j<=n;j++) {
                   2715:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2716:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2717:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2718:        }
                   2719:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2720:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2721:       }
                   2722: #endif
                   2723: 
                   2724:       free_vector(xit,1,n); 
                   2725:       free_vector(xits,1,n); 
                   2726:       free_vector(ptt,1,n); 
                   2727:       free_vector(pt,1,n); 
                   2728:       return; 
1.192     brouard  2729:     } /* enough precision */ 
1.240     brouard  2730:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2731:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2732:       ptt[j]=2.0*p[j]-pt[j]; 
                   2733:       xit[j]=p[j]-pt[j]; 
                   2734:       pt[j]=p[j]; 
                   2735:     } 
1.181     brouard  2736:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2737: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2738:                if (*iter <=4) {
1.225     brouard  2739: #else
                   2740: #endif
1.224     brouard  2741: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2742: #else
1.161     brouard  2743:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2744: #endif
1.162     brouard  2745:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2746:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2747:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2748:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2749:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2750:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2751:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2752:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2753:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2754:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2755:       /* mu² and del² are equal when f3=f1 */
                   2756:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2757:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2758:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2759:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2760: #ifdef NRCORIGINAL
                   2761:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2762: #else
                   2763:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1.161     brouard  2764:       t= t- del*SQR(fp-fptt);
1.183     brouard  2765: #endif
1.202     brouard  2766:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2767: #ifdef DEBUG
1.181     brouard  2768:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf  directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
                   2769:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1.161     brouard  2770:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2771:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2772:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2773:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2774:       printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
                   2775:       fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
                   2776: #endif
1.183     brouard  2777: #ifdef POWELLORIGINAL
                   2778:       if (t < 0.0) { /* Then we use it for new direction */
                   2779: #else
1.182     brouard  2780:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2781:                                printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.192     brouard  2782:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.224     brouard  2783:         fprintf(ficlog,"directest= %.12lf (if directest<0 or t<0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.192     brouard  2784:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2785:       } 
1.181     brouard  2786:       if (directest < 0.0) { /* Then we use it for new direction */
                   2787: #endif
1.191     brouard  2788: #ifdef DEBUGLINMIN
1.234     brouard  2789:        printf("Before linmin in direction P%d-P0\n",n);
                   2790:        for (j=1;j<=n;j++) {
                   2791:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2792:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2793:          if(j % ncovmodel == 0){
                   2794:            printf("\n");
                   2795:            fprintf(ficlog,"\n");
                   2796:          }
                   2797:        }
1.224     brouard  2798: #endif
                   2799: #ifdef LINMINORIGINAL
1.234     brouard  2800:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2801: #else
1.234     brouard  2802:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2803:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2804: #endif
1.234     brouard  2805:        
1.191     brouard  2806: #ifdef DEBUGLINMIN
1.234     brouard  2807:        for (j=1;j<=n;j++) { 
                   2808:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2809:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2810:          if(j % ncovmodel == 0){
                   2811:            printf("\n");
                   2812:            fprintf(ficlog,"\n");
                   2813:          }
                   2814:        }
1.224     brouard  2815: #endif
1.234     brouard  2816:        for (j=1;j<=n;j++) { 
                   2817:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2818:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2819:        }
1.224     brouard  2820: #ifdef LINMINORIGINAL
                   2821: #else
1.234     brouard  2822:        for (j=1, flatd=0;j<=n;j++) {
                   2823:          if(flatdir[j]>0)
                   2824:            flatd++;
                   2825:        }
                   2826:        if(flatd >0){
1.255     brouard  2827:          printf("%d flat directions: ",flatd);
                   2828:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2829:          for (j=1;j<=n;j++) { 
                   2830:            if(flatdir[j]>0){
                   2831:              printf("%d ",j);
                   2832:              fprintf(ficlog,"%d ",j);
                   2833:            }
                   2834:          }
                   2835:          printf("\n");
                   2836:          fprintf(ficlog,"\n");
1.319     brouard  2837: #ifdef FLATSUP
                   2838:           free_vector(xit,1,n); 
                   2839:           free_vector(xits,1,n); 
                   2840:           free_vector(ptt,1,n); 
                   2841:           free_vector(pt,1,n); 
                   2842:           return;
                   2843: #endif
1.234     brouard  2844:        }
1.191     brouard  2845: #endif
1.234     brouard  2846:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2847:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2848:        
1.126     brouard  2849: #ifdef DEBUG
1.234     brouard  2850:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2851:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2852:        for(j=1;j<=n;j++){
                   2853:          printf(" %lf",xit[j]);
                   2854:          fprintf(ficlog," %lf",xit[j]);
                   2855:        }
                   2856:        printf("\n");
                   2857:        fprintf(ficlog,"\n");
1.126     brouard  2858: #endif
1.192     brouard  2859:       } /* end of t or directest negative */
1.224     brouard  2860: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2861: #else
1.234     brouard  2862:       } /* end if (fptt < fp)  */
1.192     brouard  2863: #endif
1.225     brouard  2864: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2865:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2866: #else
1.224     brouard  2867: #endif
1.234     brouard  2868:                } /* loop iteration */ 
1.126     brouard  2869: } 
1.234     brouard  2870:   
1.126     brouard  2871: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2872:   
1.235     brouard  2873:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
1.234     brouard  2874:   {
1.338     brouard  2875:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2876:      *   (and selected quantitative values in nres)
                   2877:      *  by left multiplying the unit
                   2878:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2879:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2880:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2881:      * or prevalence in state 1, prevalence in state 2, 0
                   2882:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2883:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2884:      * Output is prlim.
                   2885:      * Initial matrix pimij 
                   2886:      */
1.206     brouard  2887:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2888:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2889:   /*  0,                   0                  , 1} */
                   2890:   /*
                   2891:    * and after some iteration: */
                   2892:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2893:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2894:   /*  0,                   0                  , 1} */
                   2895:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2896:   /* {0.51571254859325999, 0.4842874514067399, */
                   2897:   /*  0.51326036147820708, 0.48673963852179264} */
                   2898:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2899:     
1.332     brouard  2900:     int i, ii,j,k, k1;
1.209     brouard  2901:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2902:   /* double **matprod2(); */ /* test */
1.218     brouard  2903:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2904:   double **newm;
1.209     brouard  2905:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2906:   int ncvloop=0;
1.288     brouard  2907:   int first=0;
1.169     brouard  2908:   
1.209     brouard  2909:   min=vector(1,nlstate);
                   2910:   max=vector(1,nlstate);
                   2911:   meandiff=vector(1,nlstate);
                   2912: 
1.218     brouard  2913:        /* Starting with matrix unity */
1.126     brouard  2914:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2915:     for (j=1;j<=nlstate+ndeath;j++){
                   2916:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2917:     }
1.169     brouard  2918:   
                   2919:   cov[1]=1.;
                   2920:   
                   2921:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2922:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2923:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2924:     ncvloop++;
1.126     brouard  2925:     newm=savm;
                   2926:     /* Covariates have to be included here again */
1.138     brouard  2927:     cov[2]=agefin;
1.319     brouard  2928:      if(nagesqr==1){
                   2929:       cov[3]= agefin*agefin;
                   2930:      }
1.332     brouard  2931:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2932:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2933:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2934:        if(Typevar[k1]==1){ /* A product with age */
                   2935:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2936:        }else{
                   2937:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2938:        }
                   2939:      }/* End of loop on model equation */
                   2940:      
                   2941: /* Start of old code (replaced by a loop on position in the model equation */
                   2942:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2943:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2944:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2945:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2946:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2947:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2948:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2949:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2950:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2951:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2952:     /*    *nsd=3                              (1)  (2)           (3) */
                   2953:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2954:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2955:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2956:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2957:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2958:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2959:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2960:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2961:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2962:     /*    *TvarsDpType */
                   2963:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2964:     /*    * nsd=1              (1)           (2) */
                   2965:     /*    *TvarsD[nsd]          3             2 */
                   2966:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2967:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2968:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2969:     /*    *\/ */
                   2970:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2971:     /*   /\* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
                   2972:     /* } */
                   2973:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2974:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2975:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2976:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2977:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2978:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2979:     /*   /\* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); *\/ */
                   2980:     /* } */
                   2981:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2982:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2983:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2984:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2985:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2986:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2987:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2988:     /*   } */
                   2989:     /*   /\* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
                   2990:     /* } */
                   2991:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2992:     /*   /\* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); *\/ */
                   2993:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2994:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2995:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2996:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2997:     /*         }else{ */
                   2998:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2999:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3000:     /*         } */
                   3001:     /*   }else{ */
                   3002:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3003:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3004:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3005:     /*         }else{ */
                   3006:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3007:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3008:     /*         } */
                   3009:     /*   } */
                   3010:     /* } /\* End product without age *\/ */
                   3011: /* ENd of old code */
1.138     brouard  3012:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3013:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3014:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  3015:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3016:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  3017:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  3018:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  3019:     
1.126     brouard  3020:     savm=oldm;
                   3021:     oldm=newm;
1.209     brouard  3022: 
                   3023:     for(j=1; j<=nlstate; j++){
                   3024:       max[j]=0.;
                   3025:       min[j]=1.;
                   3026:     }
                   3027:     for(i=1;i<=nlstate;i++){
                   3028:       sumnew=0;
                   3029:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3030:       for(j=1; j<=nlstate; j++){ 
                   3031:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3032:        max[j]=FMAX(max[j],prlim[i][j]);
                   3033:        min[j]=FMIN(min[j],prlim[i][j]);
                   3034:       }
                   3035:     }
                   3036: 
1.126     brouard  3037:     maxmax=0.;
1.209     brouard  3038:     for(j=1; j<=nlstate; j++){
                   3039:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3040:       maxmax=FMAX(maxmax,meandiff[j]);
                   3041:       /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
1.169     brouard  3042:     } /* j loop */
1.203     brouard  3043:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3044:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  3045:     if(maxmax < ftolpl){
1.209     brouard  3046:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3047:       free_vector(min,1,nlstate);
                   3048:       free_vector(max,1,nlstate);
                   3049:       free_vector(meandiff,1,nlstate);
1.126     brouard  3050:       return prlim;
                   3051:     }
1.288     brouard  3052:   } /* agefin loop */
1.208     brouard  3053:     /* After some age loop it doesn't converge */
1.288     brouard  3054:   if(!first){
                   3055:     first=1;
                   3056:     printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d). Others in log file only...\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
1.317     brouard  3057:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3058:   }else if (first >=1 && first <10){
                   3059:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3060:     first++;
                   3061:   }else if (first ==10){
                   3062:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3063:     printf("Warning: the stable prevalence dit not converge. This warning came too often, IMaCh will stop notifying, even in its log file. Look at the graphs to appreciate the non convergence.\n");
                   3064:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3065:     first++;
1.288     brouard  3066:   }
                   3067: 
1.209     brouard  3068:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
                   3069:   free_vector(min,1,nlstate);
                   3070:   free_vector(max,1,nlstate);
                   3071:   free_vector(meandiff,1,nlstate);
1.208     brouard  3072:   
1.169     brouard  3073:   return prlim; /* should not reach here */
1.126     brouard  3074: }
                   3075: 
1.217     brouard  3076: 
                   3077:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3078: 
1.218     brouard  3079:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   3080:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
1.242     brouard  3081:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3082: {
1.264     brouard  3083:   /* Computes the prevalence limit in each live state at age x and for covariate combination ij (<=2**cptcoveff) by left multiplying the unit
1.217     brouard  3084:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3085:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3086:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3087:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3088:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3089:   /* Initial matrix pimij */
                   3090:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3091:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3092:   /*  0,                   0                  , 1} */
                   3093:   /*
                   3094:    * and after some iteration: */
                   3095:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3096:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3097:   /*  0,                   0                  , 1} */
                   3098:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3099:   /* {0.51571254859325999, 0.4842874514067399, */
                   3100:   /*  0.51326036147820708, 0.48673963852179264} */
                   3101:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3102: 
1.332     brouard  3103:   int i, ii,j,k, k1;
1.247     brouard  3104:   int first=0;
1.217     brouard  3105:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3106:   /* double **matprod2(); */ /* test */
                   3107:   double **out, cov[NCOVMAX+1], **bmij();
                   3108:   double **newm;
1.218     brouard  3109:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3110:   double        **oldm, **savm;  /* for use */
                   3111: 
1.217     brouard  3112:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3113:   int ncvloop=0;
                   3114:   
                   3115:   min=vector(1,nlstate);
                   3116:   max=vector(1,nlstate);
                   3117:   meandiff=vector(1,nlstate);
                   3118: 
1.266     brouard  3119:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3120:   oldm=oldms; savm=savms;
                   3121:   
                   3122:   /* Starting with matrix unity */
                   3123:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3124:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3125:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3126:     }
                   3127:   
                   3128:   cov[1]=1.;
                   3129:   
                   3130:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3131:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3132:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3133:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3134:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3135:     ncvloop++;
1.218     brouard  3136:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3137:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3138:     /* Covariates have to be included here again */
                   3139:     cov[2]=agefin;
1.319     brouard  3140:     if(nagesqr==1){
1.217     brouard  3141:       cov[3]= agefin*agefin;;
1.319     brouard  3142:     }
1.332     brouard  3143:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3144:       if(Typevar[k1]==1){ /* A product with age */
                   3145:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3146:       }else{
1.332     brouard  3147:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3148:       }
1.332     brouard  3149:     }/* End of loop on model equation */
                   3150: 
                   3151: /* Old code */ 
                   3152: 
                   3153:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3154:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3155:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3156:     /*   /\* printf("bprevalim Dummy agefin=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agefin,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
                   3157:     /* } */
                   3158:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3159:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3160:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3161:     /* /\*   /\\* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); *\\/ *\/ */
                   3162:     /* /\* } *\/ */
                   3163:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3164:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3165:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3166:     /*   /\* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); *\/ */
                   3167:     /* } */
                   3168:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3169:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3170:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3171:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3172:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3173:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3174:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3175:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3176:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3177:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3178:     /*   } */
                   3179:     /*   /\* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
                   3180:     /* } */
                   3181:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3182:     /*   /\* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); *\/ */
                   3183:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3184:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3185:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3186:     /*         }else{ */
                   3187:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3188:     /*         } */
                   3189:     /*   }else{ */
                   3190:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3191:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3192:     /*         }else{ */
                   3193:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3194:     /*         } */
                   3195:     /*   } */
                   3196:     /* } */
1.217     brouard  3197:     
                   3198:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3199:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3200:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3201:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3202:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3203:                /* ij should be linked to the correct index of cov */
                   3204:                /* age and covariate values ij are in 'cov', but we need to pass
                   3205:                 * ij for the observed prevalence at age and status and covariate
                   3206:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3207:                 */
                   3208:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   3209:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   3210:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.268     brouard  3211:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3212:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3213:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3214:     /*         printf("%d newm= ",i); */
                   3215:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3216:     /*           printf("%f ",newm[i][j]); */
                   3217:     /*         } */
                   3218:     /*         printf("oldm * "); */
                   3219:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3220:     /*           printf("%f ",oldm[i][j]); */
                   3221:     /*         } */
1.268     brouard  3222:     /*         printf(" bmmij "); */
1.266     brouard  3223:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3224:     /*           printf("%f ",pmmij[i][j]); */
                   3225:     /*         } */
                   3226:     /*         printf("\n"); */
                   3227:     /*   } */
                   3228:     /* } */
1.217     brouard  3229:     savm=oldm;
                   3230:     oldm=newm;
1.266     brouard  3231: 
1.217     brouard  3232:     for(j=1; j<=nlstate; j++){
                   3233:       max[j]=0.;
                   3234:       min[j]=1.;
                   3235:     }
                   3236:     for(j=1; j<=nlstate; j++){ 
                   3237:       for(i=1;i<=nlstate;i++){
1.234     brouard  3238:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3239:        bprlim[i][j]= newm[i][j];
                   3240:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3241:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3242:       }
                   3243:     }
1.218     brouard  3244:                
1.217     brouard  3245:     maxmax=0.;
                   3246:     for(i=1; i<=nlstate; i++){
1.318     brouard  3247:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3248:       maxmax=FMAX(maxmax,meandiff[i]);
                   3249:       /* printf("Back age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, i, meandiff[i],(int)agefin, i, max[i], i, min[i],maxmax); */
1.268     brouard  3250:     } /* i loop */
1.217     brouard  3251:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3252:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3253:     if(maxmax < ftolpl){
1.220     brouard  3254:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3255:       free_vector(min,1,nlstate);
                   3256:       free_vector(max,1,nlstate);
                   3257:       free_vector(meandiff,1,nlstate);
                   3258:       return bprlim;
                   3259:     }
1.288     brouard  3260:   } /* agefin loop */
1.217     brouard  3261:     /* After some age loop it doesn't converge */
1.288     brouard  3262:   if(!first){
1.247     brouard  3263:     first=1;
                   3264:     printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. Others in log file only...\n\
                   3265: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   3266:   }
                   3267:   fprintf(ficlog,"Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.217     brouard  3268: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   3269:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
                   3270:   free_vector(min,1,nlstate);
                   3271:   free_vector(max,1,nlstate);
                   3272:   free_vector(meandiff,1,nlstate);
                   3273:   
                   3274:   return bprlim; /* should not reach here */
                   3275: }
                   3276: 
1.126     brouard  3277: /*************** transition probabilities ***************/ 
                   3278: 
                   3279: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3280: {
1.138     brouard  3281:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3282:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3283:      model to the ncovmodel covariates (including constant and age).
                   3284:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3285:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3286:      ncth covariate in the global vector x is given by the formula:
                   3287:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3288:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3289:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3290:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3291:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3292:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3293:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3294:   */
                   3295:   double s1, lnpijopii;
1.126     brouard  3296:   /*double t34;*/
1.164     brouard  3297:   int i,j, nc, ii, jj;
1.126     brouard  3298: 
1.223     brouard  3299:   for(i=1; i<= nlstate; i++){
                   3300:     for(j=1; j<i;j++){
                   3301:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3302:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3303:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3304:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3305:       }
                   3306:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3307:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3308:     }
                   3309:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3310:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3311:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3312:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3313:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3314:       }
                   3315:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3316:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3317:     }
                   3318:   }
1.218     brouard  3319:   
1.223     brouard  3320:   for(i=1; i<= nlstate; i++){
                   3321:     s1=0;
                   3322:     for(j=1; j<i; j++){
1.339     brouard  3323:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3324:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3325:     }
                   3326:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  3327:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3328:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3329:     }
                   3330:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3331:     ps[i][i]=1./(s1+1.);
                   3332:     /* Computing other pijs */
                   3333:     for(j=1; j<i; j++)
1.325     brouard  3334:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3335:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3336:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3337:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3338:   } /* end i */
1.218     brouard  3339:   
1.223     brouard  3340:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3341:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3342:       ps[ii][jj]=0;
                   3343:       ps[ii][ii]=1;
                   3344:     }
                   3345:   }
1.294     brouard  3346: 
                   3347: 
1.223     brouard  3348:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3349:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3350:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3351:   /*   } */
                   3352:   /*   printf("\n "); */
                   3353:   /* } */
                   3354:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3355:   /*
                   3356:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3357:                goto end;*/
1.266     brouard  3358:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3359: }
                   3360: 
1.218     brouard  3361: /*************** backward transition probabilities ***************/ 
                   3362: 
                   3363:  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3364: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3365:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3366: {
1.302     brouard  3367:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
1.266     brouard  3368:    * Call to pmij(cov and x), call to cross prevalence, sums and inverses, left multiply, and returns in **ps as well as **bmij.
1.222     brouard  3369:    */
1.218     brouard  3370:   int i, ii, j,k;
1.222     brouard  3371:   
                   3372:   double **out, **pmij();
                   3373:   double sumnew=0.;
1.218     brouard  3374:   double agefin;
1.292     brouard  3375:   double k3=0.; /* constant of the w_x diagonal matrix (in order for B to sum to 1 even for death state) */
1.222     brouard  3376:   double **dnewm, **dsavm, **doldm;
                   3377:   double **bbmij;
                   3378:   
1.218     brouard  3379:   doldm=ddoldms; /* global pointers */
1.222     brouard  3380:   dnewm=ddnewms;
                   3381:   dsavm=ddsavms;
1.318     brouard  3382: 
                   3383:   /* Debug */
                   3384:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3385:   agefin=cov[2];
1.268     brouard  3386:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3387:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3388:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3389:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3390: 
                   3391:   /* P_x */
1.325     brouard  3392:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3393:   /* outputs pmmij which is a stochastic matrix in row */
                   3394: 
                   3395:   /* Diag(w_x) */
1.292     brouard  3396:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3397:   sumnew=0.;
1.269     brouard  3398:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3399:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3400:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3401:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3402:   }
                   3403:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3404:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3405:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3406:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3407:     }
                   3408:   }else{
                   3409:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3410:       for (j=1;j<=nlstate+ndeath;j++)
                   3411:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3412:     }
                   3413:     /* if(sumnew <0.9){ */
                   3414:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3415:     /* } */
                   3416:   }
                   3417:   k3=0.0;  /* We put the last diagonal to 0 */
                   3418:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3419:       doldm[ii][ii]= k3;
                   3420:   }
                   3421:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3422:   
1.292     brouard  3423:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3424:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3425: 
1.292     brouard  3426:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3427:   /* w1 p11 + w2 p21 only on live states N1./N..*N11/N1. + N2./N..*N21/N2.=(N11+N21)/N..=N.1/N.. */
1.222     brouard  3428:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3429:     sumnew=0.;
1.222     brouard  3430:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3431:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3432:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3433:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3434:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3435:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3436:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3437:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3438:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3439:        /* }else */
1.268     brouard  3440:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3441:     } /*End ii */
                   3442:   } /* End j, At the end dsavm is diag[1/(w_1p1i+w_2 p2i)] for ALL states even if the sum is only for live states */
                   3443: 
1.292     brouard  3444:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3445:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3446:   /* end bmij */
1.266     brouard  3447:   return ps; /*pointer is unchanged */
1.218     brouard  3448: }
1.217     brouard  3449: /*************** transition probabilities ***************/ 
                   3450: 
1.218     brouard  3451: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3452: {
                   3453:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3454:      computes the probability to be observed in state j being in state i by appying the
                   3455:      model to the ncovmodel covariates (including constant and age).
                   3456:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3457:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3458:      ncth covariate in the global vector x is given by the formula:
                   3459:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3460:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3461:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3462:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3463:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3464:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3465:   */
                   3466:   double s1, lnpijopii;
                   3467:   /*double t34;*/
                   3468:   int i,j, nc, ii, jj;
                   3469: 
1.234     brouard  3470:   for(i=1; i<= nlstate; i++){
                   3471:     for(j=1; j<i;j++){
                   3472:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3473:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3474:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3475:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3476:       }
                   3477:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3478:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3479:     }
                   3480:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3481:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3482:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3483:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3484:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3485:       }
                   3486:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3487:     }
                   3488:   }
                   3489:   
                   3490:   for(i=1; i<= nlstate; i++){
                   3491:     s1=0;
                   3492:     for(j=1; j<i; j++){
                   3493:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3494:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3495:     }
                   3496:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3497:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3498:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3499:     }
                   3500:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3501:     ps[i][i]=1./(s1+1.);
                   3502:     /* Computing other pijs */
                   3503:     for(j=1; j<i; j++)
                   3504:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3505:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3506:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3507:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3508:   } /* end i */
                   3509:   
                   3510:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3511:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3512:       ps[ii][jj]=0;
                   3513:       ps[ii][ii]=1;
                   3514:     }
                   3515:   }
1.296     brouard  3516:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3517:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3518:     s1=0.;
                   3519:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3520:       s1+=ps[ii][jj];
                   3521:     }
                   3522:     for(ii=1; ii<= nlstate; ii++){
                   3523:       ps[ii][jj]=ps[ii][jj]/s1;
                   3524:     }
                   3525:   }
                   3526:   /* Transposition */
                   3527:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3528:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3529:       s1=ps[ii][jj];
                   3530:       ps[ii][jj]=ps[jj][ii];
                   3531:       ps[jj][ii]=s1;
                   3532:     }
                   3533:   }
                   3534:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3535:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3536:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3537:   /*   } */
                   3538:   /*   printf("\n "); */
                   3539:   /* } */
                   3540:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3541:   /*
                   3542:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3543:     goto end;*/
                   3544:   return ps;
1.217     brouard  3545: }
                   3546: 
                   3547: 
1.126     brouard  3548: /**************** Product of 2 matrices ******************/
                   3549: 
1.145     brouard  3550: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3551: {
                   3552:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3553:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3554:   /* in, b, out are matrice of pointers which should have been initialized 
                   3555:      before: only the contents of out is modified. The function returns
                   3556:      a pointer to pointers identical to out */
1.145     brouard  3557:   int i, j, k;
1.126     brouard  3558:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3559:     for(k=ncolol; k<=ncoloh; k++){
                   3560:       out[i][k]=0.;
                   3561:       for(j=ncl; j<=nch; j++)
                   3562:        out[i][k] +=in[i][j]*b[j][k];
                   3563:     }
1.126     brouard  3564:   return out;
                   3565: }
                   3566: 
                   3567: 
                   3568: /************* Higher Matrix Product ***************/
                   3569: 
1.235     brouard  3570: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
1.126     brouard  3571: {
1.336     brouard  3572:   /* Already optimized with precov.
                   3573:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
1.126     brouard  3574:      'nhstepm*hstepm*stepm' months (i.e. until
                   3575:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3576:      nhstepm*hstepm matrices. 
                   3577:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3578:      (typically every 2 years instead of every month which is too big 
                   3579:      for the memory).
                   3580:      Model is determined by parameters x and covariates have to be 
                   3581:      included manually here. 
                   3582: 
                   3583:      */
                   3584: 
1.330     brouard  3585:   int i, j, d, h, k, k1;
1.131     brouard  3586:   double **out, cov[NCOVMAX+1];
1.126     brouard  3587:   double **newm;
1.187     brouard  3588:   double agexact;
1.214     brouard  3589:   double agebegin, ageend;
1.126     brouard  3590: 
                   3591:   /* Hstepm could be zero and should return the unit matrix */
                   3592:   for (i=1;i<=nlstate+ndeath;i++)
                   3593:     for (j=1;j<=nlstate+ndeath;j++){
                   3594:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3595:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3596:     }
                   3597:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3598:   for(h=1; h <=nhstepm; h++){
                   3599:     for(d=1; d <=hstepm; d++){
                   3600:       newm=savm;
                   3601:       /* Covariates have to be included here again */
                   3602:       cov[1]=1.;
1.214     brouard  3603:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3604:       cov[2]=agexact;
1.319     brouard  3605:       if(nagesqr==1){
1.227     brouard  3606:        cov[3]= agexact*agexact;
1.319     brouard  3607:       }
1.330     brouard  3608:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3609:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3610:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3611:        if(Typevar[k1]==1){ /* A product with age */
                   3612:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3613:        }else{
                   3614:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3615:        }
                   3616:       }/* End of loop on model equation */
                   3617:        /* Old code */ 
                   3618: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3619: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3620: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3621: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3622: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3623: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3624: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3625: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3626: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3627: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3628: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3629: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3630: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3631: /*       /\* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,TnsdVar[TvarsD[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,TnsdVar[TvarsD[k]])); *\/ */
                   3632: /*       printf("hpxij Dummy combi=%d k1=%d Tvar[%d]=V%d cov[2+%d+%d]=%lf resultmodel[nres][%d]=%d nres/nresult=%d/%d \n",ij,k1,k1, Tvar[k1],nagesqr,k1,cov[2+nagesqr+k1],k1,resultmodel[nres][k1],nres,nresult); */
                   3633: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3634: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3635: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3636: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3637: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3638: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3639: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3640: /*       printf("hPxij Quantitative k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]); */
                   3641: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3642: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3643: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3644: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3645: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3646: /*       printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d TinvDoQresult[nres=%d][%d]=%.f age=%.2f,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],nres,TinvDoQresult[nres][Tvar[k1]],cov[2],nagesqr,k1,cov[2+nagesqr+k1]); */
                   3647: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3648: 
                   3649: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3650: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3651: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3652: /*       /\* *\/ */
1.330     brouard  3653: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3654: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3655: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3656: /* /\*cptcovage=2                   1               2      *\/ */
                   3657: /* /\*Tage[k]=                      5               8      *\/  */
                   3658: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3659: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3660: /*       printf("QhPxij Quant with age k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]); */
                   3661: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3662: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3663: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3664: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3665: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3666: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3667: /*       /\*   printf("hPxij Age combi=%d k=%d cptcovage=%d Tage[%d]=%d Tvar[Tage[%d]]=V%d nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]]])]=%d nres=%d\n",ij,k,cptcovage,k,Tage[k],k,Tvar[Tage[k]], nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]])],nres); *\/ */
                   3668: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3669: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3670: /*       /\* } *\/ */
                   3671: /*       /\* printf("hPxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
                   3672: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3673: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3674: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3675: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3676: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3677: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3678: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3679: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3680: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3681:          
1.332     brouard  3682: /*       /\* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]=%d nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]=%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2],nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])],nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]); *\/ */
                   3683: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3684: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3685: /*       printf("hPxij Prod ij=%d k1=%d  cov[2+%d+%d]=%.5f Tvard[%d][1]=V%d * Tvard[%d][2]=V%d ; TinvDoQresult[nres][Tvardk[k1][1]]=%.4f * TinvDoQresult[nres][Tvardk[k1][1]]=%.4f\n",ij,k1,nagesqr,k1,cov[2+nagesqr+k1],k1,Tvardk[k1][1], k1,Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]); */
                   3686: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3687: 
                   3688: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3689: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3690: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3691: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3692: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])]; *\/ */
                   3693: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3694: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3695: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3696: /*       /\*   } *\/ */
                   3697: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3698: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3699: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3700: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3701: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3702: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3703: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3704: /*       /\*   } *\/ */
                   3705: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3706: /*     }/\*end of products *\/ */
                   3707:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3708:       /* for (k=1; k<=cptcovn;k++)  */
                   3709:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3710:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3711:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3712:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3713:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3714:       
                   3715:       
1.126     brouard  3716:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3717:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3718:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3719:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3720:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3721:       /* if((int)age == 70){ */
                   3722:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3723:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3724:       /*         printf("%d pmmij ",i); */
                   3725:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3726:       /*           printf("%f ",pmmij[i][j]); */
                   3727:       /*         } */
                   3728:       /*         printf(" oldm "); */
                   3729:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3730:       /*           printf("%f ",oldm[i][j]); */
                   3731:       /*         } */
                   3732:       /*         printf("\n"); */
                   3733:       /*       } */
                   3734:       /* } */
1.126     brouard  3735:       savm=oldm;
                   3736:       oldm=newm;
                   3737:     }
                   3738:     for(i=1; i<=nlstate+ndeath; i++)
                   3739:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3740:        po[i][j][h]=newm[i][j];
                   3741:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3742:       }
1.128     brouard  3743:     /*printf("h=%d ",h);*/
1.126     brouard  3744:   } /* end h */
1.267     brouard  3745:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3746:   return po;
                   3747: }
                   3748: 
1.217     brouard  3749: /************* Higher Back Matrix Product ***************/
1.218     brouard  3750: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
1.267     brouard  3751: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij, int nres )
1.217     brouard  3752: {
1.332     brouard  3753:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3754:      computes the transition matrix starting at age 'age' over
1.217     brouard  3755:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3756:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3757:      nhstepm*hstepm matrices.
                   3758:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3759:      (typically every 2 years instead of every month which is too big
1.217     brouard  3760:      for the memory).
1.218     brouard  3761:      Model is determined by parameters x and covariates have to be
1.266     brouard  3762:      included manually here. Then we use a call to bmij(x and cov)
                   3763:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3764:   */
1.217     brouard  3765: 
1.332     brouard  3766:   int i, j, d, h, k, k1;
1.266     brouard  3767:   double **out, cov[NCOVMAX+1], **bmij();
                   3768:   double **newm, ***newmm;
1.217     brouard  3769:   double agexact;
                   3770:   double agebegin, ageend;
1.222     brouard  3771:   double **oldm, **savm;
1.217     brouard  3772: 
1.266     brouard  3773:   newmm=po; /* To be saved */
                   3774:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3775:   /* Hstepm could be zero and should return the unit matrix */
                   3776:   for (i=1;i<=nlstate+ndeath;i++)
                   3777:     for (j=1;j<=nlstate+ndeath;j++){
                   3778:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3779:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3780:     }
                   3781:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3782:   for(h=1; h <=nhstepm; h++){
                   3783:     for(d=1; d <=hstepm; d++){
                   3784:       newm=savm;
                   3785:       /* Covariates have to be included here again */
                   3786:       cov[1]=1.;
1.271     brouard  3787:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3788:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3789:         /* Debug */
                   3790:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3791:       cov[2]=agexact;
1.332     brouard  3792:       if(nagesqr==1){
1.222     brouard  3793:        cov[3]= agexact*agexact;
1.332     brouard  3794:       }
                   3795:       /** New code */
                   3796:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3797:        if(Typevar[k1]==1){ /* A product with age */
                   3798:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3799:        }else{
1.332     brouard  3800:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3801:        }
1.332     brouard  3802:       }/* End of loop on model equation */
                   3803:       /** End of new code */
                   3804:   /** This was old code */
                   3805:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3806:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3807:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3808:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3809:       /*   /\* printf("hbxij Dummy agexact=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agexact,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
                   3810:       /* } */
                   3811:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3812:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3813:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3814:       /*       /\* printf("hPxij Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); *\/ */
                   3815:       /* } */
                   3816:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3817:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3818:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3819:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3820:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3821:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3822:       /*       } */
                   3823:       /*       /\* printf("hBxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
                   3824:       /* } */
                   3825:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3826:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3827:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3828:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3829:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3830:       /*         }else{ */
                   3831:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3832:       /*         } */
                   3833:       /*       }else{ */
                   3834:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3835:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3836:       /*         }else{ */
                   3837:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3838:       /*         } */
                   3839:       /*       } */
                   3840:       /* }                      */
                   3841:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3842:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3843: /** End of old code */
                   3844:       
1.218     brouard  3845:       /* Careful transposed matrix */
1.266     brouard  3846:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3847:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3848:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3849:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3850:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3851:       /* if((int)age == 70){ */
                   3852:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3853:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3854:       /*         printf("%d pmmij ",i); */
                   3855:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3856:       /*           printf("%f ",pmmij[i][j]); */
                   3857:       /*         } */
                   3858:       /*         printf(" oldm "); */
                   3859:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3860:       /*           printf("%f ",oldm[i][j]); */
                   3861:       /*         } */
                   3862:       /*         printf("\n"); */
                   3863:       /*       } */
                   3864:       /* } */
                   3865:       savm=oldm;
                   3866:       oldm=newm;
                   3867:     }
                   3868:     for(i=1; i<=nlstate+ndeath; i++)
                   3869:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3870:        po[i][j][h]=newm[i][j];
1.268     brouard  3871:        /* if(h==nhstepm) */
                   3872:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3873:       }
1.268     brouard  3874:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3875:   } /* end h */
1.268     brouard  3876:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3877:   return po;
                   3878: }
                   3879: 
                   3880: 
1.162     brouard  3881: #ifdef NLOPT
                   3882:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3883:   double fret;
                   3884:   double *xt;
                   3885:   int j;
                   3886:   myfunc_data *d2 = (myfunc_data *) pd;
                   3887: /* xt = (p1-1); */
                   3888:   xt=vector(1,n); 
                   3889:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3890: 
                   3891:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3892:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3893:   printf("Function = %.12lf ",fret);
                   3894:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3895:   printf("\n");
                   3896:  free_vector(xt,1,n);
                   3897:   return fret;
                   3898: }
                   3899: #endif
1.126     brouard  3900: 
                   3901: /*************** log-likelihood *************/
                   3902: double func( double *x)
                   3903: {
1.336     brouard  3904:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3905:   int ioffset=0;
1.339     brouard  3906:   int ipos=0,iposold=0,ncovv=0;
                   3907: 
1.340     brouard  3908:   double cotvarv, cotvarvold;
1.226     brouard  3909:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3910:   double **out;
                   3911:   double lli; /* Individual log likelihood */
                   3912:   int s1, s2;
1.228     brouard  3913:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.336     brouard  3914: 
1.226     brouard  3915:   double bbh, survp;
                   3916:   double agexact;
1.336     brouard  3917:   double agebegin, ageend;
1.226     brouard  3918:   /*extern weight */
                   3919:   /* We are differentiating ll according to initial status */
                   3920:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3921:   /*for(i=1;i<imx;i++) 
                   3922:     printf(" %d\n",s[4][i]);
                   3923:   */
1.162     brouard  3924: 
1.226     brouard  3925:   ++countcallfunc;
1.162     brouard  3926: 
1.226     brouard  3927:   cov[1]=1.;
1.126     brouard  3928: 
1.226     brouard  3929:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3930:   ioffset=0;
1.226     brouard  3931:   if(mle==1){
                   3932:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3933:       /* Computes the values of the ncovmodel covariates of the model
                   3934:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3935:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3936:         to be observed in j being in i according to the model.
                   3937:       */
1.243     brouard  3938:       ioffset=2+nagesqr ;
1.233     brouard  3939:    /* Fixed */
1.336     brouard  3940:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3941:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3942:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3943:        /*  TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
1.320     brouard  3944:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3945:        cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
1.319     brouard  3946:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3947:       }
1.226     brouard  3948:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3949:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3950:         has been calculated etc */
                   3951:       /* For an individual i, wav[i] gives the number of effective waves */
                   3952:       /* We compute the contribution to Likelihood of each effective transition
                   3953:         mw[mi][i] is real wave of the mi th effectve wave */
                   3954:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3955:         s2=s[mw[mi+1][i]][i];
1.341     brouard  3956:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
1.226     brouard  3957:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3958:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3959:       */
1.336     brouard  3960:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3961:       /* Wave varying (but not age varying) */
1.339     brouard  3962:        /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates in the model (single and product but no age )"V5+V4+V3+V4*V3+V5*age+V1*age+V1" +TvarVind 1,2,3,4(V4*V3)  Tvar[1]@7{5, 4, 3, 6, 5, 1, 1 ; 6 because the created covar is after V5 and is 6, minus 1+1, 3,2,1,4 positions in cotvar*\/ */
                   3963:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   3964:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   3965:        /* } */
1.340     brouard  3966:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   3967:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   3968:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   3969:          if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341     brouard  3970:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  3971:          }else{ /* fixed covariate */
                   3972:            cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   3973:          }
1.339     brouard  3974:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  3975:            cotvarvold=cotvarv;
                   3976:          }else{ /* A second product */
                   3977:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  3978:          }
                   3979:          iposold=ipos;
1.340     brouard  3980:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  3981:        }
1.339     brouard  3982:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
                   3983:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3984:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3985:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3986:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3987:        /*   printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
                   3988:        /* } */
                   3989:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   3990:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3991:        /*   /\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
                   3992:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   3993:        /* } */
                   3994:        /* for products of time varying to be done */
1.234     brouard  3995:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3996:          for (j=1;j<=nlstate+ndeath;j++){
                   3997:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3998:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3999:          }
1.336     brouard  4000: 
                   4001:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4002:        ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
1.234     brouard  4003:        for(d=0; d<dh[mi][i]; d++){
                   4004:          newm=savm;
                   4005:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4006:          cov[2]=agexact;
                   4007:          if(nagesqr==1)
                   4008:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4009:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  4010:            if(!FixedV[Tvar[Tage[kk]]])
                   4011:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4012:            else
1.341     brouard  4013:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.234     brouard  4014:          }
                   4015:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4016:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4017:          savm=oldm;
                   4018:          oldm=newm;
                   4019:        } /* end mult */
                   4020:        
                   4021:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4022:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4023:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4024:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4025:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4026:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4027:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4028:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4029:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4030:                                 * -stepm/2 to stepm/2 .
                   4031:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4032:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4033:                                 */
1.234     brouard  4034:        s1=s[mw[mi][i]][i];
                   4035:        s2=s[mw[mi+1][i]][i];
                   4036:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4037:        /* bias bh is positive if real duration
                   4038:         * is higher than the multiple of stepm and negative otherwise.
                   4039:         */
                   4040:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4041:        if( s2 > nlstate){ 
                   4042:          /* i.e. if s2 is a death state and if the date of death is known 
                   4043:             then the contribution to the likelihood is the probability to 
                   4044:             die between last step unit time and current  step unit time, 
                   4045:             which is also equal to probability to die before dh 
                   4046:             minus probability to die before dh-stepm . 
                   4047:             In version up to 0.92 likelihood was computed
                   4048:             as if date of death was unknown. Death was treated as any other
                   4049:             health state: the date of the interview describes the actual state
                   4050:             and not the date of a change in health state. The former idea was
                   4051:             to consider that at each interview the state was recorded
                   4052:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4053:             introduced the exact date of death then we should have modified
                   4054:             the contribution of an exact death to the likelihood. This new
                   4055:             contribution is smaller and very dependent of the step unit
                   4056:             stepm. It is no more the probability to die between last interview
                   4057:             and month of death but the probability to survive from last
                   4058:             interview up to one month before death multiplied by the
                   4059:             probability to die within a month. Thanks to Chris
                   4060:             Jackson for correcting this bug.  Former versions increased
                   4061:             mortality artificially. The bad side is that we add another loop
                   4062:             which slows down the processing. The difference can be up to 10%
                   4063:             lower mortality.
                   4064:          */
                   4065:          /* If, at the beginning of the maximization mostly, the
                   4066:             cumulative probability or probability to be dead is
                   4067:             constant (ie = 1) over time d, the difference is equal to
                   4068:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4069:             s1 at precedent wave, to be dead a month before current
                   4070:             wave is equal to probability, being at state s1 at
                   4071:             precedent wave, to be dead at mont of the current
                   4072:             wave. Then the observed probability (that this person died)
                   4073:             is null according to current estimated parameter. In fact,
                   4074:             it should be very low but not zero otherwise the log go to
                   4075:             infinity.
                   4076:          */
1.183     brouard  4077: /* #ifdef INFINITYORIGINAL */
                   4078: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4079: /* #else */
                   4080: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4081: /*         lli=log(mytinydouble); */
                   4082: /*       else */
                   4083: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4084: /* #endif */
1.226     brouard  4085:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4086:          
1.226     brouard  4087:        } else if  ( s2==-1 ) { /* alive */
                   4088:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4089:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4090:          /*survp += out[s1][j]; */
                   4091:          lli= log(survp);
                   4092:        }
1.336     brouard  4093:        /* else if  (s2==-4) {  */
                   4094:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4095:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4096:        /*   lli= log(survp);  */
                   4097:        /* }  */
                   4098:        /* else if  (s2==-5) {  */
                   4099:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4100:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4101:        /*   lli= log(survp);  */
                   4102:        /* }  */
1.226     brouard  4103:        else{
                   4104:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4105:          /*  lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
                   4106:        } 
                   4107:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4108:        /*if(lli ==000.0)*/
1.340     brouard  4109:        /* printf("num[i], i=%d, bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
1.226     brouard  4110:        ipmx +=1;
                   4111:        sw += weight[i];
                   4112:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4113:        /* if (lli < log(mytinydouble)){ */
                   4114:        /*   printf("Close to inf lli = %.10lf <  %.10lf i= %d mi= %d, s[%d][i]=%d s1=%d s2=%d\n", lli,log(mytinydouble), i, mi,mw[mi][i], s[mw[mi][i]][i], s1,s2); */
                   4115:        /*   fprintf(ficlog,"Close to inf lli = %.10lf i= %d mi= %d, s[mw[mi][i]][i]=%d\n", lli, i, mi,s[mw[mi][i]][i]); */
                   4116:        /* } */
                   4117:       } /* end of wave */
                   4118:     } /* end of individual */
                   4119:   }  else if(mle==2){
                   4120:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4121:       ioffset=2+nagesqr ;
                   4122:       for (k=1; k<=ncovf;k++)
                   4123:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4124:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4125:        for(k=1; k <= ncovv ; k++){
1.341     brouard  4126:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.319     brouard  4127:        }
1.226     brouard  4128:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4129:          for (j=1;j<=nlstate+ndeath;j++){
                   4130:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4131:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4132:          }
                   4133:        for(d=0; d<=dh[mi][i]; d++){
                   4134:          newm=savm;
                   4135:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4136:          cov[2]=agexact;
                   4137:          if(nagesqr==1)
                   4138:            cov[3]= agexact*agexact;
                   4139:          for (kk=1; kk<=cptcovage;kk++) {
                   4140:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4141:          }
                   4142:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4143:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4144:          savm=oldm;
                   4145:          oldm=newm;
                   4146:        } /* end mult */
                   4147:       
                   4148:        s1=s[mw[mi][i]][i];
                   4149:        s2=s[mw[mi+1][i]][i];
                   4150:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4151:        lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
                   4152:        ipmx +=1;
                   4153:        sw += weight[i];
                   4154:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4155:       } /* end of wave */
                   4156:     } /* end of individual */
                   4157:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4158:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4159:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4160:       for(mi=1; mi<= wav[i]-1; mi++){
                   4161:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4162:          for (j=1;j<=nlstate+ndeath;j++){
                   4163:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4164:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4165:          }
                   4166:        for(d=0; d<dh[mi][i]; d++){
                   4167:          newm=savm;
                   4168:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4169:          cov[2]=agexact;
                   4170:          if(nagesqr==1)
                   4171:            cov[3]= agexact*agexact;
                   4172:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4173:            if(!FixedV[Tvar[Tage[kk]]])
                   4174:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4175:            else
1.341     brouard  4176:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.226     brouard  4177:          }
                   4178:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4179:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4180:          savm=oldm;
                   4181:          oldm=newm;
                   4182:        } /* end mult */
                   4183:       
                   4184:        s1=s[mw[mi][i]][i];
                   4185:        s2=s[mw[mi+1][i]][i];
                   4186:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4187:        lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
                   4188:        ipmx +=1;
                   4189:        sw += weight[i];
                   4190:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4191:       } /* end of wave */
                   4192:     } /* end of individual */
                   4193:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4194:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4195:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4196:       for(mi=1; mi<= wav[i]-1; mi++){
                   4197:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4198:          for (j=1;j<=nlstate+ndeath;j++){
                   4199:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4200:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4201:          }
                   4202:        for(d=0; d<dh[mi][i]; d++){
                   4203:          newm=savm;
                   4204:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4205:          cov[2]=agexact;
                   4206:          if(nagesqr==1)
                   4207:            cov[3]= agexact*agexact;
                   4208:          for (kk=1; kk<=cptcovage;kk++) {
                   4209:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4210:          }
1.126     brouard  4211:        
1.226     brouard  4212:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4213:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4214:          savm=oldm;
                   4215:          oldm=newm;
                   4216:        } /* end mult */
                   4217:       
                   4218:        s1=s[mw[mi][i]][i];
                   4219:        s2=s[mw[mi+1][i]][i];
                   4220:        if( s2 > nlstate){ 
                   4221:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4222:        } else if  ( s2==-1 ) { /* alive */
                   4223:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4224:            survp += out[s1][j];
                   4225:          lli= log(survp);
                   4226:        }else{
                   4227:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4228:        }
                   4229:        ipmx +=1;
                   4230:        sw += weight[i];
                   4231:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343   ! brouard  4232:        /* printf("num[i]=%09ld, i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.226     brouard  4233:       } /* end of wave */
                   4234:     } /* end of individual */
                   4235:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4236:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4237:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4238:       for(mi=1; mi<= wav[i]-1; mi++){
                   4239:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4240:          for (j=1;j<=nlstate+ndeath;j++){
                   4241:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4242:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4243:          }
                   4244:        for(d=0; d<dh[mi][i]; d++){
                   4245:          newm=savm;
                   4246:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4247:          cov[2]=agexact;
                   4248:          if(nagesqr==1)
                   4249:            cov[3]= agexact*agexact;
                   4250:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  4251:            if(!FixedV[Tvar[Tage[kk]]])
                   4252:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4253:            else
1.341     brouard  4254:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.226     brouard  4255:          }
1.126     brouard  4256:        
1.226     brouard  4257:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4258:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4259:          savm=oldm;
                   4260:          oldm=newm;
                   4261:        } /* end mult */
                   4262:       
                   4263:        s1=s[mw[mi][i]][i];
                   4264:        s2=s[mw[mi+1][i]][i];
                   4265:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4266:        ipmx +=1;
                   4267:        sw += weight[i];
                   4268:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4269:        /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]);*/
                   4270:       } /* end of wave */
                   4271:     } /* end of individual */
                   4272:   } /* End of if */
                   4273:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4274:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4275:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4276:   return -l;
1.126     brouard  4277: }
                   4278: 
                   4279: /*************** log-likelihood *************/
                   4280: double funcone( double *x)
                   4281: {
1.228     brouard  4282:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4283:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4284:   int ioffset=0;
1.339     brouard  4285:   int ipos=0,iposold=0,ncovv=0;
                   4286: 
1.340     brouard  4287:   double cotvarv, cotvarvold;
1.131     brouard  4288:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4289:   double **out;
                   4290:   double lli; /* Individual log likelihood */
                   4291:   double llt;
                   4292:   int s1, s2;
1.228     brouard  4293:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4294: 
1.126     brouard  4295:   double bbh, survp;
1.187     brouard  4296:   double agexact;
1.214     brouard  4297:   double agebegin, ageend;
1.126     brouard  4298:   /*extern weight */
                   4299:   /* We are differentiating ll according to initial status */
                   4300:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4301:   /*for(i=1;i<imx;i++) 
                   4302:     printf(" %d\n",s[4][i]);
                   4303:   */
                   4304:   cov[1]=1.;
                   4305: 
                   4306:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4307:   ioffset=0;
                   4308:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4309:     /* Computes the values of the ncovmodel covariates of the model
                   4310:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4311:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4312:        to be observed in j being in i according to the model.
                   4313:     */
1.243     brouard  4314:     /* ioffset=2+nagesqr+cptcovage; */
                   4315:     ioffset=2+nagesqr;
1.232     brouard  4316:     /* Fixed */
1.224     brouard  4317:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4318:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4319:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  4320:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4321:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4322:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4323:       cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
1.232     brouard  4324: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4325: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4326: /*    cov[2+6]=covar[2][i]; V2  */
                   4327: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4328: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4329: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4330: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4331: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4332: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4333:     }
1.336     brouard  4334:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4335:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4336:         has been calculated etc */
                   4337:       /* For an individual i, wav[i] gives the number of effective waves */
                   4338:       /* We compute the contribution to Likelihood of each effective transition
                   4339:         mw[mi][i] is real wave of the mi th effectve wave */
                   4340:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4341:         s2=s[mw[mi+1][i]][i];
1.341     brouard  4342:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  4343:       */
                   4344:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4345:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4346:     /*   cov[++ioffset]=coqvar[TvarFQ[k]][i];/\* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V2 and V1*V2 is fixed (k=6 and 7?)*\/ */
                   4347:     /* } */
1.231     brouard  4348:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4349:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4350:     /* } */
1.225     brouard  4351:     
1.233     brouard  4352: 
                   4353:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  4354:       /* Wave varying (but not age varying) *//* V1+V3+age*V1+age*V3+V1*V3 with V4 tv and V5 tvq k= 1 to 5 and extra at V(5+1)=6 for V1*V3 */
                   4355:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4356:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4357:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4358:       /* } */
                   4359:       
                   4360:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4361:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4362:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4363:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4364:       /* We need the position of the time varying or product in the model */
                   4365:       /* TvarVVind={2,5,5}, for V3 at position 2 and then the product V1*V3 is decomposed into V1 and V3 but at same position 5 */            
                   4366:       /* TvarVV gives the variable name */
1.340     brouard  4367:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4368:       *      k=         1   2     3     4         5        6        7       8        9
                   4369:       *  varying            1     2                                 3       4        5
                   4370:       *  ncovv              1     2                                3 4     5 6      7 8
1.343   ! brouard  4371:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  4372:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4373:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4374:       */
                   4375:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4376:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4377:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4378:        if(TvarFind[itv]==0){ /* Not a fixed covariate */
1.341     brouard  4379:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.340     brouard  4380:        }else{ /* fixed covariate */
                   4381:          cotvarv=covar[Tvar[TvarFind[itv]]][i];
                   4382:        }
1.339     brouard  4383:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  4384:          cotvarvold=cotvarv;
                   4385:        }else{ /* A second product */
                   4386:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  4387:        }
                   4388:        iposold=ipos;
1.340     brouard  4389:        cov[ioffset+ipos]=cotvarv;
1.339     brouard  4390:        /* For products */
                   4391:       }
                   4392:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4393:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4394:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4395:       /*       /\*           1  2   3      4      5                         *\/ */
                   4396:       /*       /\*itv           1                                           *\/ */
                   4397:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4398:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4399:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4400:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4401:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4402:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4403:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4404:       /*       /\* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][itv][i]=%f\n", i, mi, itv, TvarVDind[itv],cotvar[mw[mi][i]][itv][i]); *\/ */
                   4405:       /* } */
1.232     brouard  4406:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4407:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4408:       /*       /\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
                   4409:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4410:       /* } */
1.126     brouard  4411:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4412:        for (j=1;j<=nlstate+ndeath;j++){
                   4413:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4414:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4415:        }
1.214     brouard  4416:       
                   4417:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4418:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4419:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4420:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4421:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4422:          and mw[mi+1][i]. dh depends on stepm.*/
                   4423:        newm=savm;
1.247     brouard  4424:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4425:        cov[2]=agexact;
                   4426:        if(nagesqr==1)
                   4427:          cov[3]= agexact*agexact;
                   4428:        for (kk=1; kk<=cptcovage;kk++) {
                   4429:          if(!FixedV[Tvar[Tage[kk]]])
                   4430:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4431:          else
1.341     brouard  4432:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.242     brouard  4433:        }
                   4434:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4435:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4436:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4437:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4438:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4439:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4440:        savm=oldm;
                   4441:        oldm=newm;
1.126     brouard  4442:       } /* end mult */
1.336     brouard  4443:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4444:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4445:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4446:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4447:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4448:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4449:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4450:         * probability in order to take into account the bias as a fraction of the way
                   4451:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4452:                                 * -stepm/2 to stepm/2 .
                   4453:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4454:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4455:                                 */
1.126     brouard  4456:       s1=s[mw[mi][i]][i];
                   4457:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4458:       /* if(s2==-1){ */
1.268     brouard  4459:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4460:       /*       /\* exit(1); *\/ */
                   4461:       /* } */
1.126     brouard  4462:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4463:       /* bias is positive if real duration
                   4464:        * is higher than the multiple of stepm and negative otherwise.
                   4465:        */
                   4466:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4467:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4468:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4469:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4470:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4471:        lli= log(survp);
1.126     brouard  4472:       }else if (mle==1){
1.242     brouard  4473:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4474:       } else if(mle==2){
1.242     brouard  4475:        lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
1.126     brouard  4476:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4477:        lli= (savm[s1][s2]>(double)1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
1.126     brouard  4478:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4479:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4480:       } else{  /* mle=0 back to 1 */
1.242     brouard  4481:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4482:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4483:       } /* End of if */
                   4484:       ipmx +=1;
                   4485:       sw += weight[i];
                   4486:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  4487:       /* Printing covariates values for each contribution for checking */
1.343   ! brouard  4488:       /* printf("num[i]=%09ld, i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  4489:       if(globpr){
1.246     brouard  4490:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4491:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4492:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.268     brouard  4493:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343   ! brouard  4494:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
        !          4495:        /* %11.6f %11.6f %11.6f ", \ */
        !          4496:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
        !          4497:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4498:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4499:          llt +=ll[k]*gipmx/gsw;
                   4500:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4501:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4502:        }
1.343   ! brouard  4503:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  4504:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  4505:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343   ! brouard  4506:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
        !          4507:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
        !          4508:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
        !          4509:        }
        !          4510:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
        !          4511:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4512:          if(ipos!=iposold){ /* Not a product or first of a product */
        !          4513:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
        !          4514:            /* printf(" %g",cov[ioffset+ipos]); */
        !          4515:          }else{
        !          4516:            fprintf(ficresilk,"*");
        !          4517:            /* printf("*"); */
1.342     brouard  4518:          }
1.343   ! brouard  4519:          iposold=ipos;
        !          4520:        }
        !          4521:        for (kk=1; kk<=cptcovage;kk++) {
        !          4522:          if(!FixedV[Tvar[Tage[kk]]]){
        !          4523:            fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]);
        !          4524:            /* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); */
        !          4525:          }else{
        !          4526:            fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
        !          4527:            /* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
1.342     brouard  4528:          }
1.343   ! brouard  4529:        }
        !          4530:        /* printf("\n"); */
1.342     brouard  4531:        /* } /\*  End debugILK *\/ */
                   4532:        fprintf(ficresilk,"\n");
                   4533:       } /* End if globpr */
1.335     brouard  4534:     } /* end of wave */
                   4535:   } /* end of individual */
                   4536:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4537: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4538:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4539:   if(globpr==0){ /* First time we count the contributions and weights */
                   4540:     gipmx=ipmx;
                   4541:     gsw=sw;
                   4542:   }
1.343   ! brouard  4543:   return -l;
1.126     brouard  4544: }
                   4545: 
                   4546: 
                   4547: /*************** function likelione ***********/
1.292     brouard  4548: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4549: {
                   4550:   /* This routine should help understanding what is done with 
                   4551:      the selection of individuals/waves and
                   4552:      to check the exact contribution to the likelihood.
                   4553:      Plotting could be done.
1.342     brouard  4554:   */
                   4555:   void pstamp(FILE *ficres);
1.343   ! brouard  4556:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  4557: 
                   4558:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4559:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4560:     strcat(fileresilk,fileresu);
1.126     brouard  4561:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4562:       printf("Problem with resultfile: %s\n", fileresilk);
                   4563:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4564:     }
1.342     brouard  4565:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  4566:     fprintf(ficresilk, "#individual(line's_record) count ageb ageend s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
                   4567:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4568:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4569:     for(k=1; k<=nlstate; k++) 
                   4570:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  4571:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   4572: 
                   4573:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4574:       for(kf=1;kf <= ncovf; kf++){
                   4575:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   4576:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   4577:       }
                   4578:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343   ! brouard  4579:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  4580:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4581:          /* printf(" %d",ipos); */
                   4582:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   4583:        }else{
                   4584:          /* printf("*"); */
                   4585:          fprintf(ficresilk,"*");
1.343   ! brouard  4586:        }
1.342     brouard  4587:        iposold=ipos;
                   4588:       }
                   4589:       for (kk=1; kk<=cptcovage;kk++) {
                   4590:        if(!FixedV[Tvar[Tage[kk]]]){
                   4591:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   4592:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   4593:        }else{
                   4594:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4595:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   4596:        }
                   4597:       }
                   4598:     /* } /\* End if debugILK *\/ */
                   4599:     /* printf("\n"); */
                   4600:     fprintf(ficresilk,"\n");
                   4601:   } /* End glogpri */
1.126     brouard  4602: 
1.292     brouard  4603:   *fretone=(*func)(p);
1.126     brouard  4604:   if(*globpri !=0){
                   4605:     fclose(ficresilk);
1.205     brouard  4606:     if (mle ==0)
                   4607:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4608:     else if(mle >=1)
                   4609:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4610:     fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1.274     brouard  4611:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4612:       
1.207     brouard  4613:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.343   ! brouard  4614: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4615:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343   ! brouard  4616: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
        !          4617:     
        !          4618:     for (k=1; k<= nlstate ; k++) {
        !          4619:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br>\n \
        !          4620: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
        !          4621:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
        !          4622:        /* kvar=Tvar[TvarFind[kf]]; */ /* variable */
        !          4623:        fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
        !          4624: <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
        !          4625:       }
        !          4626:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
        !          4627:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
        !          4628:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
        !          4629:        /* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
        !          4630:        if(ipos!=iposold){ /* Not a product or first of a product */
        !          4631:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
        !          4632:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
        !          4633:          if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
        !          4634:            fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored time varying dummy covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
        !          4635: <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar);
        !          4636:          } /* End only for dummies time varying (single?) */
        !          4637:        }else{ /* Useless product */
        !          4638:          /* printf("*"); */
        !          4639:          /* fprintf(ficresilk,"*"); */ 
        !          4640:        }
        !          4641:        iposold=ipos;
        !          4642:       } /* For each time varying covariate */
        !          4643:     } /* End loop on states */
        !          4644: 
        !          4645: /*     if(debugILK){ */
        !          4646: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
        !          4647: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
        !          4648: /*     for (k=1; k<= nlstate ; k++) { */
        !          4649: /*       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
        !          4650: /* <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]); */
        !          4651: /*     } */
        !          4652: /*       } */
        !          4653: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
        !          4654: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
        !          4655: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
        !          4656: /*     /\* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); *\/ */
        !          4657: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
        !          4658: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
        !          4659: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
        !          4660: /*       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /\* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  *\/ */
        !          4661: /*         for (k=1; k<= nlstate ; k++) { */
        !          4662: /*           fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
        !          4663: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
        !          4664: /*         } /\* End state *\/ */
        !          4665: /*       } /\* End only for dummies time varying (single?) *\/ */
        !          4666: /*     }else{ /\* Useless product *\/ */
        !          4667: /*       /\* printf("*"); *\/ */
        !          4668: /*       /\* fprintf(ficresilk,"*"); *\/  */
        !          4669: /*     } */
        !          4670: /*     iposold=ipos; */
        !          4671: /*       } /\* For each time varying covariate *\/ */
        !          4672: /*     }/\* End debugILK *\/ */
1.207     brouard  4673:     fflush(fichtm);
1.343   ! brouard  4674:   }/* End globpri */
1.126     brouard  4675:   return;
                   4676: }
                   4677: 
                   4678: 
                   4679: /*********** Maximum Likelihood Estimation ***************/
                   4680: 
                   4681: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4682: {
1.319     brouard  4683:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4684:   double **xi;
                   4685:   double fret;
                   4686:   double fretone; /* Only one call to likelihood */
                   4687:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4688: 
                   4689: #ifdef NLOPT
                   4690:   int creturn;
                   4691:   nlopt_opt opt;
                   4692:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4693:   double *lb;
                   4694:   double minf; /* the minimum objective value, upon return */
                   4695:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4696:   myfunc_data dinst, *d = &dinst;
                   4697: #endif
                   4698: 
                   4699: 
1.126     brouard  4700:   xi=matrix(1,npar,1,npar);
                   4701:   for (i=1;i<=npar;i++)
                   4702:     for (j=1;j<=npar;j++)
                   4703:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4704:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4705:   strcpy(filerespow,"POW_"); 
1.126     brouard  4706:   strcat(filerespow,fileres);
                   4707:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4708:     printf("Problem with resultfile: %s\n", filerespow);
                   4709:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4710:   }
                   4711:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4712:   for (i=1;i<=nlstate;i++)
                   4713:     for(j=1;j<=nlstate+ndeath;j++)
                   4714:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4715:   fprintf(ficrespow,"\n");
1.162     brouard  4716: #ifdef POWELL
1.319     brouard  4717: #ifdef LINMINORIGINAL
                   4718: #else /* LINMINORIGINAL */
                   4719:   
                   4720:   flatdir=ivector(1,npar); 
                   4721:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4722: #endif /*LINMINORIGINAL */
                   4723: 
                   4724: #ifdef FLATSUP
                   4725:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4726:   /* reorganizing p by suppressing flat directions */
                   4727:   for(i=1, jk=1; i <=nlstate; i++){
                   4728:     for(k=1; k <=(nlstate+ndeath); k++){
                   4729:       if (k != i) {
                   4730:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4731:         if(flatdir[jk]==1){
                   4732:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4733:         }
                   4734:         for(j=1; j <=ncovmodel; j++){
                   4735:           printf("%12.7f ",p[jk]);
                   4736:           jk++; 
                   4737:         }
                   4738:         printf("\n");
                   4739:       }
                   4740:     }
                   4741:   }
                   4742: /* skipping */
                   4743:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4744:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4745:     for(k=1; k <=(nlstate+ndeath); k++){
                   4746:       if (k != i) {
                   4747:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4748:         if(flatdir[jk]==1){
                   4749:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4750:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4751:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4752:             /*q[jjk]=p[jk];*/
                   4753:           }
                   4754:         }else{
                   4755:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4756:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4757:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4758:             /*q[jjk]=p[jk];*/
                   4759:           }
                   4760:         }
                   4761:         printf("\n");
                   4762:       }
                   4763:       fflush(stdout);
                   4764:     }
                   4765:   }
                   4766:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4767: #else  /* FLATSUP */
1.126     brouard  4768:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4769: #endif  /* FLATSUP */
                   4770: 
                   4771: #ifdef LINMINORIGINAL
                   4772: #else
                   4773:       free_ivector(flatdir,1,npar); 
                   4774: #endif  /* LINMINORIGINAL*/
                   4775: #endif /* POWELL */
1.126     brouard  4776: 
1.162     brouard  4777: #ifdef NLOPT
                   4778: #ifdef NEWUOA
                   4779:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4780: #else
                   4781:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4782: #endif
                   4783:   lb=vector(0,npar-1);
                   4784:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4785:   nlopt_set_lower_bounds(opt, lb);
                   4786:   nlopt_set_initial_step1(opt, 0.1);
                   4787:   
                   4788:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4789:   d->function = func;
                   4790:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4791:   nlopt_set_min_objective(opt, myfunc, d);
                   4792:   nlopt_set_xtol_rel(opt, ftol);
                   4793:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4794:     printf("nlopt failed! %d\n",creturn); 
                   4795:   }
                   4796:   else {
                   4797:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4798:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4799:     iter=1; /* not equal */
                   4800:   }
                   4801:   nlopt_destroy(opt);
                   4802: #endif
1.319     brouard  4803: #ifdef FLATSUP
                   4804:   /* npared = npar -flatd/ncovmodel; */
                   4805:   /* xired= matrix(1,npared,1,npared); */
                   4806:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4807:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4808:   /* free_matrix(xire,1,npared,1,npared); */
                   4809: #else  /* FLATSUP */
                   4810: #endif /* FLATSUP */
1.126     brouard  4811:   free_matrix(xi,1,npar,1,npar);
                   4812:   fclose(ficrespow);
1.203     brouard  4813:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4814:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4815:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4816: 
                   4817: }
                   4818: 
                   4819: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4820: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4821: {
                   4822:   double  **a,**y,*x,pd;
1.203     brouard  4823:   /* double **hess; */
1.164     brouard  4824:   int i, j;
1.126     brouard  4825:   int *indx;
                   4826: 
                   4827:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4828:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4829:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4830:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4831:   double gompertz(double p[]);
1.203     brouard  4832:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4833: 
                   4834:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4835:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4836:   for (i=1;i<=npar;i++){
1.203     brouard  4837:     printf("%d-",i);fflush(stdout);
                   4838:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4839:    
                   4840:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4841:     
                   4842:     /*  printf(" %f ",p[i]);
                   4843:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4844:   }
                   4845:   
                   4846:   for (i=1;i<=npar;i++) {
                   4847:     for (j=1;j<=npar;j++)  {
                   4848:       if (j>i) { 
1.203     brouard  4849:        printf(".%d-%d",i,j);fflush(stdout);
                   4850:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4851:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4852:        
                   4853:        hess[j][i]=hess[i][j];    
                   4854:        /*printf(" %lf ",hess[i][j]);*/
                   4855:       }
                   4856:     }
                   4857:   }
                   4858:   printf("\n");
                   4859:   fprintf(ficlog,"\n");
                   4860: 
                   4861:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4862:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4863:   
                   4864:   a=matrix(1,npar,1,npar);
                   4865:   y=matrix(1,npar,1,npar);
                   4866:   x=vector(1,npar);
                   4867:   indx=ivector(1,npar);
                   4868:   for (i=1;i<=npar;i++)
                   4869:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4870:   ludcmp(a,npar,indx,&pd);
                   4871: 
                   4872:   for (j=1;j<=npar;j++) {
                   4873:     for (i=1;i<=npar;i++) x[i]=0;
                   4874:     x[j]=1;
                   4875:     lubksb(a,npar,indx,x);
                   4876:     for (i=1;i<=npar;i++){ 
                   4877:       matcov[i][j]=x[i];
                   4878:     }
                   4879:   }
                   4880: 
                   4881:   printf("\n#Hessian matrix#\n");
                   4882:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4883:   for (i=1;i<=npar;i++) { 
                   4884:     for (j=1;j<=npar;j++) { 
1.203     brouard  4885:       printf("%.6e ",hess[i][j]);
                   4886:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4887:     }
                   4888:     printf("\n");
                   4889:     fprintf(ficlog,"\n");
                   4890:   }
                   4891: 
1.203     brouard  4892:   /* printf("\n#Covariance matrix#\n"); */
                   4893:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4894:   /* for (i=1;i<=npar;i++) {  */
                   4895:   /*   for (j=1;j<=npar;j++) {  */
                   4896:   /*     printf("%.6e ",matcov[i][j]); */
                   4897:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4898:   /*   } */
                   4899:   /*   printf("\n"); */
                   4900:   /*   fprintf(ficlog,"\n"); */
                   4901:   /* } */
                   4902: 
1.126     brouard  4903:   /* Recompute Inverse */
1.203     brouard  4904:   /* for (i=1;i<=npar;i++) */
                   4905:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4906:   /* ludcmp(a,npar,indx,&pd); */
                   4907: 
                   4908:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4909: 
                   4910:   /* for (j=1;j<=npar;j++) { */
                   4911:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4912:   /*   x[j]=1; */
                   4913:   /*   lubksb(a,npar,indx,x); */
                   4914:   /*   for (i=1;i<=npar;i++){  */
                   4915:   /*     y[i][j]=x[i]; */
                   4916:   /*     printf("%.3e ",y[i][j]); */
                   4917:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4918:   /*   } */
                   4919:   /*   printf("\n"); */
                   4920:   /*   fprintf(ficlog,"\n"); */
                   4921:   /* } */
                   4922: 
                   4923:   /* Verifying the inverse matrix */
                   4924: #ifdef DEBUGHESS
                   4925:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4926: 
1.203     brouard  4927:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4928:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4929: 
                   4930:   for (j=1;j<=npar;j++) {
                   4931:     for (i=1;i<=npar;i++){ 
1.203     brouard  4932:       printf("%.2f ",y[i][j]);
                   4933:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4934:     }
                   4935:     printf("\n");
                   4936:     fprintf(ficlog,"\n");
                   4937:   }
1.203     brouard  4938: #endif
1.126     brouard  4939: 
                   4940:   free_matrix(a,1,npar,1,npar);
                   4941:   free_matrix(y,1,npar,1,npar);
                   4942:   free_vector(x,1,npar);
                   4943:   free_ivector(indx,1,npar);
1.203     brouard  4944:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4945: 
                   4946: 
                   4947: }
                   4948: 
                   4949: /*************** hessian matrix ****************/
                   4950: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4951: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4952:   int i;
                   4953:   int l=1, lmax=20;
1.203     brouard  4954:   double k1,k2, res, fx;
1.132     brouard  4955:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4956:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4957:   int k=0,kmax=10;
                   4958:   double l1;
                   4959: 
                   4960:   fx=func(x);
                   4961:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4962:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4963:     l1=pow(10,l);
                   4964:     delts=delt;
                   4965:     for(k=1 ; k <kmax; k=k+1){
                   4966:       delt = delta*(l1*k);
                   4967:       p2[theta]=x[theta] +delt;
1.145     brouard  4968:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4969:       p2[theta]=x[theta]-delt;
                   4970:       k2=func(p2)-fx;
                   4971:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4972:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4973:       
1.203     brouard  4974: #ifdef DEBUGHESSII
1.126     brouard  4975:       printf("%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
                   4976:       fprintf(ficlog,"%d %d k1=%.12e k2=%.12e xk1=%.12e xk2=%.12e delt=%.12e res=%.12e l=%d k=%d,fx=%.12e\n",theta,theta,k1,k2,x[theta]+delt,x[theta]-delt,delt,res, l, k,fx);
                   4977: #endif
                   4978:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4979:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4980:        k=kmax;
                   4981:       }
                   4982:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4983:        k=kmax; l=lmax*10;
1.126     brouard  4984:       }
                   4985:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4986:        delts=delt;
                   4987:       }
1.203     brouard  4988:     } /* End loop k */
1.126     brouard  4989:   }
                   4990:   delti[theta]=delts;
                   4991:   return res; 
                   4992:   
                   4993: }
                   4994: 
1.203     brouard  4995: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4996: {
                   4997:   int i;
1.164     brouard  4998:   int l=1, lmax=20;
1.126     brouard  4999:   double k1,k2,k3,k4,res,fx;
1.132     brouard  5000:   double p2[MAXPARM+1];
1.203     brouard  5001:   int k, kmax=1;
                   5002:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  5003: 
                   5004:   int firstime=0;
1.203     brouard  5005:   
1.126     brouard  5006:   fx=func(x);
1.203     brouard  5007:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  5008:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  5009:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5010:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5011:     k1=func(p2)-fx;
                   5012:   
1.203     brouard  5013:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5014:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5015:     k2=func(p2)-fx;
                   5016:   
1.203     brouard  5017:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5018:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  5019:     k3=func(p2)-fx;
                   5020:   
1.203     brouard  5021:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5022:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  5023:     k4=func(p2)-fx;
1.203     brouard  5024:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5025:     if(k1*k2*k3*k4 <0.){
1.208     brouard  5026:       firstime=1;
1.203     brouard  5027:       kmax=kmax+10;
1.208     brouard  5028:     }
                   5029:     if(kmax >=10 || firstime ==1){
1.246     brouard  5030:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
                   5031:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  5032:       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti*k=%.12e deltj*k=%.12e, xi-de*k=%.12e xj-de*k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
                   5033:       fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti*k=%.12e deltj*k=%.12e, xi-de*k=%.12e xj-de*k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
                   5034:     }
                   5035: #ifdef DEBUGHESSIJ
                   5036:     v1=hess[thetai][thetai];
                   5037:     v2=hess[thetaj][thetaj];
                   5038:     cv12=res;
                   5039:     /* Computing eigen value of Hessian matrix */
                   5040:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5041:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5042:     if ((lc2 <0) || (lc1 <0) ){
                   5043:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5044:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5045:       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
                   5046:       fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
                   5047:     }
1.126     brouard  5048: #endif
                   5049:   }
                   5050:   return res;
                   5051: }
                   5052: 
1.203     brouard  5053:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5054: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5055: /* { */
                   5056: /*   int i; */
                   5057: /*   int l=1, lmax=20; */
                   5058: /*   double k1,k2,k3,k4,res,fx; */
                   5059: /*   double p2[MAXPARM+1]; */
                   5060: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5061: /*   int k=0,kmax=10; */
                   5062: /*   double l1; */
                   5063:   
                   5064: /*   fx=func(x); */
                   5065: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5066: /*     l1=pow(10,l); */
                   5067: /*     delts=delt; */
                   5068: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5069: /*       delt = delti*(l1*k); */
                   5070: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5071: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5072: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5073: /*       k1=func(p2)-fx; */
                   5074:       
                   5075: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5076: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5077: /*       k2=func(p2)-fx; */
                   5078:       
                   5079: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5080: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5081: /*       k3=func(p2)-fx; */
                   5082:       
                   5083: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5084: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5085: /*       k4=func(p2)-fx; */
                   5086: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5087: /* #ifdef DEBUGHESSIJ */
                   5088: /*       printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4); */
                   5089: /*       fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e  res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4); */
                   5090: /* #endif */
                   5091: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5092: /*     k=kmax; */
                   5093: /*       } */
                   5094: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5095: /*     k=kmax; l=lmax*10; */
                   5096: /*       } */
                   5097: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5098: /*     delts=delt; */
                   5099: /*       } */
                   5100: /*     } /\* End loop k *\/ */
                   5101: /*   } */
                   5102: /*   delti[theta]=delts; */
                   5103: /*   return res;  */
                   5104: /* } */
                   5105: 
                   5106: 
1.126     brouard  5107: /************** Inverse of matrix **************/
                   5108: void ludcmp(double **a, int n, int *indx, double *d) 
                   5109: { 
                   5110:   int i,imax,j,k; 
                   5111:   double big,dum,sum,temp; 
                   5112:   double *vv; 
                   5113:  
                   5114:   vv=vector(1,n); 
                   5115:   *d=1.0; 
                   5116:   for (i=1;i<=n;i++) { 
                   5117:     big=0.0; 
                   5118:     for (j=1;j<=n;j++) 
                   5119:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  5120:     if (big == 0.0){
                   5121:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5122:       for (j=1;j<=n;j++) {
                   5123:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5124:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5125:       }
                   5126:       fflush(ficlog);
                   5127:       fclose(ficlog);
                   5128:       nrerror("Singular matrix in routine ludcmp"); 
                   5129:     }
1.126     brouard  5130:     vv[i]=1.0/big; 
                   5131:   } 
                   5132:   for (j=1;j<=n;j++) { 
                   5133:     for (i=1;i<j;i++) { 
                   5134:       sum=a[i][j]; 
                   5135:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5136:       a[i][j]=sum; 
                   5137:     } 
                   5138:     big=0.0; 
                   5139:     for (i=j;i<=n;i++) { 
                   5140:       sum=a[i][j]; 
                   5141:       for (k=1;k<j;k++) 
                   5142:        sum -= a[i][k]*a[k][j]; 
                   5143:       a[i][j]=sum; 
                   5144:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5145:        big=dum; 
                   5146:        imax=i; 
                   5147:       } 
                   5148:     } 
                   5149:     if (j != imax) { 
                   5150:       for (k=1;k<=n;k++) { 
                   5151:        dum=a[imax][k]; 
                   5152:        a[imax][k]=a[j][k]; 
                   5153:        a[j][k]=dum; 
                   5154:       } 
                   5155:       *d = -(*d); 
                   5156:       vv[imax]=vv[j]; 
                   5157:     } 
                   5158:     indx[j]=imax; 
                   5159:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5160:     if (j != n) { 
                   5161:       dum=1.0/(a[j][j]); 
                   5162:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5163:     } 
                   5164:   } 
                   5165:   free_vector(vv,1,n);  /* Doesn't work */
                   5166: ;
                   5167: } 
                   5168: 
                   5169: void lubksb(double **a, int n, int *indx, double b[]) 
                   5170: { 
                   5171:   int i,ii=0,ip,j; 
                   5172:   double sum; 
                   5173:  
                   5174:   for (i=1;i<=n;i++) { 
                   5175:     ip=indx[i]; 
                   5176:     sum=b[ip]; 
                   5177:     b[ip]=b[i]; 
                   5178:     if (ii) 
                   5179:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5180:     else if (sum) ii=i; 
                   5181:     b[i]=sum; 
                   5182:   } 
                   5183:   for (i=n;i>=1;i--) { 
                   5184:     sum=b[i]; 
                   5185:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5186:     b[i]=sum/a[i][i]; 
                   5187:   } 
                   5188: } 
                   5189: 
                   5190: void pstamp(FILE *fichier)
                   5191: {
1.196     brouard  5192:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5193: }
                   5194: 
1.297     brouard  5195: void date2dmy(double date,double *day, double *month, double *year){
                   5196:   double yp=0., yp1=0., yp2=0.;
                   5197:   
                   5198:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5199:                        fractional in yp1 */
                   5200:   *year=yp;
                   5201:   yp2=modf((yp1*12),&yp);
                   5202:   *month=yp;
                   5203:   yp1=modf((yp2*30.5),&yp);
                   5204:   *day=yp;
                   5205:   if(*day==0) *day=1;
                   5206:   if(*month==0) *month=1;
                   5207: }
                   5208: 
1.253     brouard  5209: 
                   5210: 
1.126     brouard  5211: /************ Frequencies ********************/
1.251     brouard  5212: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5213:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5214:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5215: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5216:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5217:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5218:   int iind=0, iage=0;
                   5219:   int mi; /* Effective wave */
                   5220:   int first;
                   5221:   double ***freq; /* Frequencies */
1.268     brouard  5222:   double *x, *y, a=0.,b=0.,r=1., sa=0., sb=0.; /* for regression, y=b+m*x and r is the correlation coefficient */
                   5223:   int no=0, linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb);
1.284     brouard  5224:   double *meanq, *stdq, *idq;
1.226     brouard  5225:   double **meanqt;
                   5226:   double *pp, **prop, *posprop, *pospropt;
                   5227:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5228:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5229:   double agebegin, ageend;
                   5230:     
                   5231:   pp=vector(1,nlstate);
1.251     brouard  5232:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5233:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5234:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5235:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5236:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5237:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5238:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5239:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5240:   strcpy(fileresp,"P_");
                   5241:   strcat(fileresp,fileresu);
                   5242:   /*strcat(fileresphtm,fileresu);*/
                   5243:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5244:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5245:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5246:     exit(0);
                   5247:   }
1.240     brouard  5248:   
1.226     brouard  5249:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5250:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5251:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5252:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5253:     fflush(ficlog);
                   5254:     exit(70); 
                   5255:   }
                   5256:   else{
                   5257:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5258: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5259: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5260:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5261:   }
1.319     brouard  5262:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies (weight=%d) and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm, weightopt);
1.240     brouard  5263:   
1.226     brouard  5264:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5265:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5266:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5267:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5268:     fflush(ficlog);
                   5269:     exit(70); 
1.240     brouard  5270:   } else{
1.226     brouard  5271:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.319     brouard  5272: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5273: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5274:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5275:   }
1.319     brouard  5276:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>(weight=%d) frequencies of all effective transitions of the model, by age at begin of transition, and covariate value at the begin of transition (if the covariate is a varying covariate) </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr,weightopt);
1.240     brouard  5277:   
1.253     brouard  5278:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5279:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5280:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5281:   j1=0;
1.126     brouard  5282:   
1.227     brouard  5283:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5284:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5285:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5286:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5287:   
                   5288:   
1.226     brouard  5289:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5290:      reference=low_education V1=0,V2=0
                   5291:      med_educ                V1=1 V2=0, 
                   5292:      high_educ               V1=0 V2=1
1.330     brouard  5293:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5294:   */
1.249     brouard  5295:   dateintsum=0;
                   5296:   k2cpt=0;
                   5297: 
1.253     brouard  5298:   if(cptcoveff == 0 )
1.265     brouard  5299:     nl=1;  /* Constant and age model only */
1.253     brouard  5300:   else
                   5301:     nl=2;
1.265     brouard  5302: 
                   5303:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5304:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5305:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5306:    *     freq[s1][s2][iage] =0.
                   5307:    *     Loop on iind
                   5308:    *       ++freq[s1][s2][iage] weighted
                   5309:    *     end iind
                   5310:    *     if covariate and j!0
                   5311:    *       headers Variable on one line
                   5312:    *     endif cov j!=0
                   5313:    *     header of frequency table by age
                   5314:    *     Loop on age
                   5315:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5316:    *       pos+=freq[s1][s2][iage] weighted
                   5317:    *       Loop on s1 initial state
                   5318:    *         fprintf(ficresp
                   5319:    *       end s1
                   5320:    *     end age
                   5321:    *     if j!=0 computes starting values
                   5322:    *     end compute starting values
                   5323:    *   end j1
                   5324:    * end nl 
                   5325:    */
1.253     brouard  5326:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5327:     if(nj==1)
                   5328:       j=0;  /* First pass for the constant */
1.265     brouard  5329:     else{
1.335     brouard  5330:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
1.265     brouard  5331:     }
1.251     brouard  5332:     first=1;
1.332     brouard  5333:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all dummy covariates combination of the model, ie excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  5334:       posproptt=0.;
1.330     brouard  5335:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5336:        scanf("%d", i);*/
                   5337:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5338:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5339:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5340:            freq[i][s2][m]=0;
1.251     brouard  5341:       
                   5342:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5343:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5344:          prop[i][m]=0;
                   5345:        posprop[i]=0;
                   5346:        pospropt[i]=0;
                   5347:       }
1.283     brouard  5348:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5349:         idq[z1]=0.;
                   5350:         meanq[z1]=0.;
                   5351:         stdq[z1]=0.;
1.283     brouard  5352:       }
                   5353:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5354:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5355:       /*         meanqt[m][z1]=0.; */
                   5356:       /*       } */
                   5357:       /* }       */
1.251     brouard  5358:       /* dateintsum=0; */
                   5359:       /* k2cpt=0; */
                   5360:       
1.265     brouard  5361:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5362:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5363:        bool=1;
                   5364:        if(j !=0){
                   5365:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5366:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5367:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5368:                /* if(Tvaraff[z1] ==-20){ */
                   5369:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5370:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5371:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5372:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5373:                /* if( iind >=imx-3) printf("Searching error iind=%d Tvaraff[z1]=%d covar[Tvaraff[z1]][iind]=%.f TnsdVar[Tvaraff[z1]]=%d, cptcoveff=%d, cptcovs=%d \n",iind, Tvaraff[z1], covar[Tvaraff[z1]][iind],TnsdVar[Tvaraff[z1]],cptcoveff, cptcovs); */
                   5374:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5375:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5376:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5377:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5378:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5379:                  /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", */
                   5380:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5381:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5382:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5383:                } /* Onlyf fixed */
                   5384:              } /* end z1 */
1.335     brouard  5385:            } /* cptcoveff > 0 */
1.251     brouard  5386:          } /* end any */
                   5387:        }/* end j==0 */
1.265     brouard  5388:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5389:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5390:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5391:            m=mw[mi][iind];
                   5392:            if(j!=0){
                   5393:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5394:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5395:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5396:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5397:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  5398:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
1.251     brouard  5399:                                                                                      value is -1, we don't select. It differs from the 
                   5400:                                                                                      constant and age model which counts them. */
                   5401:                      bool=0; /* not selected */
                   5402:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5403:                    /* i1=Tvaraff[z1]; */
                   5404:                    /* i2=TnsdVar[i1]; */
                   5405:                    /* i3=nbcode[i1][i2]; */
                   5406:                    /* i4=covar[i1][iind]; */
                   5407:                    /* if(i4 != i3){ */
                   5408:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5409:                      bool=0;
                   5410:                    }
                   5411:                  }
                   5412:                }
                   5413:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5414:            } /* end j==0 */
                   5415:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5416:            if(bool==1){ /*Selected */
1.251     brouard  5417:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5418:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5419:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5420:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5421:              if(m >=firstpass && m <=lastpass){
                   5422:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5423:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5424:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5425:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5426:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5427:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5428:                if (m<lastpass) {
                   5429:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5430:                  /*   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
                   5431:                  if(s[m][iind]==-1)
                   5432:                    printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
                   5433:                  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
1.311     brouard  5434:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5435:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5436:                      idq[z1]=idq[z1]+weight[iind];
                   5437:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5438:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5439:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5440:                    }
1.284     brouard  5441:                  }
1.251     brouard  5442:                  /* if((int)agev[m][iind] == 55) */
                   5443:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5444:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5445:                  freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
1.234     brouard  5446:                }
1.251     brouard  5447:              } /* end if between passes */  
                   5448:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5449:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5450:                k2cpt++;
                   5451:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5452:              }
1.251     brouard  5453:            }else{
                   5454:              bool=1;
                   5455:            }/* end bool 2 */
                   5456:          } /* end m */
1.284     brouard  5457:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5458:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5459:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5460:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5461:          /* } */
1.251     brouard  5462:        } /* end bool */
                   5463:       } /* end iind = 1 to imx */
1.319     brouard  5464:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5465:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5466:       
                   5467:       
                   5468:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5469:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5470:         pstamp(ficresp);
1.335     brouard  5471:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5472:         pstamp(ficresp);
1.251     brouard  5473:        printf( "\n#********** Variable "); 
                   5474:        fprintf(ficresp, "\n#********** Variable "); 
                   5475:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5476:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5477:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  5478:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  5479:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5480:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5481:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5482:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5483:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5484:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5485:          }else{
1.330     brouard  5486:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5487:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5488:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5489:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5490:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5491:          }
                   5492:        }
                   5493:        printf( "**********\n#");
                   5494:        fprintf(ficresp, "**********\n#");
                   5495:        fprintf(ficresphtm, "**********</h3>\n");
                   5496:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5497:        fprintf(ficlog, "**********\n");
                   5498:       }
1.284     brouard  5499:       /*
                   5500:        Printing means of quantitative variables if any
                   5501:       */
                   5502:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5503:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5504:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5505:        if(weightopt==1){
                   5506:          printf(" Weighted mean and standard deviation of");
                   5507:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5508:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5509:        }
1.311     brouard  5510:        /* mu = \frac{w x}{\sum w}
                   5511:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5512:        */
                   5513:        printf(" fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
                   5514:        fprintf(ficlog," fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
                   5515:        fprintf(ficresphtmfr," fixed quantitative variable V%d on %.3g (weighted) representatives of the population : %8.5g (%8.5g)<p>\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
1.284     brouard  5516:       }
                   5517:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5518:       /*       for(m=1;m<=lastpass;m++){ */
                   5519:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5520:       /*   } */
                   5521:       /* } */
1.283     brouard  5522: 
1.251     brouard  5523:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5524:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5525:         fprintf(ficresp, " Age");
1.335     brouard  5526:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5527:          printf(" V%d=%d, z1=%d, Tvaraff[z1]=%d, j1=%d, TnsdVar[Tvaraff[%d]]=%d |",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])], z1, Tvaraff[z1], j1,z1,TnsdVar[Tvaraff[z1]]);
                   5528:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5529:        }
1.251     brouard  5530:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5531:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5532:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5533:       }
1.335     brouard  5534:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5535:       fprintf(ficresphtm, "\n");
                   5536:       
                   5537:       /* Header of frequency table by age */
                   5538:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5539:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5540:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5541:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5542:          if(s2!=0 && m!=0)
                   5543:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5544:        }
1.226     brouard  5545:       }
1.251     brouard  5546:       fprintf(ficresphtmfr, "\n");
                   5547:     
                   5548:       /* For each age */
                   5549:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5550:        fprintf(ficresphtm,"<tr>");
                   5551:        if(iage==iagemax+1){
                   5552:          fprintf(ficlog,"1");
                   5553:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5554:        }else if(iage==iagemax+2){
                   5555:          fprintf(ficlog,"0");
                   5556:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5557:        }else if(iage==iagemax+3){
                   5558:          fprintf(ficlog,"Total");
                   5559:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5560:        }else{
1.240     brouard  5561:          if(first==1){
1.251     brouard  5562:            first=0;
                   5563:            printf("See log file for details...\n");
                   5564:          }
                   5565:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5566:          fprintf(ficlog,"Age %d", iage);
                   5567:        }
1.265     brouard  5568:        for(s1=1; s1 <=nlstate ; s1++){
                   5569:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5570:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5571:        }
1.265     brouard  5572:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5573:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5574:            pos += freq[s1][m][iage];
                   5575:          if(pp[s1]>=1.e-10){
1.251     brouard  5576:            if(first==1){
1.265     brouard  5577:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5578:            }
1.265     brouard  5579:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5580:          }else{
                   5581:            if(first==1)
1.265     brouard  5582:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5583:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5584:          }
                   5585:        }
                   5586:       
1.265     brouard  5587:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5588:          /* posprop[s1]=0; */
                   5589:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5590:            pp[s1] += freq[s1][m][iage];
                   5591:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5592:       
                   5593:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5594:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5595:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5596:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5597:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5598:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5599:        }
                   5600:        
                   5601:        /* Writing ficresp */
1.335     brouard  5602:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5603:           if( iage <= iagemax){
                   5604:            fprintf(ficresp," %d",iage);
                   5605:           }
                   5606:         }else if( nj==2){
                   5607:           if( iage <= iagemax){
                   5608:            fprintf(ficresp," %d",iage);
1.335     brouard  5609:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5610:           }
1.240     brouard  5611:        }
1.265     brouard  5612:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5613:          if(pos>=1.e-5){
1.251     brouard  5614:            if(first==1)
1.265     brouard  5615:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5616:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5617:          }else{
                   5618:            if(first==1)
1.265     brouard  5619:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5620:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5621:          }
                   5622:          if( iage <= iagemax){
                   5623:            if(pos>=1.e-5){
1.335     brouard  5624:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5625:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5626:               }else if( nj==2){
                   5627:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5628:               }
                   5629:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5630:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5631:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5632:            } else{
1.335     brouard  5633:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5634:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5635:            }
1.240     brouard  5636:          }
1.265     brouard  5637:          pospropt[s1] +=posprop[s1];
                   5638:        } /* end loop s1 */
1.251     brouard  5639:        /* pospropt=0.; */
1.265     brouard  5640:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5641:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5642:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5643:              if(first==1){
1.265     brouard  5644:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5645:              }
1.265     brouard  5646:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5647:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5648:            }
1.265     brouard  5649:            if(s1!=0 && m!=0)
                   5650:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5651:          }
1.265     brouard  5652:        } /* end loop s1 */
1.251     brouard  5653:        posproptt=0.; 
1.265     brouard  5654:        for(s1=1; s1 <=nlstate; s1++){
                   5655:          posproptt += pospropt[s1];
1.251     brouard  5656:        }
                   5657:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5658:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5659:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5660:          if(iage <= iagemax)
                   5661:            fprintf(ficresp,"\n");
1.240     brouard  5662:        }
1.251     brouard  5663:        if(first==1)
                   5664:          printf("Others in log...\n");
                   5665:        fprintf(ficlog,"\n");
                   5666:       } /* end loop age iage */
1.265     brouard  5667:       
1.251     brouard  5668:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5669:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5670:        if(posproptt < 1.e-5){
1.265     brouard  5671:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5672:        }else{
1.265     brouard  5673:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5674:        }
1.226     brouard  5675:       }
1.251     brouard  5676:       fprintf(ficresphtm,"</tr>\n");
                   5677:       fprintf(ficresphtm,"</table>\n");
                   5678:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5679:       if(posproptt < 1.e-5){
1.251     brouard  5680:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5681:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5682:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5683:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5684:        invalidvarcomb[j1]=1;
1.226     brouard  5685:       }else{
1.338     brouard  5686:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5687:        invalidvarcomb[j1]=0;
1.226     brouard  5688:       }
1.251     brouard  5689:       fprintf(ficresphtmfr,"</table>\n");
                   5690:       fprintf(ficlog,"\n");
                   5691:       if(j!=0){
                   5692:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5693:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5694:          for(k=1; k <=(nlstate+ndeath); k++){
                   5695:            if (k != i) {
1.265     brouard  5696:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5697:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5698:                  if(j1==1){ /* All dummy covariates to zero */
                   5699:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5700:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5701:                    printf("%d%d ",i,k);
                   5702:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5703:                    printf("%12.7f ln(%.0f/%.0f)= %f, OR=%f sd=%f \n",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]),freq[i][k][iagemax+3]/freq[i][i][iagemax+3], sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]));
                   5704:                    fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f \n",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   5705:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5706:                  }
1.253     brouard  5707:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5708:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5709:                    x[iage]= (double)iage;
                   5710:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5711:                    /* printf("i=%d, k=%d, s1=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,s1,j1,jj, iage, y[iage]); */
1.253     brouard  5712:                  }
1.268     brouard  5713:                  /* Some are not finite, but linreg will ignore these ages */
                   5714:                  no=0;
1.253     brouard  5715:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5716:                  pstart[s1]=b;
                   5717:                  pstart[s1-1]=a;
1.252     brouard  5718:                }else if( j1!=1 && (j1==2 || (log(j1-1.)/log(2.)-(int)(log(j1-1.)/log(2.))) <0.010) && ( TvarsDind[(int)(log(j1-1.)/log(2.))+1]+2+nagesqr == jj)  && Dummy[jj-2-nagesqr]==0){ /* We want only if the position, jj, in model corresponds to unique covariate equal to 1 in j1 combination */ 
                   5719:                  printf("j1=%d, jj=%d, (int)(log(j1-1.)/log(2.))+1=%d, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(int)(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
                   5720:                  printf("j1=%d, jj=%d, (log(j1-1.)/log(2.))+1=%f, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
1.265     brouard  5721:                  pstart[s1]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
1.252     brouard  5722:                  printf("%d%d ",i,k);
                   5723:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5724:                  printf("s1=%d,i=%d,k=%d,p[%d]=%12.7f ln((%.0f/%.0f)/(%.0f/%.0f))= %f, OR=%f sd=%f \n",s1,i,k,s1,p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3],freq[i][k][iagemax+4],freq[i][i][iagemax+4], log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4])),(freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]), sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]+1/freq[i][k][iagemax+4]+1/freq[i][i][iagemax+4]));
1.251     brouard  5725:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5726:                  ;
                   5727:                }
                   5728:                /* printf("%12.7f )", param[i][jj][k]); */
                   5729:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5730:                s1++; 
1.251     brouard  5731:              } /* end jj */
                   5732:            } /* end k!= i */
                   5733:          } /* end k */
1.265     brouard  5734:        } /* end i, s1 */
1.251     brouard  5735:       } /* end j !=0 */
                   5736:     } /* end selected combination of covariate j1 */
                   5737:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5738:       printf("#Freqsummary: Starting values for the constants:\n");
                   5739:       fprintf(ficlog,"\n");
1.265     brouard  5740:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5741:        for(k=1; k <=(nlstate+ndeath); k++){
                   5742:          if (k != i) {
                   5743:            printf("%d%d ",i,k);
                   5744:            fprintf(ficlog,"%d%d ",i,k);
                   5745:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5746:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5747:              if(jj==1){ /* Age has to be done */
1.265     brouard  5748:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5749:                printf("%12.7f ln(%.0f/%.0f)= %12.7f ",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   5750:                fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f ",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
1.251     brouard  5751:              }
                   5752:              /* printf("%12.7f )", param[i][jj][k]); */
                   5753:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5754:              s1++; 
1.250     brouard  5755:            }
1.251     brouard  5756:            printf("\n");
                   5757:            fprintf(ficlog,"\n");
1.250     brouard  5758:          }
                   5759:        }
1.284     brouard  5760:       } /* end of state i */
1.251     brouard  5761:       printf("#Freqsummary\n");
                   5762:       fprintf(ficlog,"\n");
1.265     brouard  5763:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5764:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5765:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5766:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5767:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5768:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5769:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5770:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5771:          /* } */
                   5772:        }
1.265     brouard  5773:       } /* end loop s1 */
1.251     brouard  5774:       
                   5775:       printf("\n");
                   5776:       fprintf(ficlog,"\n");
                   5777:     } /* end j=0 */
1.249     brouard  5778:   } /* end j */
1.252     brouard  5779: 
1.253     brouard  5780:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5781:     for(i=1, jk=1; i <=nlstate; i++){
                   5782:       for(j=1; j <=nlstate+ndeath; j++){
                   5783:        if(j!=i){
                   5784:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5785:          printf("%1d%1d",i,j);
                   5786:          fprintf(ficparo,"%1d%1d",i,j);
                   5787:          for(k=1; k<=ncovmodel;k++){
                   5788:            /*    printf(" %lf",param[i][j][k]); */
                   5789:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5790:            p[jk]=pstart[jk];
                   5791:            printf(" %f ",pstart[jk]);
                   5792:            fprintf(ficparo," %f ",pstart[jk]);
                   5793:            jk++;
                   5794:          }
                   5795:          printf("\n");
                   5796:          fprintf(ficparo,"\n");
                   5797:        }
                   5798:       }
                   5799:     }
                   5800:   } /* end mle=-2 */
1.226     brouard  5801:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5802:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5803:   
1.226     brouard  5804:   fclose(ficresp);
                   5805:   fclose(ficresphtm);
                   5806:   fclose(ficresphtmfr);
1.283     brouard  5807:   free_vector(idq,1,nqfveff);
1.226     brouard  5808:   free_vector(meanq,1,nqfveff);
1.284     brouard  5809:   free_vector(stdq,1,nqfveff);
1.226     brouard  5810:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5811:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5812:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5813:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5814:   free_vector(pospropt,1,nlstate);
                   5815:   free_vector(posprop,1,nlstate);
1.251     brouard  5816:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5817:   free_vector(pp,1,nlstate);
                   5818:   /* End of freqsummary */
                   5819: }
1.126     brouard  5820: 
1.268     brouard  5821: /* Simple linear regression */
                   5822: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5823: 
                   5824:   /* y=a+bx regression */
                   5825:   double   sumx = 0.0;                        /* sum of x                      */
                   5826:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5827:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5828:   double   sumy = 0.0;                        /* sum of y                      */
                   5829:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5830:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5831:   double yhat;
                   5832:   
                   5833:   double denom=0;
                   5834:   int i;
                   5835:   int ne=*no;
                   5836:   
                   5837:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5838:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5839:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5840:       continue;
                   5841:     }
                   5842:     ne=ne+1;
                   5843:     sumx  += x[i];       
                   5844:     sumx2 += x[i]*x[i];  
                   5845:     sumxy += x[i] * y[i];
                   5846:     sumy  += y[i];      
                   5847:     sumy2 += y[i]*y[i]; 
                   5848:     denom = (ne * sumx2 - sumx*sumx);
                   5849:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
                   5850:   } 
                   5851:   
                   5852:   denom = (ne * sumx2 - sumx*sumx);
                   5853:   if (denom == 0) {
                   5854:     // vertical, slope m is infinity
                   5855:     *b = INFINITY;
                   5856:     *a = 0;
                   5857:     if (r) *r = 0;
                   5858:     return 1;
                   5859:   }
                   5860:   
                   5861:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5862:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5863:   if (r!=NULL) {
                   5864:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5865:       sqrt((sumx2 - sumx*sumx/ne) *
                   5866:           (sumy2 - sumy*sumy/ne));
                   5867:   }
                   5868:   *no=ne;
                   5869:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5870:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5871:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5872:       continue;
                   5873:     }
                   5874:     ne=ne+1;
                   5875:     yhat = y[i] - *a -*b* x[i];
                   5876:     sume2  += yhat * yhat ;       
                   5877:     
                   5878:     denom = (ne * sumx2 - sumx*sumx);
                   5879:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
                   5880:   } 
                   5881:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5882:   *sa= *sb * sqrt(sumx2/ne);
                   5883:   
                   5884:   return 0; 
                   5885: }
                   5886: 
1.126     brouard  5887: /************ Prevalence ********************/
1.227     brouard  5888: void prevalence(double ***probs, double agemin, double agemax, int **s, double **agev, int nlstate, int imx, int *Tvar, int **nbcode, int *ncodemax,double **mint,double **anint, double dateprev1,double dateprev2, int firstpass, int lastpass)
                   5889: {  
                   5890:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5891:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5892:      We still use firstpass and lastpass as another selection.
                   5893:   */
1.126     brouard  5894:  
1.227     brouard  5895:   int i, m, jk, j1, bool, z1,j, iv;
                   5896:   int mi; /* Effective wave */
                   5897:   int iage;
                   5898:   double agebegin, ageend;
                   5899: 
                   5900:   double **prop;
                   5901:   double posprop; 
                   5902:   double  y2; /* in fractional years */
                   5903:   int iagemin, iagemax;
                   5904:   int first; /** to stop verbosity which is redirected to log file */
                   5905: 
                   5906:   iagemin= (int) agemin;
                   5907:   iagemax= (int) agemax;
                   5908:   /*pp=vector(1,nlstate);*/
1.251     brouard  5909:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5910:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5911:   j1=0;
1.222     brouard  5912:   
1.227     brouard  5913:   /*j=cptcoveff;*/
                   5914:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5915:   
1.288     brouard  5916:   first=0;
1.335     brouard  5917:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5918:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5919:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5920:        prop[i][iage]=0.0;
                   5921:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5922:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5923:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5924:     
                   5925:     for (i=1; i<=imx; i++) { /* Each individual */
                   5926:       bool=1;
                   5927:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5928:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5929:        m=mw[mi][i];
                   5930:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5931:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5932:        for (z1=1; z1<=cptcoveff; z1++){
                   5933:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  5934:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  5935:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5936:              bool=0;
                   5937:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5938:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5939:              bool=0;
                   5940:            }
                   5941:        }
                   5942:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5943:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5944:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5945:          if(m >=firstpass && m <=lastpass){
                   5946:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5947:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5948:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5949:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5950:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5951:                printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
                   5952:                exit(1);
                   5953:              }
                   5954:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5955:                /*if(i>4620) printf(" i=%d m=%d s[m][i]=%d (int)agev[m][i]=%d weight[i]=%f prop=%f\n",i,m,s[m][i],(int)agev[m][m],weight[i],prop[s[m][i]][(int)agev[m][i]]);*/
                   5956:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5957:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5958:              } /* end valid statuses */ 
                   5959:            } /* end selection of dates */
                   5960:          } /* end selection of waves */
                   5961:        } /* end bool */
                   5962:       } /* end wave */
                   5963:     } /* end individual */
                   5964:     for(i=iagemin; i <= iagemax+3; i++){  
                   5965:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5966:        posprop += prop[jk][i]; 
                   5967:       } 
                   5968:       
                   5969:       for(jk=1; jk <=nlstate ; jk++){      
                   5970:        if( i <=  iagemax){ 
                   5971:          if(posprop>=1.e-5){ 
                   5972:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5973:          } else{
1.288     brouard  5974:            if(!first){
                   5975:              first=1;
1.266     brouard  5976:              printf("Warning Observed prevalence doesn't sum to 1 for state %d: probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,jk, j1,probs[i][jk][j1]);
                   5977:            }else{
1.288     brouard  5978:              fprintf(ficlog,"Warning Observed prevalence doesn't sum to 1 for state %d: probs[%d][%d][%d]=%lf because of lack of cases.\n",jk,i,jk, j1,probs[i][jk][j1]);
1.227     brouard  5979:            }
                   5980:          }
                   5981:        } 
                   5982:       }/* end jk */ 
                   5983:     }/* end i */ 
1.222     brouard  5984:      /*} *//* end i1 */
1.227     brouard  5985:   } /* end j1 */
1.222     brouard  5986:   
1.227     brouard  5987:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5988:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5989:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5990: }  /* End of prevalence */
1.126     brouard  5991: 
                   5992: /************* Waves Concatenation ***************/
                   5993: 
                   5994: void  concatwav(int wav[], int **dh, int **bh,  int **mw, int **s, double *agedc, double **agev, int  firstpass, int lastpass, int imx, int nlstate, int stepm)
                   5995: {
1.298     brouard  5996:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
1.126     brouard  5997:      Death is a valid wave (if date is known).
                   5998:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5999:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  6000:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  6001:   */
1.126     brouard  6002: 
1.224     brouard  6003:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  6004:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6005:      double sum=0., jmean=0.;*/
1.224     brouard  6006:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  6007:   int j, k=0,jk, ju, jl;
                   6008:   double sum=0.;
                   6009:   first=0;
1.214     brouard  6010:   firstwo=0;
1.217     brouard  6011:   firsthree=0;
1.218     brouard  6012:   firstfour=0;
1.164     brouard  6013:   jmin=100000;
1.126     brouard  6014:   jmax=-1;
                   6015:   jmean=0.;
1.224     brouard  6016: 
                   6017: /* Treating live states */
1.214     brouard  6018:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  6019:     mi=0;  /* First valid wave */
1.227     brouard  6020:     mli=0; /* Last valid wave */
1.309     brouard  6021:     m=firstpass;  /* Loop on waves */
                   6022:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  6023:       if(m >firstpass && s[m][i]==s[m-1][i] && mint[m][i]==mint[m-1][i] && anint[m][i]==anint[m-1][i]){/* Two succesive identical information on wave m */
                   6024:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6025:       }else if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
1.309     brouard  6026:        mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
1.227     brouard  6027:        mli=m;
1.224     brouard  6028:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6029:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  6030:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  6031:       }
1.309     brouard  6032:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  6033: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  6034:        break;
1.224     brouard  6035: #else
1.317     brouard  6036:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* no death date and known date of interview, case -2 (vital status unknown is warned later */
1.227     brouard  6037:          if(firsthree == 0){
1.302     brouard  6038:            printf("Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as 1-p_{%d%d} .\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m, s[m][i], nlstate+ndeath);
1.227     brouard  6039:            firsthree=1;
1.317     brouard  6040:          }else if(firsthree >=1 && firsthree < 10){
                   6041:            fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as 1-p_{%d%d} .\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m, s[m][i], nlstate+ndeath);
                   6042:            firsthree++;
                   6043:          }else if(firsthree == 10){
                   6044:            printf("Information, too many Information flags: no more reported to log either\n");
                   6045:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6046:            firsthree++;
                   6047:          }else{
                   6048:            firsthree++;
1.227     brouard  6049:          }
1.309     brouard  6050:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  6051:          mli=m;
                   6052:        }
                   6053:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6054:          nbwarn++;
1.309     brouard  6055:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  6056:            printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   6057:            fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   6058:          }
                   6059:          break;
                   6060:        }
                   6061:        break;
1.224     brouard  6062: #endif
1.227     brouard  6063:       }/* End m >= lastpass */
1.126     brouard  6064:     }/* end while */
1.224     brouard  6065: 
1.227     brouard  6066:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
1.216     brouard  6067:     /* After last pass */
1.224     brouard  6068: /* Treating death states */
1.214     brouard  6069:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  6070:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6071:       /* } */
1.126     brouard  6072:       mi++;    /* Death is another wave */
                   6073:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  6074:       /* Only death is a correct wave */
1.126     brouard  6075:       mw[mi][i]=m;
1.257     brouard  6076:     } /* else not in a death state */
1.224     brouard  6077: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  6078:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  6079:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  6080:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* month of death occured before last wave month and status should have been death instead of -1 */
1.227     brouard  6081:          nbwarn++;
                   6082:          if(firstfiv==0){
1.309     brouard  6083:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  6084:            firstfiv=1;
                   6085:          }else{
1.309     brouard  6086:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  6087:          }
1.309     brouard  6088:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6089:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  6090:          nberr++;
                   6091:          if(firstwo==0){
1.309     brouard  6092:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. See documentation\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  6093:            firstwo=1;
                   6094:          }
1.309     brouard  6095:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  6096:        }
1.257     brouard  6097:       }else{ /* if date of interview is unknown */
1.227     brouard  6098:        /* death is known but not confirmed by death status at any wave */
                   6099:        if(firstfour==0){
1.309     brouard  6100:          printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d with status %d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  6101:          firstfour=1;
                   6102:        }
1.309     brouard  6103:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d  with status %d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.214     brouard  6104:       }
1.224     brouard  6105:     } /* end if date of death is known */
                   6106: #endif
1.309     brouard  6107:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6108:     /* wav[i]=mw[mi][i];   */
1.126     brouard  6109:     if(mi==0){
                   6110:       nbwarn++;
                   6111:       if(first==0){
1.227     brouard  6112:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6113:        first=1;
1.126     brouard  6114:       }
                   6115:       if(first==1){
1.227     brouard  6116:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  6117:       }
                   6118:     } /* end mi==0 */
                   6119:   } /* End individuals */
1.214     brouard  6120:   /* wav and mw are no more changed */
1.223     brouard  6121:        
1.317     brouard  6122:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6123:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6124: 
                   6125: 
1.126     brouard  6126:   for(i=1; i<=imx; i++){
                   6127:     for(mi=1; mi<wav[i];mi++){
                   6128:       if (stepm <=0)
1.227     brouard  6129:        dh[mi][i]=1;
1.126     brouard  6130:       else{
1.260     brouard  6131:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  6132:          if (agedc[i] < 2*AGESUP) {
                   6133:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6134:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6135:            else if(j<0){
                   6136:              nberr++;
                   6137:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6138:              j=1; /* Temporary Dangerous patch */
                   6139:              printf("   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
                   6140:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6141:              fprintf(ficlog,"   We assumed that the date of interview was correct (and not the date of death) and postponed the death %d month(s) (one stepm) after the interview. You MUST fix the contradiction between dates.\n",stepm);
                   6142:            }
                   6143:            k=k+1;
                   6144:            if (j >= jmax){
                   6145:              jmax=j;
                   6146:              ijmax=i;
                   6147:            }
                   6148:            if (j <= jmin){
                   6149:              jmin=j;
                   6150:              ijmin=i;
                   6151:            }
                   6152:            sum=sum+j;
                   6153:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6154:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6155:          }
                   6156:        }
                   6157:        else{
                   6158:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6159: /*       if (j<0) printf("%d %lf %lf %d %d %d\n", i,agev[mw[mi+1][i]][i], agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]); */
1.223     brouard  6160:                                        
1.227     brouard  6161:          k=k+1;
                   6162:          if (j >= jmax) {
                   6163:            jmax=j;
                   6164:            ijmax=i;
                   6165:          }
                   6166:          else if (j <= jmin){
                   6167:            jmin=j;
                   6168:            ijmin=i;
                   6169:          }
                   6170:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6171:          /*printf("%d %lf %d %d %d\n", i,agev[mw[mi][i]][i],j,s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);*/
                   6172:          if(j<0){
                   6173:            nberr++;
                   6174:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6175:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   6176:          }
                   6177:          sum=sum+j;
                   6178:        }
                   6179:        jk= j/stepm;
                   6180:        jl= j -jk*stepm;
                   6181:        ju= j -(jk+1)*stepm;
                   6182:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6183:          if(jl==0){
                   6184:            dh[mi][i]=jk;
                   6185:            bh[mi][i]=0;
                   6186:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6187:                  * to avoid the price of an extra matrix product in likelihood */
                   6188:            dh[mi][i]=jk+1;
                   6189:            bh[mi][i]=ju;
                   6190:          }
                   6191:        }else{
                   6192:          if(jl <= -ju){
                   6193:            dh[mi][i]=jk;
                   6194:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6195:                                 * is higher than the multiple of stepm and negative otherwise.
                   6196:                                 */
                   6197:          }
                   6198:          else{
                   6199:            dh[mi][i]=jk+1;
                   6200:            bh[mi][i]=ju;
                   6201:          }
                   6202:          if(dh[mi][i]==0){
                   6203:            dh[mi][i]=1; /* At least one step */
                   6204:            bh[mi][i]=ju; /* At least one step */
                   6205:            /*  printf(" bh=%d ju=%d jl=%d dh=%d jk=%d stepm=%d %d\n",bh[mi][i],ju,jl,dh[mi][i],jk,stepm,i);*/
                   6206:          }
                   6207:        } /* end if mle */
1.126     brouard  6208:       }
                   6209:     } /* end wave */
                   6210:   }
                   6211:   jmean=sum/k;
                   6212:   printf("Delay (in months) between two waves Min=%d (for indiviudal %ld) Max=%d (%ld) Mean=%f\n\n ",jmin, num[ijmin], jmax, num[ijmax], jmean);
1.141     brouard  6213:   fprintf(ficlog,"Delay (in months) between two waves Min=%d (for indiviudal %d) Max=%d (%d) Mean=%f\n\n ",jmin, ijmin, jmax, ijmax, jmean);
1.227     brouard  6214: }
1.126     brouard  6215: 
                   6216: /*********** Tricode ****************************/
1.220     brouard  6217:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6218:  {
                   6219:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6220:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6221:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6222:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6223:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6224:     */
1.130     brouard  6225: 
1.242     brouard  6226:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6227:    int modmaxcovj=0; /* Modality max of covariates j */
                   6228:    int cptcode=0; /* Modality max of covariates j */
                   6229:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6230: 
                   6231: 
1.242     brouard  6232:    /* cptcoveff=0;  */
                   6233:    /* *cptcov=0; */
1.126     brouard  6234:  
1.242     brouard  6235:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6236:    for (k=1; k <= maxncov; k++)
                   6237:      for(j=1; j<=2; j++)
                   6238:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6239: 
1.242     brouard  6240:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6241:    for (k=1; k<=cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.242     brouard  6242:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343   ! brouard  6243:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.339     brouard  6244:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6245:        switch(Fixed[k]) {
                   6246:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6247:         modmaxcovj=0;
                   6248:         modmincovj=0;
1.242     brouard  6249:         for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
1.339     brouard  6250:           /* printf("Waiting for error tricode Tvar[%d]=%d i=%d (int)(covar[Tvar[k]][i]=%d\n",k,Tvar[k], i, (int)(covar[Tvar[k]][i])); */
1.242     brouard  6251:           ij=(int)(covar[Tvar[k]][i]);
                   6252:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6253:            * If product of Vn*Vm, still boolean *:
                   6254:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6255:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6256:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6257:              modality of the nth covariate of individual i. */
                   6258:           if (ij > modmaxcovj)
                   6259:             modmaxcovj=ij; 
                   6260:           else if (ij < modmincovj) 
                   6261:             modmincovj=ij; 
1.287     brouard  6262:           if (ij <0 || ij >1 ){
1.311     brouard  6263:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6264:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6265:             fflush(ficlog);
                   6266:             exit(1);
1.287     brouard  6267:           }
                   6268:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6269:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6270:             exit(1);
                   6271:           }else
                   6272:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6273:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6274:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6275:           /* getting the maximum value of the modality of the covariate
                   6276:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6277:              female ies 1, then modmaxcovj=1.
                   6278:           */
                   6279:         } /* end for loop on individuals i */
                   6280:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6281:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6282:         cptcode=modmaxcovj;
                   6283:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6284:         /*for (i=0; i<=cptcode; i++) {*/
                   6285:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6286:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6287:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6288:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6289:             if( j != -1){
                   6290:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6291:                                  covariate for which somebody answered excluding 
                   6292:                                  undefined. Usually 2: 0 and 1. */
                   6293:             }
                   6294:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6295:                                     covariate for which somebody answered including 
                   6296:                                     undefined. Usually 3: -1, 0 and 1. */
                   6297:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6298:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6299:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6300:                        
1.242     brouard  6301:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6302:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6303:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6304:         /* modmincovj=3; modmaxcovj = 7; */
                   6305:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6306:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6307:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6308:         /* nbcode[Tvar[j]][ij]=k; */
                   6309:         /* nbcode[Tvar[j]][1]=0; */
                   6310:         /* nbcode[Tvar[j]][2]=1; */
                   6311:         /* nbcode[Tvar[j]][3]=2; */
                   6312:         /* To be continued (not working yet). */
                   6313:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6314: 
                   6315:         /* for (i=modmincovj; i<=modmaxcovj; i++) { */ /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
                   6316:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6317:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6318:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6319:         /*, could be restored in the future */
                   6320:         for (i=0; i<=1; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
1.242     brouard  6321:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6322:             break;
                   6323:           }
                   6324:           ij++;
1.287     brouard  6325:           nbcode[Tvar[k]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality. nbcode[1][1]=0 nbcode[1][2]=1 . Could be -1*/
1.242     brouard  6326:           cptcode = ij; /* New max modality for covar j */
                   6327:         } /* end of loop on modality i=-1 to 1 or more */
                   6328:         break;
                   6329:        case 1: /* Testing on varying covariate, could be simple and
                   6330:                * should look at waves or product of fixed *
                   6331:                * varying. No time to test -1, assuming 0 and 1 only */
                   6332:         ij=0;
                   6333:         for(i=0; i<=1;i++){
                   6334:           nbcode[Tvar[k]][++ij]=i;
                   6335:         }
                   6336:         break;
                   6337:        default:
                   6338:         break;
                   6339:        } /* end switch */
                   6340:      } /* end dummy test */
1.342     brouard  6341:      if(Dummy[k]==1 && Typevar[k] !=1 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  6342:        for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
1.335     brouard  6343:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6344:           printf("Error k=%d \n",k);
                   6345:           exit(1);
                   6346:         }
1.311     brouard  6347:         if(isnan(covar[Tvar[k]][i])){
                   6348:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6349:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6350:           fflush(ficlog);
                   6351:           exit(1);
                   6352:          }
                   6353:        }
1.335     brouard  6354:      } /* end Quanti */
1.287     brouard  6355:    } /* end of loop on model-covariate k. nbcode[Tvark][1]=-1, nbcode[Tvark][1]=0 and nbcode[Tvark][2]=1 sets the value of covariate k*/  
1.242     brouard  6356:   
                   6357:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6358:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6359:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6360:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6361:      ij=Tvar[i]; /* Tvar 5,4,3,6,5,7,1,4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V4*age */ 
                   6362:      Ndum[ij]++; /* Count the # of 1, 2 etc: {1,1,1,2,2,1,1} because V1 once, V2 once, two V4 and V5 in above */
                   6363:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6364:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6365:   
                   6366:    ij=0;
                   6367:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
1.335     brouard  6368:    for (k=1; k<=  cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   6369:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6370:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6371:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6372:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6373:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6374:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
1.242     brouard  6375:        /* If product not in single variable we don't print results */
                   6376:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6377:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6378:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6379:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6380:        /* ij            1    2                                            3  */  
                   6381:        /* Tvaraff[ij]=  4    3                                            1  */
                   6382:        /* Tmodelind[ij]=2    3                                            9  */
                   6383:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6384:        Tvaraff[ij]=Tvar[k]; /* For printing combination *//* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, Tvar {5, 4, 3, 6, 5, 2, 7, 1, 1} Tvaraff={4, 3, 1} V4, V3, V1*/
                   6385:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6386:        TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
                   6387:        if(Fixed[k]!=0)
                   6388:         anyvaryingduminmodel=1;
                   6389:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6390:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6391:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6392:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6393:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6394:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6395:      } 
                   6396:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6397:    /* ij--; */
                   6398:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6399:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6400:                * because they can be excluded from the model and real
                   6401:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6402:    for(j=ij+1; j<= cptcovt; j++){
                   6403:      Tvaraff[j]=0;
                   6404:      Tmodelind[j]=0;
                   6405:    }
                   6406:    for(j=ntveff+1; j<= cptcovt; j++){
                   6407:      TmodelInvind[j]=0;
                   6408:    }
                   6409:    /* To be sorted */
                   6410:    ;
                   6411:  }
1.126     brouard  6412: 
1.145     brouard  6413: 
1.126     brouard  6414: /*********** Health Expectancies ****************/
                   6415: 
1.235     brouard  6416:  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
1.126     brouard  6417: 
                   6418: {
                   6419:   /* Health expectancies, no variances */
1.329     brouard  6420:   /* cij is the combination in the list of combination of dummy covariates */
                   6421:   /* strstart is a string of time at start of computing */
1.164     brouard  6422:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6423:   int nhstepma, nstepma; /* Decreasing with age */
                   6424:   double age, agelim, hf;
                   6425:   double ***p3mat;
                   6426:   double eip;
                   6427: 
1.238     brouard  6428:   /* pstamp(ficreseij); */
1.126     brouard  6429:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6430:   fprintf(ficreseij,"# Age");
                   6431:   for(i=1; i<=nlstate;i++){
                   6432:     for(j=1; j<=nlstate;j++){
                   6433:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6434:     }
                   6435:     fprintf(ficreseij," e%1d. ",i);
                   6436:   }
                   6437:   fprintf(ficreseij,"\n");
                   6438: 
                   6439:   
                   6440:   if(estepm < stepm){
                   6441:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6442:   }
                   6443:   else  hstepm=estepm;   
                   6444:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6445:    * This is mainly to measure the difference between two models: for example
                   6446:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6447:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6448:    * progression in between and thus overestimating or underestimating according
                   6449:    * to the curvature of the survival function. If, for the same date, we 
                   6450:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6451:    * to compare the new estimate of Life expectancy with the same linear 
                   6452:    * hypothesis. A more precise result, taking into account a more precise
                   6453:    * curvature will be obtained if estepm is as small as stepm. */
                   6454: 
                   6455:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6456:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6457:      nhstepm is the number of hstepm from age to agelim 
                   6458:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6459:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6460:      and note for a fixed period like estepm months */
                   6461:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6462:      survival function given by stepm (the optimization length). Unfortunately it
                   6463:      means that if the survival funtion is printed only each two years of age and if
                   6464:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6465:      results. So we changed our mind and took the option of the best precision.
                   6466:   */
                   6467:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6468: 
                   6469:   agelim=AGESUP;
                   6470:   /* If stepm=6 months */
                   6471:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6472:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6473:     
                   6474: /* nhstepm age range expressed in number of stepm */
                   6475:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6476:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6477:   /* if (stepm >= YEARM) hstepm=1;*/
                   6478:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6479:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6480: 
                   6481:   for (age=bage; age<=fage; age ++){ 
                   6482:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6483:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6484:     /* if (stepm >= YEARM) hstepm=1;*/
                   6485:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6486: 
                   6487:     /* If stepm=6 months */
                   6488:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6489:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6490:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
1.235     brouard  6491:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6492:     
                   6493:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6494:     
                   6495:     printf("%d|",(int)age);fflush(stdout);
                   6496:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6497:     
                   6498:     /* Computing expectancies */
                   6499:     for(i=1; i<=nlstate;i++)
                   6500:       for(j=1; j<=nlstate;j++)
                   6501:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6502:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6503:          
                   6504:          /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
                   6505: 
                   6506:        }
                   6507: 
                   6508:     fprintf(ficreseij,"%3.0f",age );
                   6509:     for(i=1; i<=nlstate;i++){
                   6510:       eip=0;
                   6511:       for(j=1; j<=nlstate;j++){
                   6512:        eip +=eij[i][j][(int)age];
                   6513:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6514:       }
                   6515:       fprintf(ficreseij,"%9.4f", eip );
                   6516:     }
                   6517:     fprintf(ficreseij,"\n");
                   6518:     
                   6519:   }
                   6520:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6521:   printf("\n");
                   6522:   fprintf(ficlog,"\n");
                   6523:   
                   6524: }
                   6525: 
1.235     brouard  6526:  void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[], int nres )
1.126     brouard  6527: 
                   6528: {
                   6529:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6530:      to initial status i, ei. .
1.126     brouard  6531:   */
1.336     brouard  6532:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6533:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6534:   int nhstepma, nstepma; /* Decreasing with age */
                   6535:   double age, agelim, hf;
                   6536:   double ***p3matp, ***p3matm, ***varhe;
                   6537:   double **dnewm,**doldm;
                   6538:   double *xp, *xm;
                   6539:   double **gp, **gm;
                   6540:   double ***gradg, ***trgradg;
                   6541:   int theta;
                   6542: 
                   6543:   double eip, vip;
                   6544: 
                   6545:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6546:   xp=vector(1,npar);
                   6547:   xm=vector(1,npar);
                   6548:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6549:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6550:   
                   6551:   pstamp(ficresstdeij);
                   6552:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6553:   fprintf(ficresstdeij,"# Age");
                   6554:   for(i=1; i<=nlstate;i++){
                   6555:     for(j=1; j<=nlstate;j++)
                   6556:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6557:     fprintf(ficresstdeij," e%1d. ",i);
                   6558:   }
                   6559:   fprintf(ficresstdeij,"\n");
                   6560: 
                   6561:   pstamp(ficrescveij);
                   6562:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6563:   fprintf(ficrescveij,"# Age");
                   6564:   for(i=1; i<=nlstate;i++)
                   6565:     for(j=1; j<=nlstate;j++){
                   6566:       cptj= (j-1)*nlstate+i;
                   6567:       for(i2=1; i2<=nlstate;i2++)
                   6568:        for(j2=1; j2<=nlstate;j2++){
                   6569:          cptj2= (j2-1)*nlstate+i2;
                   6570:          if(cptj2 <= cptj)
                   6571:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6572:        }
                   6573:     }
                   6574:   fprintf(ficrescveij,"\n");
                   6575:   
                   6576:   if(estepm < stepm){
                   6577:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6578:   }
                   6579:   else  hstepm=estepm;   
                   6580:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6581:    * This is mainly to measure the difference between two models: for example
                   6582:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6583:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6584:    * progression in between and thus overestimating or underestimating according
                   6585:    * to the curvature of the survival function. If, for the same date, we 
                   6586:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6587:    * to compare the new estimate of Life expectancy with the same linear 
                   6588:    * hypothesis. A more precise result, taking into account a more precise
                   6589:    * curvature will be obtained if estepm is as small as stepm. */
                   6590: 
                   6591:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6592:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6593:      nhstepm is the number of hstepm from age to agelim 
                   6594:      nstepm is the number of stepm from age to agelin. 
                   6595:      Look at hpijx to understand the reason of that which relies in memory size
                   6596:      and note for a fixed period like estepm months */
                   6597:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6598:      survival function given by stepm (the optimization length). Unfortunately it
                   6599:      means that if the survival funtion is printed only each two years of age and if
                   6600:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6601:      results. So we changed our mind and took the option of the best precision.
                   6602:   */
                   6603:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6604: 
                   6605:   /* If stepm=6 months */
                   6606:   /* nhstepm age range expressed in number of stepm */
                   6607:   agelim=AGESUP;
                   6608:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6609:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6610:   /* if (stepm >= YEARM) hstepm=1;*/
                   6611:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6612:   
                   6613:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6614:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6615:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6616:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6617:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6618:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6619: 
                   6620:   for (age=bage; age<=fage; age ++){ 
                   6621:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6622:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6623:     /* if (stepm >= YEARM) hstepm=1;*/
                   6624:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6625:                
1.126     brouard  6626:     /* If stepm=6 months */
                   6627:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6628:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6629:     
                   6630:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6631:                
1.126     brouard  6632:     /* Computing  Variances of health expectancies */
                   6633:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6634:        decrease memory allocation */
                   6635:     for(theta=1; theta <=npar; theta++){
                   6636:       for(i=1; i<=npar; i++){ 
1.222     brouard  6637:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6638:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6639:       }
1.235     brouard  6640:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6641:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6642:                        
1.126     brouard  6643:       for(j=1; j<= nlstate; j++){
1.222     brouard  6644:        for(i=1; i<=nlstate; i++){
                   6645:          for(h=0; h<=nhstepm-1; h++){
                   6646:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6647:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6648:          }
                   6649:        }
1.126     brouard  6650:       }
1.218     brouard  6651:                        
1.126     brouard  6652:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6653:        for(h=0; h<=nhstepm-1; h++){
                   6654:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6655:        }
1.126     brouard  6656:     }/* End theta */
                   6657:     
                   6658:     
                   6659:     for(h=0; h<=nhstepm-1; h++)
                   6660:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6661:        for(theta=1; theta <=npar; theta++)
                   6662:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6663:     
1.218     brouard  6664:                
1.222     brouard  6665:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6666:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6667:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6668:                
1.222     brouard  6669:     printf("%d|",(int)age);fflush(stdout);
                   6670:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6671:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6672:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6673:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6674:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6675:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6676:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6677:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6678:       }
                   6679:     }
1.320     brouard  6680:     /* if((int)age ==50){ */
                   6681:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6682:     /* } */
1.126     brouard  6683:     /* Computing expectancies */
1.235     brouard  6684:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6685:     for(i=1; i<=nlstate;i++)
                   6686:       for(j=1; j<=nlstate;j++)
1.222     brouard  6687:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6688:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6689:                                        
1.222     brouard  6690:          /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
1.218     brouard  6691:                                        
1.222     brouard  6692:        }
1.269     brouard  6693: 
                   6694:     /* Standard deviation of expectancies ij */                
1.126     brouard  6695:     fprintf(ficresstdeij,"%3.0f",age );
                   6696:     for(i=1; i<=nlstate;i++){
                   6697:       eip=0.;
                   6698:       vip=0.;
                   6699:       for(j=1; j<=nlstate;j++){
1.222     brouard  6700:        eip += eij[i][j][(int)age];
                   6701:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6702:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6703:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
1.126     brouard  6704:       }
                   6705:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6706:     }
                   6707:     fprintf(ficresstdeij,"\n");
1.218     brouard  6708:                
1.269     brouard  6709:     /* Variance of expectancies ij */          
1.126     brouard  6710:     fprintf(ficrescveij,"%3.0f",age );
                   6711:     for(i=1; i<=nlstate;i++)
                   6712:       for(j=1; j<=nlstate;j++){
1.222     brouard  6713:        cptj= (j-1)*nlstate+i;
                   6714:        for(i2=1; i2<=nlstate;i2++)
                   6715:          for(j2=1; j2<=nlstate;j2++){
                   6716:            cptj2= (j2-1)*nlstate+i2;
                   6717:            if(cptj2 <= cptj)
                   6718:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6719:          }
1.126     brouard  6720:       }
                   6721:     fprintf(ficrescveij,"\n");
1.218     brouard  6722:                
1.126     brouard  6723:   }
                   6724:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6725:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6726:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6727:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6728:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6729:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6730:   printf("\n");
                   6731:   fprintf(ficlog,"\n");
1.218     brouard  6732:        
1.126     brouard  6733:   free_vector(xm,1,npar);
                   6734:   free_vector(xp,1,npar);
                   6735:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6736:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6737:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6738: }
1.218     brouard  6739:  
1.126     brouard  6740: /************ Variance ******************/
1.235     brouard  6741:  void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[], int nres)
1.218     brouard  6742:  {
1.279     brouard  6743:    /** Variance of health expectancies 
                   6744:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6745:     * double **newm;
                   6746:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6747:     */
1.218     brouard  6748:   
                   6749:    /* int movingaverage(); */
                   6750:    double **dnewm,**doldm;
                   6751:    double **dnewmp,**doldmp;
                   6752:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6753:    int first=0;
1.218     brouard  6754:    int k;
                   6755:    double *xp;
1.279     brouard  6756:    double **gp, **gm;  /**< for var eij */
                   6757:    double ***gradg, ***trgradg; /**< for var eij */
                   6758:    double **gradgp, **trgradgp; /**< for var p point j */
                   6759:    double *gpp, *gmp; /**< for var p point j */
                   6760:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6761:    double ***p3mat;
                   6762:    double age,agelim, hf;
                   6763:    /* double ***mobaverage; */
                   6764:    int theta;
                   6765:    char digit[4];
                   6766:    char digitp[25];
                   6767: 
                   6768:    char fileresprobmorprev[FILENAMELENGTH];
                   6769: 
                   6770:    if(popbased==1){
                   6771:      if(mobilav!=0)
                   6772:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6773:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6774:    }
                   6775:    else 
                   6776:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6777: 
1.218     brouard  6778:    /* if (mobilav!=0) { */
                   6779:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6780:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6781:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6782:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6783:    /*   } */
                   6784:    /* } */
                   6785: 
                   6786:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6787:    sprintf(digit,"%-d",ij);
                   6788:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6789:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6790:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6791:    strcat(fileresprobmorprev,fileresu);
                   6792:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6793:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6794:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6795:    }
                   6796:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6797:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6798:    pstamp(ficresprobmorprev);
                   6799:    fprintf(ficresprobmorprev,"# probabilities of dying before estepm=%d months for people of exact age and weighted probabilities w1*p1j+w2*p2j+... stand dev in()\n",estepm);
1.238     brouard  6800:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6801: 
                   6802:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6803:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6804:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6805:    /* } */
                   6806:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   6807:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6808:    }
1.337     brouard  6809:    /* for(j=1;j<=cptcoveff;j++)  */
                   6810:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6811:    fprintf(ficresprobmorprev,"\n");
                   6812: 
1.218     brouard  6813:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6814:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6815:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6816:      for(i=1; i<=nlstate;i++)
                   6817:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6818:    }  
                   6819:    fprintf(ficresprobmorprev,"\n");
                   6820:   
                   6821:    fprintf(ficgp,"\n# Routine varevsij");
                   6822:    fprintf(ficgp,"\nunset title \n");
                   6823:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6824:    fprintf(fichtm,"\n<li><h4> Computing probabilities of dying over estepm months as a weighted average (i.e global mortality independent of initial healh state)</h4></li>\n");
                   6825:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6826: 
1.218     brouard  6827:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6828:    pstamp(ficresvij);
                   6829:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6830:    if(popbased==1)
                   6831:      fprintf(ficresvij,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d\n",mobilav);
                   6832:    else
                   6833:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6834:    fprintf(ficresvij,"# Age");
                   6835:    for(i=1; i<=nlstate;i++)
                   6836:      for(j=1; j<=nlstate;j++)
                   6837:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6838:    fprintf(ficresvij,"\n");
                   6839: 
                   6840:    xp=vector(1,npar);
                   6841:    dnewm=matrix(1,nlstate,1,npar);
                   6842:    doldm=matrix(1,nlstate,1,nlstate);
                   6843:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6844:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6845: 
                   6846:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6847:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6848:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6849:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6850:   
1.218     brouard  6851:    if(estepm < stepm){
                   6852:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6853:    }
                   6854:    else  hstepm=estepm;   
                   6855:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6856:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6857:       nhstepm is the number of hstepm from age to agelim 
                   6858:       nstepm is the number of stepm from age to agelim. 
                   6859:       Look at function hpijx to understand why because of memory size limitations, 
                   6860:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6861:       survival function given by stepm (the optimization length). Unfortunately it
                   6862:       means that if the survival funtion is printed every two years of age and if
                   6863:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6864:       results. So we changed our mind and took the option of the best precision.
                   6865:    */
                   6866:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6867:    agelim = AGESUP;
                   6868:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6869:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6870:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6871:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6872:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6873:      gp=matrix(0,nhstepm,1,nlstate);
                   6874:      gm=matrix(0,nhstepm,1,nlstate);
                   6875:                
                   6876:                
                   6877:      for(theta=1; theta <=npar; theta++){
                   6878:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6879:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6880:        }
1.279     brouard  6881:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6882:        * returns into prlim .
1.288     brouard  6883:        */
1.242     brouard  6884:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6885: 
                   6886:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6887:        if (popbased==1) {
                   6888:         if(mobilav ==0){
                   6889:           for(i=1; i<=nlstate;i++)
                   6890:             prlim[i][i]=probs[(int)age][i][ij];
                   6891:         }else{ /* mobilav */ 
                   6892:           for(i=1; i<=nlstate;i++)
                   6893:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6894:         }
                   6895:        }
1.295     brouard  6896:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6897:        */                      
                   6898:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=0 to nhstepm */
1.292     brouard  6899:        /**< And for each alive state j, sums over i \f$ w^i_x {}{h}_p^{ij}x\f$, which are the probability
1.279     brouard  6900:        * at horizon h in state j including mortality.
                   6901:        */
1.218     brouard  6902:        for(j=1; j<= nlstate; j++){
                   6903:         for(h=0; h<=nhstepm; h++){
                   6904:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6905:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6906:         }
                   6907:        }
1.279     brouard  6908:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6909:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6910:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6911:        */
                   6912:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6913:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6914:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6915:        }
                   6916:        
                   6917:        /* Again with minus shift */
1.218     brouard  6918:                        
                   6919:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6920:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6921: 
1.242     brouard  6922:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6923:                        
                   6924:        if (popbased==1) {
                   6925:         if(mobilav ==0){
                   6926:           for(i=1; i<=nlstate;i++)
                   6927:             prlim[i][i]=probs[(int)age][i][ij];
                   6928:         }else{ /* mobilav */ 
                   6929:           for(i=1; i<=nlstate;i++)
                   6930:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6931:         }
                   6932:        }
                   6933:                        
1.235     brouard  6934:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6935:                        
                   6936:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6937:         for(h=0; h<=nhstepm; h++){
                   6938:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6939:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6940:         }
                   6941:        }
                   6942:        /* This for computing probability of death (h=1 means
                   6943:          computed over hstepm matrices product = hstepm*stepm months) 
                   6944:          as a weighted average of prlim.
                   6945:        */
                   6946:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6947:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6948:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6949:        }    
1.279     brouard  6950:        /* end shifting computations */
                   6951: 
                   6952:        /**< Computing gradient matrix at horizon h 
                   6953:        */
1.218     brouard  6954:        for(j=1; j<= nlstate; j++) /* vareij */
                   6955:         for(h=0; h<=nhstepm; h++){
                   6956:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6957:         }
1.279     brouard  6958:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6959:        */
                   6960:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6961:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6962:        }
                   6963:                        
                   6964:      } /* End theta */
1.279     brouard  6965:      
                   6966:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6967:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6968:                
                   6969:      for(h=0; h<=nhstepm; h++) /* veij */
                   6970:        for(j=1; j<=nlstate;j++)
                   6971:         for(theta=1; theta <=npar; theta++)
                   6972:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6973:                
                   6974:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6975:        for(theta=1; theta <=npar; theta++)
                   6976:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6977:      /**< as well as its transposed matrix 
                   6978:       */               
1.218     brouard  6979:                
                   6980:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6981:      for(i=1;i<=nlstate;i++)
                   6982:        for(j=1;j<=nlstate;j++)
                   6983:         vareij[i][j][(int)age] =0.;
1.279     brouard  6984: 
                   6985:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6986:       * and k (nhstepm) formula 15 of article
                   6987:       * Lievre-Brouard-Heathcote
                   6988:       */
                   6989:      
1.218     brouard  6990:      for(h=0;h<=nhstepm;h++){
                   6991:        for(k=0;k<=nhstepm;k++){
                   6992:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6993:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6994:         for(i=1;i<=nlstate;i++)
                   6995:           for(j=1;j<=nlstate;j++)
                   6996:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6997:        }
                   6998:      }
                   6999:                
1.279     brouard  7000:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7001:       * p.j overall mortality formula 49 but computed directly because
                   7002:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7003:       * wix is independent of theta.
                   7004:       */
1.218     brouard  7005:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7006:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7007:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7008:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7009:         varppt[j][i]=doldmp[j][i];
                   7010:      /* end ppptj */
                   7011:      /*  x centered again */
                   7012:                
1.242     brouard  7013:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  7014:                
                   7015:      if (popbased==1) {
                   7016:        if(mobilav ==0){
                   7017:         for(i=1; i<=nlstate;i++)
                   7018:           prlim[i][i]=probs[(int)age][i][ij];
                   7019:        }else{ /* mobilav */ 
                   7020:         for(i=1; i<=nlstate;i++)
                   7021:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7022:        }
                   7023:      }
                   7024:                
                   7025:      /* This for computing probability of death (h=1 means
                   7026:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7027:        as a weighted average of prlim.
                   7028:      */
1.235     brouard  7029:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  7030:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7031:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7032:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7033:      }    
                   7034:      /* end probability of death */
                   7035:                
                   7036:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7037:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7038:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7039:        for(i=1; i<=nlstate;i++){
                   7040:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7041:        }
                   7042:      } 
                   7043:      fprintf(ficresprobmorprev,"\n");
                   7044:                
                   7045:      fprintf(ficresvij,"%.0f ",age );
                   7046:      for(i=1; i<=nlstate;i++)
                   7047:        for(j=1; j<=nlstate;j++){
                   7048:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7049:        }
                   7050:      fprintf(ficresvij,"\n");
                   7051:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7052:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7053:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7054:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7055:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7056:    } /* End age */
                   7057:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7058:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7059:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7060:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7061:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7062:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7063:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7064:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7065:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7066:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7067:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7068:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7069:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7070:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7071:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7072:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7073:    fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7074:    /*  fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months and then divided by estepm and multiplied by %.0f in order to have the probability to die over a year <br> <img src=\"varmuptjgr%s%s.svg\"> <br>\n", stepm,YEARM,digitp,digit);
1.126     brouard  7075:     */
1.218     brouard  7076:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7077:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  7078: 
1.218     brouard  7079:    free_vector(xp,1,npar);
                   7080:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7081:    free_matrix(dnewm,1,nlstate,1,npar);
                   7082:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7083:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7084:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7085:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7086:    fclose(ficresprobmorprev);
                   7087:    fflush(ficgp);
                   7088:    fflush(fichtm); 
                   7089:  }  /* end varevsij */
1.126     brouard  7090: 
                   7091: /************ Variance of prevlim ******************/
1.269     brouard  7092:  void varprevlim(char fileresvpl[], FILE *ficresvpl, double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, char strstart[], int nres)
1.126     brouard  7093: {
1.205     brouard  7094:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  7095:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  7096: 
1.268     brouard  7097:   double **dnewmpar,**doldm;
1.126     brouard  7098:   int i, j, nhstepm, hstepm;
                   7099:   double *xp;
                   7100:   double *gp, *gm;
                   7101:   double **gradg, **trgradg;
1.208     brouard  7102:   double **mgm, **mgp;
1.126     brouard  7103:   double age,agelim;
                   7104:   int theta;
                   7105:   
                   7106:   pstamp(ficresvpl);
1.288     brouard  7107:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  7108:   fprintf(ficresvpl,"# Age ");
                   7109:   if(nresult >=1)
                   7110:     fprintf(ficresvpl," Result# ");
1.126     brouard  7111:   for(i=1; i<=nlstate;i++)
                   7112:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7113:   fprintf(ficresvpl,"\n");
                   7114: 
                   7115:   xp=vector(1,npar);
1.268     brouard  7116:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  7117:   doldm=matrix(1,nlstate,1,nlstate);
                   7118:   
                   7119:   hstepm=1*YEARM; /* Every year of age */
                   7120:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7121:   agelim = AGESUP;
                   7122:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7123:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7124:     if (stepm >= YEARM) hstepm=1;
                   7125:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7126:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  7127:     mgp=matrix(1,npar,1,nlstate);
                   7128:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  7129:     gp=vector(1,nlstate);
                   7130:     gm=vector(1,nlstate);
                   7131: 
                   7132:     for(theta=1; theta <=npar; theta++){
                   7133:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7134:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7135:       }
1.288     brouard  7136:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7137:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7138:       /* else */
                   7139:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7140:       for(i=1;i<=nlstate;i++){
1.126     brouard  7141:        gp[i] = prlim[i][i];
1.208     brouard  7142:        mgp[theta][i] = prlim[i][i];
                   7143:       }
1.126     brouard  7144:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7145:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  7146:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7147:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7148:       /* else */
                   7149:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  7150:       for(i=1;i<=nlstate;i++){
1.126     brouard  7151:        gm[i] = prlim[i][i];
1.208     brouard  7152:        mgm[theta][i] = prlim[i][i];
                   7153:       }
1.126     brouard  7154:       for(i=1;i<=nlstate;i++)
                   7155:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7156:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7157:     } /* End theta */
                   7158: 
                   7159:     trgradg =matrix(1,nlstate,1,npar);
                   7160: 
                   7161:     for(j=1; j<=nlstate;j++)
                   7162:       for(theta=1; theta <=npar; theta++)
                   7163:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7164:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7165:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7166:     /*   for(j=1; j<=nlstate;j++){ */
                   7167:     /*         printf(" %d ",j); */
                   7168:     /*         for(theta=1; theta <=npar; theta++) */
                   7169:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7170:     /*         printf("\n "); */
                   7171:     /*   } */
                   7172:     /* } */
                   7173:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7174:     /*   printf("\n gradg %d ",(int)age); */
                   7175:     /*   for(j=1; j<=nlstate;j++){ */
                   7176:     /*         printf("%d ",j); */
                   7177:     /*         for(theta=1; theta <=npar; theta++) */
                   7178:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7179:     /*         printf("\n "); */
                   7180:     /*   } */
                   7181:     /* } */
1.126     brouard  7182: 
                   7183:     for(i=1;i<=nlstate;i++)
                   7184:       varpl[i][(int)age] =0.;
1.209     brouard  7185:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7186:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7187:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7188:     }else{
1.268     brouard  7189:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7190:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7191:     }
1.126     brouard  7192:     for(i=1;i<=nlstate;i++)
                   7193:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7194: 
                   7195:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7196:     if(nresult >=1)
                   7197:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7198:     for(i=1; i<=nlstate;i++){
1.126     brouard  7199:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7200:       /* for(j=1;j<=nlstate;j++) */
                   7201:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7202:     }
1.126     brouard  7203:     fprintf(ficresvpl,"\n");
                   7204:     free_vector(gp,1,nlstate);
                   7205:     free_vector(gm,1,nlstate);
1.208     brouard  7206:     free_matrix(mgm,1,npar,1,nlstate);
                   7207:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7208:     free_matrix(gradg,1,npar,1,nlstate);
                   7209:     free_matrix(trgradg,1,nlstate,1,npar);
                   7210:   } /* End age */
                   7211: 
                   7212:   free_vector(xp,1,npar);
                   7213:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7214:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7215: 
                   7216: }
                   7217: 
                   7218: 
                   7219: /************ Variance of backprevalence limit ******************/
1.269     brouard  7220:  void varbrevlim(char fileresvbl[], FILE  *ficresvbl, double **varbpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **bprlim, double ftolpl, int mobilavproj, int *ncvyearp, int ij, char strstart[], int nres)
1.268     brouard  7221: {
                   7222:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7223:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7224: 
                   7225:   double **dnewmpar,**doldm;
                   7226:   int i, j, nhstepm, hstepm;
                   7227:   double *xp;
                   7228:   double *gp, *gm;
                   7229:   double **gradg, **trgradg;
                   7230:   double **mgm, **mgp;
                   7231:   double age,agelim;
                   7232:   int theta;
                   7233:   
                   7234:   pstamp(ficresvbl);
                   7235:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7236:   fprintf(ficresvbl,"# Age ");
                   7237:   if(nresult >=1)
                   7238:     fprintf(ficresvbl," Result# ");
                   7239:   for(i=1; i<=nlstate;i++)
                   7240:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7241:   fprintf(ficresvbl,"\n");
                   7242: 
                   7243:   xp=vector(1,npar);
                   7244:   dnewmpar=matrix(1,nlstate,1,npar);
                   7245:   doldm=matrix(1,nlstate,1,nlstate);
                   7246:   
                   7247:   hstepm=1*YEARM; /* Every year of age */
                   7248:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7249:   agelim = AGEINF;
                   7250:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7251:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7252:     if (stepm >= YEARM) hstepm=1;
                   7253:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7254:     gradg=matrix(1,npar,1,nlstate);
                   7255:     mgp=matrix(1,npar,1,nlstate);
                   7256:     mgm=matrix(1,npar,1,nlstate);
                   7257:     gp=vector(1,nlstate);
                   7258:     gm=vector(1,nlstate);
                   7259: 
                   7260:     for(theta=1; theta <=npar; theta++){
                   7261:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7262:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7263:       }
                   7264:       if(mobilavproj > 0 )
                   7265:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7266:       else
                   7267:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7268:       for(i=1;i<=nlstate;i++){
                   7269:        gp[i] = bprlim[i][i];
                   7270:        mgp[theta][i] = bprlim[i][i];
                   7271:       }
                   7272:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7273:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7274:        if(mobilavproj > 0 )
                   7275:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7276:        else
                   7277:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7278:       for(i=1;i<=nlstate;i++){
                   7279:        gm[i] = bprlim[i][i];
                   7280:        mgm[theta][i] = bprlim[i][i];
                   7281:       }
                   7282:       for(i=1;i<=nlstate;i++)
                   7283:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7284:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7285:     } /* End theta */
                   7286: 
                   7287:     trgradg =matrix(1,nlstate,1,npar);
                   7288: 
                   7289:     for(j=1; j<=nlstate;j++)
                   7290:       for(theta=1; theta <=npar; theta++)
                   7291:        trgradg[j][theta]=gradg[theta][j];
                   7292:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7293:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7294:     /*   for(j=1; j<=nlstate;j++){ */
                   7295:     /*         printf(" %d ",j); */
                   7296:     /*         for(theta=1; theta <=npar; theta++) */
                   7297:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7298:     /*         printf("\n "); */
                   7299:     /*   } */
                   7300:     /* } */
                   7301:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7302:     /*   printf("\n gradg %d ",(int)age); */
                   7303:     /*   for(j=1; j<=nlstate;j++){ */
                   7304:     /*         printf("%d ",j); */
                   7305:     /*         for(theta=1; theta <=npar; theta++) */
                   7306:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7307:     /*         printf("\n "); */
                   7308:     /*   } */
                   7309:     /* } */
                   7310: 
                   7311:     for(i=1;i<=nlstate;i++)
                   7312:       varbpl[i][(int)age] =0.;
                   7313:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7314:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7315:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7316:     }else{
                   7317:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7318:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7319:     }
                   7320:     for(i=1;i<=nlstate;i++)
                   7321:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7322: 
                   7323:     fprintf(ficresvbl,"%.0f ",age );
                   7324:     if(nresult >=1)
                   7325:       fprintf(ficresvbl,"%d ",nres );
                   7326:     for(i=1; i<=nlstate;i++)
                   7327:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7328:     fprintf(ficresvbl,"\n");
                   7329:     free_vector(gp,1,nlstate);
                   7330:     free_vector(gm,1,nlstate);
                   7331:     free_matrix(mgm,1,npar,1,nlstate);
                   7332:     free_matrix(mgp,1,npar,1,nlstate);
                   7333:     free_matrix(gradg,1,npar,1,nlstate);
                   7334:     free_matrix(trgradg,1,nlstate,1,npar);
                   7335:   } /* End age */
                   7336: 
                   7337:   free_vector(xp,1,npar);
                   7338:   free_matrix(doldm,1,nlstate,1,npar);
                   7339:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7340: 
                   7341: }
                   7342: 
                   7343: /************ Variance of one-step probabilities  ******************/
                   7344: void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
1.222     brouard  7345:  {
                   7346:    int i, j=0,  k1, l1, tj;
                   7347:    int k2, l2, j1,  z1;
                   7348:    int k=0, l;
                   7349:    int first=1, first1, first2;
1.326     brouard  7350:    int nres=0; /* New */
1.222     brouard  7351:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7352:    double **dnewm,**doldm;
                   7353:    double *xp;
                   7354:    double *gp, *gm;
                   7355:    double **gradg, **trgradg;
                   7356:    double **mu;
                   7357:    double age, cov[NCOVMAX+1];
                   7358:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7359:    int theta;
                   7360:    char fileresprob[FILENAMELENGTH];
                   7361:    char fileresprobcov[FILENAMELENGTH];
                   7362:    char fileresprobcor[FILENAMELENGTH];
                   7363:    double ***varpij;
                   7364: 
                   7365:    strcpy(fileresprob,"PROB_"); 
                   7366:    strcat(fileresprob,fileres);
                   7367:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7368:      printf("Problem with resultfile: %s\n", fileresprob);
                   7369:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7370:    }
                   7371:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7372:    strcat(fileresprobcov,fileresu);
                   7373:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7374:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7375:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7376:    }
                   7377:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7378:    strcat(fileresprobcor,fileresu);
                   7379:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7380:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7381:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7382:    }
                   7383:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7384:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7385:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7386:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7387:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7388:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7389:    pstamp(ficresprob);
                   7390:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7391:    fprintf(ficresprob,"# Age");
                   7392:    pstamp(ficresprobcov);
                   7393:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7394:    fprintf(ficresprobcov,"# Age");
                   7395:    pstamp(ficresprobcor);
                   7396:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7397:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7398: 
                   7399: 
1.222     brouard  7400:    for(i=1; i<=nlstate;i++)
                   7401:      for(j=1; j<=(nlstate+ndeath);j++){
                   7402:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7403:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7404:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7405:      }  
                   7406:    /* fprintf(ficresprob,"\n");
                   7407:       fprintf(ficresprobcov,"\n");
                   7408:       fprintf(ficresprobcor,"\n");
                   7409:    */
                   7410:    xp=vector(1,npar);
                   7411:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7412:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7413:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7414:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7415:    first=1;
                   7416:    fprintf(ficgp,"\n# Routine varprob");
                   7417:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7418:    fprintf(fichtm,"\n");
                   7419: 
1.288     brouard  7420:    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back. File %s</li>\n",optionfilehtmcov,optionfilehtmcov);
1.222     brouard  7421:    fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
                   7422:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7423: and drawn. It helps understanding how is the covariance between two incidences.\
                   7424:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7425:    fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
1.126     brouard  7426: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7427: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7428: standard deviations wide on each axis. <br>\
                   7429:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7430:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7431: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7432: 
1.222     brouard  7433:    cov[1]=1;
                   7434:    /* tj=cptcoveff; */
1.225     brouard  7435:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7436:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7437:    j1=0;
1.332     brouard  7438: 
                   7439:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7440:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  7441:      /* printf("Varprob  TKresult[nres]=%d j1=%d, nres=%d, cptcovn=%d, cptcoveff=%d tj=%d cptcovs=%d\n",  TKresult[nres], j1, nres, cptcovn, cptcoveff, tj, cptcovs); */
1.332     brouard  7442:      if(tj != 1 && TKresult[nres]!= j1)
                   7443:        continue;
                   7444: 
                   7445:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7446:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7447:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7448:      if  (cptcovn>0) {
1.334     brouard  7449:        fprintf(ficresprob, "\n#********** Variable ");
                   7450:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7451:        fprintf(ficgp, "\n#********** Variable ");
                   7452:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7453:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7454: 
                   7455:        /* Including quantitative variables of the resultline to be done */
                   7456:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343   ! brouard  7457:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  7458:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7459:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
1.334     brouard  7460:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7461:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7462:             fprintf(ficresprob,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7463:             fprintf(ficresprobcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7464:             fprintf(ficgp,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7465:             fprintf(fichtmcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7466:             fprintf(ficresprobcor,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7467:             fprintf(ficresprob,"fixed ");
                   7468:             fprintf(ficresprobcov,"fixed ");
                   7469:             fprintf(ficgp,"fixed ");
                   7470:             fprintf(fichtmcov,"fixed ");
                   7471:             fprintf(ficresprobcor,"fixed ");
                   7472:           }else{
                   7473:             fprintf(ficresprob,"varyi ");
                   7474:             fprintf(ficresprobcov,"varyi ");
                   7475:             fprintf(ficgp,"varyi ");
                   7476:             fprintf(fichtmcov,"varyi ");
                   7477:             fprintf(ficresprobcor,"varyi ");
                   7478:           }
                   7479:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7480:           /* For each selected (single) quantitative value */
1.337     brouard  7481:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7482:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7483:             fprintf(ficresprob,"fixed ");
                   7484:             fprintf(ficresprobcov,"fixed ");
                   7485:             fprintf(ficgp,"fixed ");
                   7486:             fprintf(fichtmcov,"fixed ");
                   7487:             fprintf(ficresprobcor,"fixed ");
                   7488:           }else{
                   7489:             fprintf(ficresprob,"varyi ");
                   7490:             fprintf(ficresprobcov,"varyi ");
                   7491:             fprintf(ficgp,"varyi ");
                   7492:             fprintf(fichtmcov,"varyi ");
                   7493:             fprintf(ficresprobcor,"varyi ");
                   7494:           }
                   7495:         }else{
                   7496:           printf("Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   7497:           fprintf(ficlog,"Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   7498:           exit(1);
                   7499:         }
                   7500:        } /* End loop on variable of this resultline */
                   7501:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7502:        fprintf(ficresprob, "**********\n#\n");
                   7503:        fprintf(ficresprobcov, "**********\n#\n");
                   7504:        fprintf(ficgp, "**********\n#\n");
                   7505:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7506:        fprintf(ficresprobcor, "**********\n#");    
                   7507:        if(invalidvarcomb[j1]){
                   7508:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7509:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7510:         continue;
                   7511:        }
                   7512:      }
                   7513:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7514:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7515:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7516:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7517:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7518:        cov[2]=age;
                   7519:        if(nagesqr==1)
                   7520:         cov[3]= age*age;
1.334     brouard  7521:        /* New code end of combination but for each resultline */
                   7522:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7523:         if(Typevar[k1]==1){ /* A product with age */
                   7524:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7525:         }else{
1.334     brouard  7526:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7527:         }
1.334     brouard  7528:        }/* End of loop on model equation */
                   7529: /* Old code */
                   7530:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7531:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7532:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7533:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7534:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7535:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7536:        /*                                                                  * 1  1 1 1 1 */
                   7537:        /*                                                                  * 2  2 1 1 1 */
                   7538:        /*                                                                  * 3  1 2 1 1 */
                   7539:        /*                                                                  *\/ */
                   7540:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7541:        /* } */
                   7542:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7543:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7544:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7545:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7546:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7547:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7548:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7549:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7550:        /*         printf("Internal IMaCh error, don't know which value for quantitative covariate with age, Tage[k]%d, k=%d, Tvar[Tage[k]]=V%d, age=%d\n",Tage[k],k ,Tvar[Tage[k]], (int)cov[2]); */
                   7551:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7552:        /*         /\* exit(1); *\/ */
                   7553:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7554:        /*       } */
                   7555:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7556:        /* } */
                   7557:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7558:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7559:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7560:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])]; */
                   7561:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7562:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7563:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7564:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7565:        /*         } */
                   7566:        /*       }else{ */
                   7567:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7568:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7569:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7570:        /*         }else{ */
                   7571:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7572:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7573:        /*         } */
                   7574:        /*       } */
                   7575:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7576:        /* } */                 
1.326     brouard  7577: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7578:        for(theta=1; theta <=npar; theta++){
                   7579:         for(i=1; i<=npar; i++)
                   7580:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7581:                                
1.222     brouard  7582:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7583:                                
1.222     brouard  7584:         k=0;
                   7585:         for(i=1; i<= (nlstate); i++){
                   7586:           for(j=1; j<=(nlstate+ndeath);j++){
                   7587:             k=k+1;
                   7588:             gp[k]=pmmij[i][j];
                   7589:           }
                   7590:         }
1.220     brouard  7591:                                
1.222     brouard  7592:         for(i=1; i<=npar; i++)
                   7593:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7594:                                
1.222     brouard  7595:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7596:         k=0;
                   7597:         for(i=1; i<=(nlstate); i++){
                   7598:           for(j=1; j<=(nlstate+ndeath);j++){
                   7599:             k=k+1;
                   7600:             gm[k]=pmmij[i][j];
                   7601:           }
                   7602:         }
1.220     brouard  7603:                                
1.222     brouard  7604:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7605:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7606:        }
1.126     brouard  7607: 
1.222     brouard  7608:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7609:         for(theta=1; theta <=npar; theta++)
                   7610:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7611:                        
1.222     brouard  7612:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7613:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7614:                        
1.222     brouard  7615:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7616:                        
1.222     brouard  7617:        k=0;
                   7618:        for(i=1; i<=(nlstate); i++){
                   7619:         for(j=1; j<=(nlstate+ndeath);j++){
                   7620:           k=k+1;
                   7621:           mu[k][(int) age]=pmmij[i][j];
                   7622:         }
                   7623:        }
                   7624:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7625:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7626:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7627:                        
1.222     brouard  7628:        /*printf("\n%d ",(int)age);
                   7629:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7630:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7631:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7632:         }*/
1.220     brouard  7633:                        
1.222     brouard  7634:        fprintf(ficresprob,"\n%d ",(int)age);
                   7635:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7636:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7637:                        
1.222     brouard  7638:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7639:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7640:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7641:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7642:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7643:        }
                   7644:        i=0;
                   7645:        for (k=1; k<=(nlstate);k++){
                   7646:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7647:           i++;
                   7648:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7649:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7650:           for (j=1; j<=i;j++){
                   7651:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7652:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7653:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7654:           }
                   7655:         }
                   7656:        }/* end of loop for state */
                   7657:      } /* end of loop for age */
                   7658:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7659:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7660:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7661:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7662:     
                   7663:      /* Confidence intervalle of pij  */
                   7664:      /*
                   7665:        fprintf(ficgp,"\nunset parametric;unset label");
                   7666:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7667:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7668:        fprintf(fichtm,"\n<br>Probability with  confidence intervals expressed in year<sup>-1</sup> :<a href=\"pijgr%s.png\">pijgr%s.png</A>, ",optionfilefiname,optionfilefiname);
                   7669:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7670:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7671:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7672:      */
                   7673:                
                   7674:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7675:      first1=1;first2=2;
                   7676:      for (k2=1; k2<=(nlstate);k2++){
                   7677:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7678:         if(l2==k2) continue;
                   7679:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7680:         for (k1=1; k1<=(nlstate);k1++){
                   7681:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7682:             if(l1==k1) continue;
                   7683:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7684:             if(i<=j) continue;
                   7685:             for (age=bage; age<=fage; age ++){ 
                   7686:               if ((int)age %5==0){
                   7687:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7688:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7689:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7690:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7691:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7692:                 c12=cv12/sqrt(v1*v2);
                   7693:                 /* Computing eigen value of matrix of covariance */
                   7694:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7695:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7696:                 if ((lc2 <0) || (lc1 <0) ){
                   7697:                   if(first2==1){
                   7698:                     first1=0;
                   7699:                     printf("Strange: j1=%d One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Probably WRONG RESULTS. See log file for details...\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
                   7700:                   }
                   7701:                   fprintf(ficlog,"Strange: j1=%d One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Probably WRONG RESULTS.\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);fflush(ficlog);
                   7702:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7703:                   /* lc2=fabs(lc2); */
                   7704:                 }
1.220     brouard  7705:                                                                
1.222     brouard  7706:                 /* Eigen vectors */
1.280     brouard  7707:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7708:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7709:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7710:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7711:                 }else
                   7712:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7713:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7714:                 v21=(lc1-v1)/cv12*v11;
                   7715:                 v12=-v21;
                   7716:                 v22=v11;
                   7717:                 tnalp=v21/v11;
                   7718:                 if(first1==1){
                   7719:                   first1=0;
                   7720:                   printf("%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tang %.3f\nOthers in log...\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
                   7721:                 }
                   7722:                 fprintf(ficlog,"%d %d%d-%d%d mu %.4e %.4e Var %.4e %.4e cor %.3f cov %.4e Eig %.3e %.3e 1stv %.3f %.3f tan %.3f\n",(int) age,k1,l1,k2,l2,mu1,mu2,v1,v2,c12,cv12,lc1,lc2,v11,v21,tnalp);
                   7723:                 /*printf(fignu*/
                   7724:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7725:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7726:                 if(first==1){
                   7727:                   first=0;
                   7728:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7729:                   fprintf(ficgp,"\nset parametric;unset label");
                   7730:                   fprintf(ficgp,"\nset log y;set log x; set xlabel \"p%1d%1d (year-1)\";set ylabel \"p%1d%1d (year-1)\"",k1,l1,k2,l2);
                   7731:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7732:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7733:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7734: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7735:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7736:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7737:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7738:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7739:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7740:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7741:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7742:                   fprintf(ficgp,"\nplot [-pi:pi] %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not",      \
1.280     brouard  7743:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7744:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7745:                 }else{
                   7746:                   first=0;
                   7747:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7748:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7749:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7750:                   fprintf(ficgp,"\nreplot %11.3e+ %.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)), %11.3e +%.3f*(%11.3e*%11.3e*cos(t)+%11.3e*%11.3e*sin(t)) not", \
1.266     brouard  7751:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7752:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7753:                 }/* if first */
                   7754:               } /* age mod 5 */
                   7755:             } /* end loop age */
                   7756:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7757:             first=1;
                   7758:           } /*l12 */
                   7759:         } /* k12 */
                   7760:        } /*l1 */
                   7761:      }/* k1 */
1.332     brouard  7762:    }  /* loop on combination of covariates j1 */
1.326     brouard  7763:    } /* loop on nres */
1.222     brouard  7764:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7765:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7766:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7767:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7768:    free_vector(xp,1,npar);
                   7769:    fclose(ficresprob);
                   7770:    fclose(ficresprobcov);
                   7771:    fclose(ficresprobcor);
                   7772:    fflush(ficgp);
                   7773:    fflush(fichtmcov);
                   7774:  }
1.126     brouard  7775: 
                   7776: 
                   7777: /******************* Printing html file ***********/
1.201     brouard  7778: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7779:                  int lastpass, int stepm, int weightopt, char model[],\
                   7780:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7781:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7782:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7783:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7784:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7785:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7786:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7787:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7788: </ul>");
1.319     brouard  7789: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7790: /* </ul>", model); */
1.214     brouard  7791:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7792:    fprintf(fichtm,"<li>- Observed frequency between two states (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file)<br/>\n",
                   7793:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7794:    fprintf(fichtm,"<li> - Observed prevalence (cross-sectional prevalence) in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
1.213     brouard  7795:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7796:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7797:    fprintf(fichtm,"\
                   7798:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7799:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7800:    fprintf(fichtm,"\
1.217     brouard  7801:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7802:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7803:    fprintf(fichtm,"\
1.288     brouard  7804:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7805:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7806:    fprintf(fichtm,"\
1.288     brouard  7807:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7808:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7809:    fprintf(fichtm,"\
1.211     brouard  7810:  - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
1.126     brouard  7811:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7812:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7813:    if(prevfcast==1){
                   7814:      fprintf(fichtm,"\
                   7815:  - Prevalence projections by age and states:                           \
1.201     brouard  7816:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7817:    }
1.126     brouard  7818: 
                   7819: 
1.225     brouard  7820:    m=pow(2,cptcoveff);
1.222     brouard  7821:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7822: 
1.317     brouard  7823:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7824: 
                   7825:    jj1=0;
                   7826: 
                   7827:    fprintf(fichtm," \n<ul>");
1.337     brouard  7828:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7829:      /* k1=nres; */
1.338     brouard  7830:      k1=TKresult[nres];
                   7831:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7832:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7833:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7834:    /*     continue; */
1.264     brouard  7835:      jj1++;
                   7836:      if (cptcovn > 0) {
                   7837:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7838:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7839:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7840:        }
1.337     brouard  7841:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7842:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7843:        /* } */
                   7844:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7845:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7846:        /* } */
1.264     brouard  7847:        fprintf(fichtm,"\">");
                   7848:        
                   7849:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7850:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7851:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7852:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7853:        }
1.337     brouard  7854:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7855:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7856:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7857:        /* } */
                   7858:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7859:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7860:        /* } */
1.264     brouard  7861:        if(invalidvarcomb[k1]){
                   7862:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7863:         continue;
                   7864:        }
                   7865:        fprintf(fichtm,"</a></li>");
                   7866:      } /* cptcovn >0 */
                   7867:    }
1.317     brouard  7868:    fprintf(fichtm," \n</ul>");
1.264     brouard  7869: 
1.222     brouard  7870:    jj1=0;
1.237     brouard  7871: 
1.337     brouard  7872:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7873:      /* k1=nres; */
1.338     brouard  7874:      k1=TKresult[nres];
                   7875:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7876:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7877:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7878:    /*     continue; */
1.220     brouard  7879: 
1.222     brouard  7880:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7881:      jj1++;
                   7882:      if (cptcovn > 0) {
1.264     brouard  7883:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7884:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7885:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7886:        }
1.337     brouard  7887:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7888:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7889:        /* } */
1.264     brouard  7890:        fprintf(fichtm,"\"</a>");
                   7891:  
1.222     brouard  7892:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7893:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7894:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7895:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7896:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7897:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7898:        }
1.230     brouard  7899:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7900:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7901:        if(invalidvarcomb[k1]){
                   7902:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7903:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7904:         continue;
                   7905:        }
                   7906:      }
                   7907:      /* aij, bij */
1.259     brouard  7908:      fprintf(fichtm,"<br>- Logit model (yours is: logit(pij)=log(pij/pii)= aij+ bij age+%s) as a function of age: <a href=\"%s_%d-1-%d.svg\">%s_%d-1-%d.svg</a><br> \
1.241     brouard  7909: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
1.222     brouard  7910:      /* Pij */
1.241     brouard  7911:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2-%d.svg\">%s_%d-2-%d.svg</a><br> \
                   7912: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
1.222     brouard  7913:      /* Quasi-incidences */
                   7914:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.220     brouard  7915:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7916:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
1.241     brouard  7917: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3-%d.svg\">%s_%d-3-%d.svg</a><br> \
                   7918: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
1.222     brouard  7919:      /* Survival functions (period) in state j */
                   7920:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7921:        fprintf(fichtm,"<br>\n- Survival functions in state %d. And probability to be observed in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   7922:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7923:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7924:      }
                   7925:      /* State specific survival functions (period) */
                   7926:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7927:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7928:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7929:  <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> ", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   7930:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7931:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7932:      }
1.288     brouard  7933:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7934:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7935:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability for a person being in state (1 to %d) at different ages, to be in state %d some years after. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.338     brouard  7936:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7937:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7938:      }
1.296     brouard  7939:      if(prevbcast==1){
1.288     brouard  7940:        /* Backward prevalence in each health state */
1.222     brouard  7941:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7942:         fprintf(fichtm,"<br>\n- Convergence to mixed (stable) back prevalence in state %d. Or probability for a person to be in state %d at a younger age, knowing that she/he was in state (1 to %d) at different older ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   7943:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7944:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7945:        }
1.217     brouard  7946:      }
1.222     brouard  7947:      if(prevfcast==1){
1.288     brouard  7948:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7949:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7950:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), from year %.1f up to year %.1f tending to period (stable) forward prevalence in state %d. Or probability to be in state %d being in an observed weighted state (from 1 to %d). <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   7951:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7952:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7953:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7954:        }
                   7955:      }
1.296     brouard  7956:      if(prevbcast==1){
1.268     brouard  7957:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7958:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7959:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7960:  from year %.1f up to year %.1f (probably close to stable [mixed] back prevalence in state %d (randomness in cross-sectional prevalence is not taken into \
                   7961:  account but can visually be appreciated). Or probability to have been in an state %d, knowing that the person was in either state (1 or %d) \
1.314     brouard  7962: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateback1, dateback2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7963:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7964:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7965:        }
                   7966:      }
1.220     brouard  7967:         
1.222     brouard  7968:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7969:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
                   7970:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7971:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7972:      }
                   7973:      /* } /\* end i1 *\/ */
1.337     brouard  7974:    }/* End k1=nres */
1.222     brouard  7975:    fprintf(fichtm,"</ul>");
1.126     brouard  7976: 
1.222     brouard  7977:    fprintf(fichtm,"\
1.126     brouard  7978: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7979:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7980:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
1.197     brouard  7981: But because parameters are usually highly correlated (a higher incidence of disability \
                   7982: and a higher incidence of recovery can give very close observed transition) it might \
                   7983: be very useful to look not only at linear confidence intervals estimated from the \
                   7984: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7985: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7986: covariance matrix of the one-step probabilities. \
                   7987: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7988: 
1.222     brouard  7989:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7990:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7991:    fprintf(fichtm,"\
1.126     brouard  7992:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7993:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7994: 
1.222     brouard  7995:    fprintf(fichtm,"\
1.126     brouard  7996:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7997:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7998:    fprintf(fichtm,"\
1.126     brouard  7999:  - Variances and covariances of health expectancies by age and <b>initial health status</b> (cov(e<sup>ij</sup>,e<sup>kl</sup>)(estepm=%2d months): \
                   8000:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8001:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  8002:    fprintf(fichtm,"\
1.126     brouard  8003:  - (a) Health expectancies by health status at initial age (e<sup>ij</sup>) and standard errors (in parentheses) (b) life expectancies and standard errors (e<sup>i.</sup>=e<sup>i1</sup>+e<sup>i2</sup>+...)(estepm=%2d months): \
                   8004:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  8005:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  8006:    fprintf(fichtm,"\
1.288     brouard  8007:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the forward (period) prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.222     brouard  8008:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8009:    fprintf(fichtm,"\
1.128     brouard  8010:  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  8011:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8012:    fprintf(fichtm,"\
1.288     brouard  8013:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  8014:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  8015: 
                   8016: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8017: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8018: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8019: /*     <br>",fileres,fileres,fileres,fileres); */
                   8020: /*  else  */
1.338     brouard  8021: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=1+age+%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
1.222     brouard  8022:    fflush(fichtm);
1.126     brouard  8023: 
1.225     brouard  8024:    m=pow(2,cptcoveff);
1.222     brouard  8025:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  8026: 
1.317     brouard  8027:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8028: 
                   8029:   jj1=0;
                   8030: 
                   8031:    fprintf(fichtm," \n<ul>");
1.337     brouard  8032:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8033:      /* k1=nres; */
1.338     brouard  8034:      k1=TKresult[nres];
1.337     brouard  8035:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8036:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8037:      /*   continue; */
1.317     brouard  8038:      jj1++;
                   8039:      if (cptcovn > 0) {
                   8040:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  8041:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8042:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8043:        }
                   8044:        fprintf(fichtm,"\">");
                   8045:        
                   8046:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8047:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  8048:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8049:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8050:        }
                   8051:        if(invalidvarcomb[k1]){
                   8052:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8053:         continue;
                   8054:        }
                   8055:        fprintf(fichtm,"</a></li>");
                   8056:      } /* cptcovn >0 */
1.337     brouard  8057:    } /* End nres */
1.317     brouard  8058:    fprintf(fichtm," \n</ul>");
                   8059: 
1.222     brouard  8060:    jj1=0;
1.237     brouard  8061: 
1.241     brouard  8062:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8063:      /* k1=nres; */
1.338     brouard  8064:      k1=TKresult[nres];
                   8065:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8066:      /* for(k1=1; k1<=m;k1++){ */
                   8067:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8068:      /*   continue; */
1.222     brouard  8069:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8070:      jj1++;
1.126     brouard  8071:      if (cptcovn > 0) {
1.317     brouard  8072:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  8073:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8074:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  8075:        }
                   8076:        fprintf(fichtm,"\"</a>");
                   8077:        
1.126     brouard  8078:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  8079:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8080:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8081:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  8082:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  8083:        }
1.237     brouard  8084: 
1.338     brouard  8085:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  8086: 
1.222     brouard  8087:        if(invalidvarcomb[k1]){
                   8088:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8089:         continue;
                   8090:        }
1.337     brouard  8091:      } /* If cptcovn >0 */
1.126     brouard  8092:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  8093:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  8094: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8095:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8096:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  8097:      }
                   8098:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  8099: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  8100: true period expectancies (those weighted with period prevalences are also\
                   8101:  drawn in addition to the population based expectancies computed using\
1.314     brouard  8102:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>",nlstate, subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
                   8103:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8104:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  8105:      /* } /\* end i1 *\/ */
1.241     brouard  8106:   }/* End nres */
1.222     brouard  8107:    fprintf(fichtm,"</ul>");
                   8108:    fflush(fichtm);
1.126     brouard  8109: }
                   8110: 
                   8111: /******************* Gnuplot file **************/
1.296     brouard  8112: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double bage, double fage , int prevfcast, int prevbcast, char pathc[], double p[], int offyear, int offbyear){
1.126     brouard  8113: 
                   8114:   char dirfileres[132],optfileres[132];
1.264     brouard  8115:   char gplotcondition[132], gplotlabel[132];
1.343   ! brouard  8116:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
1.211     brouard  8117:   int lv=0, vlv=0, kl=0;
1.130     brouard  8118:   int ng=0;
1.201     brouard  8119:   int vpopbased;
1.223     brouard  8120:   int ioffset; /* variable offset for columns */
1.270     brouard  8121:   int iyearc=1; /* variable column for year of projection  */
                   8122:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  8123:   int nres=0; /* Index of resultline */
1.266     brouard  8124:   int istart=1; /* For starting graphs in projections */
1.219     brouard  8125: 
1.126     brouard  8126: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8127: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8128: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8129: /*   } */
                   8130: 
                   8131:   /*#ifdef windows */
                   8132:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  8133:   /*#endif */
1.225     brouard  8134:   m=pow(2,cptcoveff);
1.126     brouard  8135: 
1.274     brouard  8136:   /* diagram of the model */
                   8137:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8138:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8139:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8140:   fprintf(ficgp,"\n#Peripheral arrows\nset for [i=1:%d] for [j=1:%d] arrow i*10+j from cos(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.95*(cos(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0) - cos(pi*((1-(%d/2)*2./%d)/2+(j-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta2:0)), -0.95*(sin(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) - sin(pi*((1-(%d/2)*2./%d)/2+(j-1)*2./%d))+( i!=j?(i-j)/abs(i-j)*delta2:0)) ls (i < j? 1:2)\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
                   8141: 
1.343   ! brouard  8142:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] for [j=1:%d] arrow (%d+1)*10+i from cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.80*(cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0)  ), -0.80*(sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) + yoff ) ls 4\n",nlstate, nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
1.274     brouard  8143:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8144:   fprintf(ficgp,"\n#States labels, starting from 2 (2-i) instead of (1-i), was (i-1)\nset for [i=1:%d] label i sprintf(\"State %%d\",i) center at cos(pi*((1-(%d/2)*2./%d)/2+(2-i)*2./%d)), yoff+sin(pi*((1-(%d/2)*2./%d)/2+(2-i)*2./%d)) font \"helvetica, 16\" tc rgbcolor \"blue\"\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
                   8145:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8146:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8147:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8148:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8149: 
1.202     brouard  8150:   /* Contribution to likelihood */
                   8151:   /* Plot the probability implied in the likelihood */
1.223     brouard  8152:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8153:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8154:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8155:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8156: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8157:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8158: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8159:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8160:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8161:   fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
                   8162:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8163:   fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
                   8164:   for (i=1; i<= nlstate ; i ++) {
                   8165:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8166:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8167:     fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
                   8168:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8169:       fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
                   8170:     }
                   8171:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8172:   }
                   8173:   /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */               
                   8174:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8175:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8176:   fprintf(ficgp,"\nset out;unset log\n");
                   8177:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8178: 
1.343   ! brouard  8179:   /* Plot the probability implied in the likelihood by covariate value */
        !          8180:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
        !          8181:   /* if(debugILK==1){ */
        !          8182:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
        !          8183:     kvar=Tvar[TvarFind[kf]]; /* variable */
        !          8184:     k=18+Tvar[TvarFind[kf]];/*offset because there are 18 columns in the ILK_ file */
        !          8185:     for (i=1; i<= nlstate ; i ++) {
        !          8186:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
        !          8187:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
        !          8188:       fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
        !          8189:       for (j=2; j<= nlstate+ndeath ; j ++) {
        !          8190:        fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
        !          8191:       }
        !          8192:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
        !          8193:     }
        !          8194:   } /* End of each covariate dummy */
        !          8195:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
        !          8196:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
        !          8197:      *     kmodel       =     1   2     3     4         5        6        7       8        9
        !          8198:      *  varying                   1     2                                 3       4        5
        !          8199:      *  ncovv                     1     2                                3 4     5 6      7 8
        !          8200:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
        !          8201:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
        !          8202:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
        !          8203:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
        !          8204:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
        !          8205:      */
        !          8206:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
        !          8207:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
        !          8208:     /* printf("DebugILK ficgp ncovv=%d, kvar=TvarVV[ncovv]=%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
        !          8209:     if(ipos!=iposold){ /* Not a product or first of a product */
        !          8210:       /* printf(" %d",ipos); */
        !          8211:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
        !          8212:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
        !          8213:       kk++; /* Position of the ncovv column in ILK_ */
        !          8214:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
        !          8215:       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
        !          8216:        for (i=1; i<= nlstate ; i ++) {
        !          8217:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
        !          8218:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
        !          8219: 
        !          8220:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
        !          8221:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
        !          8222:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
        !          8223:            for (j=2; j<= nlstate+ndeath ; j ++) {
        !          8224:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
        !          8225:            }
        !          8226:          }else{
        !          8227:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
        !          8228:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
        !          8229:            for (j=2; j<= nlstate+ndeath ; j ++) {
        !          8230:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
        !          8231:            }
        !          8232:          }
        !          8233:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
        !          8234:        }
        !          8235:       }/* End if dummy varying */
        !          8236:     }else{ /*Product */
        !          8237:       /* printf("*"); */
        !          8238:       /* fprintf(ficresilk,"*"); */
        !          8239:     }
        !          8240:     iposold=ipos;
        !          8241:   } /* For each time varying covariate */
        !          8242:   /* } /\* debugILK==1 *\/ */
        !          8243:   /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */               
        !          8244:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
        !          8245:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
        !          8246:   fprintf(ficgp,"\nset out;unset log\n");
        !          8247:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
        !          8248: 
        !          8249: 
        !          8250:   
1.126     brouard  8251:   strcpy(dirfileres,optionfilefiname);
                   8252:   strcpy(optfileres,"vpl");
1.223     brouard  8253:   /* 1eme*/
1.238     brouard  8254:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8255:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8256:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8257:        k1=TKresult[nres];
1.338     brouard  8258:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8259:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8260:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8261:        /*   continue; */
1.238     brouard  8262:        /* We are interested in selected combination by the resultline */
1.246     brouard  8263:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8264:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8265:        strcpy(gplotlabel,"(");
1.337     brouard  8266:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8267:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8268:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8269: 
                   8270:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8271:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8272:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8273:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8274:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8275:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8276:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8277:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8278:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8279:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8280:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8281:        /* } */
                   8282:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8283:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8284:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8285:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8286:        }
                   8287:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8288:        /* printf("\n#\n"); */
1.238     brouard  8289:        fprintf(ficgp,"\n#\n");
                   8290:        if(invalidvarcomb[k1]){
1.260     brouard  8291:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8292:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8293:          continue;
                   8294:        }
1.235     brouard  8295:       
1.241     brouard  8296:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8297:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8298:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
1.338     brouard  8299:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8300:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
                   8301:        /* fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres); */
                   8302:       /* k1-1 error should be nres-1*/
1.238     brouard  8303:        for (i=1; i<= nlstate ; i ++) {
                   8304:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8305:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8306:        }
1.288     brouard  8307:        fprintf(ficgp,"\" t\"Forward prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
1.238     brouard  8308:        for (i=1; i<= nlstate ; i ++) {
                   8309:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8310:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8311:        } 
1.260     brouard  8312:        fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres); 
1.238     brouard  8313:        for (i=1; i<= nlstate ; i ++) {
                   8314:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8315:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8316:        }  
1.265     brouard  8317:        /* fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence\" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1)); */
                   8318:        
                   8319:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8320:         if(cptcoveff ==0){
1.271     brouard  8321:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8322:        }else{
                   8323:          kl=0;
                   8324:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8325:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8326:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8327:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8328:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8329:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8330:            vlv= nbcode[Tvaraff[k]][lv];
                   8331:            kl++;
                   8332:            /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   8333:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8334:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8335:            /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   8336:            if(k==cptcoveff){
                   8337:              fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Observed prevalence in state %d' w l lt 2",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   8338:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8339:            }else{
                   8340:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8341:              kl++;
                   8342:            }
                   8343:          } /* end covariate */
                   8344:        } /* end if no covariate */
                   8345: 
1.296     brouard  8346:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8347:          /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
1.242     brouard  8348:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8349:          if(cptcoveff ==0){
1.245     brouard  8350:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8351:          }else{
                   8352:            kl=0;
                   8353:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8354:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8355:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8356:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8357:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8358:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8359:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8360:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8361:              kl++;
1.238     brouard  8362:              /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   8363:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8364:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8365:              /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   8366:              if(k==cptcoveff){
1.245     brouard  8367:                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' w l lt 3",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
1.242     brouard  8368:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8369:              }else{
1.332     brouard  8370:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8371:                kl++;
                   8372:              }
                   8373:            } /* end covariate */
                   8374:          } /* end if no covariate */
1.296     brouard  8375:          if(prevbcast == 1){
1.268     brouard  8376:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8377:            /* k1-1 error should be nres-1*/
                   8378:            for (i=1; i<= nlstate ; i ++) {
                   8379:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8380:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8381:            }
1.271     brouard  8382:            fprintf(ficgp,"\" t\"Backward (stable) prevalence\" w l lt 6 dt 3,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
1.268     brouard  8383:            for (i=1; i<= nlstate ; i ++) {
                   8384:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8385:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8386:            } 
1.276     brouard  8387:            fprintf(ficgp,"\" t\"95%% CI\" w l lt 4,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres); 
1.268     brouard  8388:            for (i=1; i<= nlstate ; i ++) {
                   8389:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8390:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8391:            } 
1.274     brouard  8392:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8393:          } /* end if backprojcast */
1.296     brouard  8394:        } /* end if prevbcast */
1.276     brouard  8395:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8396:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8397:       } /* nres */
1.337     brouard  8398:     /* } /\* k1 *\/ */
1.201     brouard  8399:   } /* cpt */
1.235     brouard  8400: 
                   8401:   
1.126     brouard  8402:   /*2 eme*/
1.337     brouard  8403:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8404:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8405:       k1=TKresult[nres];
1.338     brouard  8406:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8407:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8408:       /*       continue; */
1.238     brouard  8409:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8410:       strcpy(gplotlabel,"(");
1.337     brouard  8411:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8412:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8413:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8414:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8415:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8416:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8417:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8418:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8419:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8420:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8421:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8422:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8423:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8424:       /* } */
                   8425:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8426:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8427:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8428:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8429:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8430:       }
1.264     brouard  8431:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8432:       fprintf(ficgp,"\n#\n");
1.223     brouard  8433:       if(invalidvarcomb[k1]){
                   8434:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8435:        continue;
                   8436:       }
1.219     brouard  8437:                        
1.241     brouard  8438:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8439:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8440:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8441:        if(vpopbased==0){
1.238     brouard  8442:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8443:        }else
1.238     brouard  8444:          fprintf(ficgp,"\nreplot ");
                   8445:        for (i=1; i<= nlstate+1 ; i ++) {
                   8446:          k=2*i;
1.261     brouard  8447:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased);
1.238     brouard  8448:          for (j=1; j<= nlstate+1 ; j ++) {
                   8449:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8450:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8451:          }   
                   8452:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8453:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8454:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
1.238     brouard  8455:          for (j=1; j<= nlstate+1 ; j ++) {
                   8456:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8457:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8458:          }   
                   8459:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8460:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
1.238     brouard  8461:          for (j=1; j<= nlstate+1 ; j ++) {
                   8462:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8463:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8464:          }   
                   8465:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8466:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8467:        } /* state */
                   8468:       } /* vpopbased */
1.264     brouard  8469:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; unset label;\n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  8470:     } /* end nres */
1.337     brouard  8471:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8472:        
                   8473:        
                   8474:   /*3eme*/
1.337     brouard  8475:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8476:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8477:       k1=TKresult[nres];
1.338     brouard  8478:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8479:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8480:       /*       continue; */
1.238     brouard  8481: 
1.332     brouard  8482:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8483:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8484:        strcpy(gplotlabel,"(");
1.337     brouard  8485:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8486:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8487:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8488:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8489:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8490:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8491:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8492:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8493:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8494:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8495:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8496:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8497:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8498:        /* } */
                   8499:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8500:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8501:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8502:        }
1.264     brouard  8503:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8504:        fprintf(ficgp,"\n#\n");
                   8505:        if(invalidvarcomb[k1]){
                   8506:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8507:          continue;
                   8508:        }
                   8509:                        
                   8510:        /*       k=2+nlstate*(2*cpt-2); */
                   8511:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8512:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8513:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8514:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8515: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),nres-1,nres-1,k,cpt);
1.238     brouard  8516:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8517:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8518:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8519:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8520:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8521:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8522:                                
1.238     brouard  8523:        */
                   8524:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8525:          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+i,cpt,i+1);
1.238     brouard  8526:          /*    fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+2*i,cpt,i+1);*/
1.219     brouard  8527:                                
1.238     brouard  8528:        } 
1.261     brouard  8529:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+nlstate,cpt);
1.238     brouard  8530:       }
1.264     brouard  8531:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8532:     } /* end nres */
1.337     brouard  8533:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8534:   
1.223     brouard  8535:   /* 4eme */
1.201     brouard  8536:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8537:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8538:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8539:       k1=TKresult[nres];
1.338     brouard  8540:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8541:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8542:       /*       continue; */
1.238     brouard  8543:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8544:        strcpy(gplotlabel,"(");
1.337     brouard  8545:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8546:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8547:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8548:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8549:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8550:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8551:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8552:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8553:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8554:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8555:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8556:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8557:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8558:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8559:        /* } */
                   8560:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8561:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8562:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8563:        }       
1.264     brouard  8564:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8565:        fprintf(ficgp,"\n#\n");
                   8566:        if(invalidvarcomb[k1]){
                   8567:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8568:          continue;
1.223     brouard  8569:        }
1.238     brouard  8570:       
1.241     brouard  8571:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8572:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.238     brouard  8573:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8574: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8575:        k=3;
                   8576:        for (i=1; i<= nlstate ; i ++){
                   8577:          if(i==1){
                   8578:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8579:          }else{
                   8580:            fprintf(ficgp,", '' ");
                   8581:          }
                   8582:          l=(nlstate+ndeath)*(i-1)+1;
                   8583:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8584:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8585:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8586:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8587:        } /* nlstate */
1.264     brouard  8588:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8589:       } /* end cpt state*/ 
                   8590:     } /* end nres */
1.337     brouard  8591:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8592: 
1.220     brouard  8593: /* 5eme */
1.201     brouard  8594:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8595:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8596:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8597:       k1=TKresult[nres];
1.338     brouard  8598:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8599:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8600:       /*       continue; */
1.238     brouard  8601:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8602:        strcpy(gplotlabel,"(");
1.238     brouard  8603:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
1.337     brouard  8604:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8605:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8606:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8607:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8608:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8609:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8610:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8611:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8612:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8613:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8614:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8615:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8616:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8617:        /* } */
                   8618:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8619:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8620:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8621:        }       
1.264     brouard  8622:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8623:        fprintf(ficgp,"\n#\n");
                   8624:        if(invalidvarcomb[k1]){
                   8625:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8626:          continue;
                   8627:        }
1.227     brouard  8628:       
1.241     brouard  8629:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8630:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.238     brouard  8631:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8632: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8633:        k=3;
                   8634:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8635:          if(j==1)
                   8636:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8637:          else
                   8638:            fprintf(ficgp,", '' ");
                   8639:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8640:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8641:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8642:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8643:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8644:        } /* nlstate */
                   8645:        fprintf(ficgp,", '' ");
                   8646:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8647:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8648:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8649:          if(j < nlstate)
                   8650:            fprintf(ficgp,"$%d +",k+l);
                   8651:          else
                   8652:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8653:        }
1.264     brouard  8654:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8655:       } /* end cpt state*/ 
1.337     brouard  8656:     /* } /\* end covariate *\/   */
1.238     brouard  8657:   } /* end nres */
1.227     brouard  8658:   
1.220     brouard  8659: /* 6eme */
1.202     brouard  8660:   /* CV preval stable (period) for each covariate */
1.337     brouard  8661:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8662:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8663:      k1=TKresult[nres];
1.338     brouard  8664:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8665:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8666:      /*  continue; */
1.255     brouard  8667:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8668:       strcpy(gplotlabel,"(");      
1.288     brouard  8669:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8670:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8671:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8672:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8673:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8674:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8675:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8676:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8677:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8678:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8679:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8680:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8681:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8682:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8683:       /* } */
                   8684:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8685:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8686:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8687:       }        
1.264     brouard  8688:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8689:       fprintf(ficgp,"\n#\n");
1.223     brouard  8690:       if(invalidvarcomb[k1]){
1.227     brouard  8691:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8692:        continue;
1.223     brouard  8693:       }
1.227     brouard  8694:       
1.241     brouard  8695:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8696:       fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.126     brouard  8697:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8698: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8699:       k=3; /* Offset */
1.255     brouard  8700:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8701:        if(i==1)
                   8702:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8703:        else
                   8704:          fprintf(ficgp,", '' ");
1.255     brouard  8705:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8706:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8707:        for (j=2; j<= nlstate ; j ++)
                   8708:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8709:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8710:       } /* nlstate */
1.264     brouard  8711:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8712:     } /* end cpt state*/ 
                   8713:   } /* end covariate */  
1.227     brouard  8714:   
                   8715:   
1.220     brouard  8716: /* 7eme */
1.296     brouard  8717:   if(prevbcast == 1){
1.288     brouard  8718:     /* CV backward prevalence  for each covariate */
1.337     brouard  8719:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8720:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8721:       k1=TKresult[nres];
1.338     brouard  8722:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8723:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8724:       /*       continue; */
1.268     brouard  8725:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8726:        strcpy(gplotlabel,"(");      
1.288     brouard  8727:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8728:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8729:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8730:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8731:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8732:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8733:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8734:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8735:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8736:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8737:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8738:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8739:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8740:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8741:        /* } */
                   8742:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8743:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8744:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8745:        }       
1.264     brouard  8746:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8747:        fprintf(ficgp,"\n#\n");
                   8748:        if(invalidvarcomb[k1]){
                   8749:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8750:          continue;
                   8751:        }
                   8752:        
1.241     brouard  8753:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8754:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.227     brouard  8755:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8756: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8757:        k=3; /* Offset */
1.268     brouard  8758:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8759:          if(i==1)
                   8760:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8761:          else
                   8762:            fprintf(ficgp,", '' ");
                   8763:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8764:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8765:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8766:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
1.255     brouard  8767:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8768:          /* for (j=2; j<= nlstate ; j ++) */
                   8769:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8770:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8771:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8772:        } /* nlstate */
1.264     brouard  8773:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8774:       } /* end cpt state*/ 
                   8775:     } /* end covariate */  
1.296     brouard  8776:   } /* End if prevbcast */
1.218     brouard  8777:   
1.223     brouard  8778:   /* 8eme */
1.218     brouard  8779:   if(prevfcast==1){
1.288     brouard  8780:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8781:     
1.337     brouard  8782:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8783:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8784:       k1=TKresult[nres];
1.338     brouard  8785:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8786:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8787:       /*       continue; */
1.211     brouard  8788:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8789:        strcpy(gplotlabel,"(");      
1.288     brouard  8790:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8791:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8792:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8793:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8794:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8795:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8796:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8797:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8798:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8799:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8800:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8801:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8802:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8803:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8804:        /* } */
                   8805:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8806:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8807:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8808:        }       
1.264     brouard  8809:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8810:        fprintf(ficgp,"\n#\n");
                   8811:        if(invalidvarcomb[k1]){
                   8812:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8813:          continue;
                   8814:        }
                   8815:        
                   8816:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8817:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8818:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.227     brouard  8819:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8820: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8821: 
                   8822:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8823:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8824:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8825:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8826:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8827:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8828:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8829:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8830:          if(i==istart){
1.227     brouard  8831:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8832:          }else{
                   8833:            fprintf(ficgp,",\\\n '' ");
                   8834:          }
                   8835:          if(cptcoveff ==0){ /* No covariate */
                   8836:            ioffset=2; /* Age is in 2 */
                   8837:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8838:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8839:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8840:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8841:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8842:            if(i==nlstate+1){
1.270     brouard  8843:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8844:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8845:              fprintf(ficgp,",\\\n '' ");
                   8846:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8847:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8848:                     offyear,                           \
1.268     brouard  8849:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8850:            }else
1.227     brouard  8851:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8852:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8853:          }else{ /* more than 2 covariates */
1.270     brouard  8854:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8855:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8856:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8857:            iyearc=ioffset-1;
                   8858:            iagec=ioffset;
1.227     brouard  8859:            fprintf(ficgp," u %d:(",ioffset); 
                   8860:            kl=0;
                   8861:            strcpy(gplotcondition,"(");
                   8862:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8863:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8864:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8865:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8866:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8867:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8868:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8869:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8870:              kl++;
                   8871:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8872:              kl++;
                   8873:              if(k <cptcoveff && cptcoveff>1)
                   8874:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8875:            }
                   8876:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8877:            /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   8878:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8879:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8880:            /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   8881:            if(i==nlstate+1){
1.270     brouard  8882:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8883:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8884:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8885:              fprintf(ficgp," u %d:(",iagec); 
                   8886:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8887:                      iyearc, iagec, offyear,                           \
                   8888:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8889: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
1.227     brouard  8890:            }else{
                   8891:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8892:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8893:            }
                   8894:          } /* end if covariate */
                   8895:        } /* nlstate */
1.264     brouard  8896:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8897:       } /* end cpt state*/
                   8898:     } /* end covariate */
                   8899:   } /* End if prevfcast */
1.227     brouard  8900:   
1.296     brouard  8901:   if(prevbcast==1){
1.268     brouard  8902:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8903:     
1.337     brouard  8904:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8905:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8906:      k1=TKresult[nres];
1.338     brouard  8907:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8908:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8909:        /*      continue; */
1.268     brouard  8910:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8911:        strcpy(gplotlabel,"(");      
                   8912:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
1.337     brouard  8913:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8914:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8915:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8916:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8917:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8918:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8919:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8920:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8921:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8922:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8923:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8924:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8925:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8926:        /* } */
                   8927:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8928:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8929:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8930:        }       
                   8931:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8932:        fprintf(ficgp,"\n#\n");
                   8933:        if(invalidvarcomb[k1]){
                   8934:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8935:          continue;
                   8936:        }
                   8937:        
                   8938:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8939:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8940:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8941:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8942: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8943: 
                   8944:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8945:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8946:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8947:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8948:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8949:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8950:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8951:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8952:          if(i==istart){
                   8953:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8954:          }else{
                   8955:            fprintf(ficgp,",\\\n '' ");
                   8956:          }
                   8957:          if(cptcoveff ==0){ /* No covariate */
                   8958:            ioffset=2; /* Age is in 2 */
                   8959:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8960:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8961:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8962:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8963:            fprintf(ficgp," u %d:(", ioffset); 
                   8964:            if(i==nlstate+1){
1.270     brouard  8965:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8966:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8967:              fprintf(ficgp,",\\\n '' ");
                   8968:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8969:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8970:                     offbyear,                          \
                   8971:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8972:            }else
                   8973:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8974:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8975:          }else{ /* more than 2 covariates */
1.270     brouard  8976:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8977:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8978:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8979:            iyearc=ioffset-1;
                   8980:            iagec=ioffset;
1.268     brouard  8981:            fprintf(ficgp," u %d:(",ioffset); 
                   8982:            kl=0;
                   8983:            strcpy(gplotcondition,"(");
1.337     brouard  8984:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  8985:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  8986:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   8987:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8988:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8989:                lv=Tvresult[nres][k];
                   8990:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   8991:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8992:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8993:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8994:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8995:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8996:                kl++;
                   8997:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   8998:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   8999:                kl++;
1.338     brouard  9000:                if(k <cptcovs && cptcovs>1)
1.337     brouard  9001:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9002:              }
1.268     brouard  9003:            }
                   9004:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9005:            /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   9006:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9007:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9008:            /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   9009:            if(i==nlstate+1){
1.270     brouard  9010:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9011:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  9012:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  9013:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  9014:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  9015:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9016:                      iyearc,iagec,offbyear,                            \
                   9017:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  9018: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9019:            }else{
                   9020:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9021:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9022:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9023:            }
                   9024:          } /* end if covariate */
                   9025:        } /* nlstate */
                   9026:        fprintf(ficgp,"\nset out; unset label;\n");
                   9027:       } /* end cpt state*/
                   9028:     } /* end covariate */
1.296     brouard  9029:   } /* End if prevbcast */
1.268     brouard  9030:   
1.227     brouard  9031:   
1.238     brouard  9032:   /* 9eme writing MLE parameters */
                   9033:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  9034:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  9035:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  9036:     for(k=1; k <=(nlstate+ndeath); k++){
                   9037:       if (k != i) {
1.227     brouard  9038:        fprintf(ficgp,"#   current state %d\n",k);
                   9039:        for(j=1; j <=ncovmodel; j++){
                   9040:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9041:          jk++; 
                   9042:        }
                   9043:        fprintf(ficgp,"\n");
1.126     brouard  9044:       }
                   9045:     }
1.223     brouard  9046:   }
1.187     brouard  9047:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  9048:   
1.145     brouard  9049:   /*goto avoid;*/
1.238     brouard  9050:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9051:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  9052:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9053:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9054:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9055:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9056:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9057:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9058:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9059:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9060:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9061:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9062:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9063:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9064:   fprintf(ficgp,"#\n");
1.223     brouard  9065:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  9066:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  9067:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  9068:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  9069:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  9070:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  9071:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9072:      /* k1=nres; */
1.338     brouard  9073:       k1=TKresult[nres];
                   9074:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9075:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  9076:       strcpy(gplotlabel,"(");
1.276     brouard  9077:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  9078:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9079:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9080:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9081:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9082:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9083:       }
                   9084:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9085:       /*       continue; */
                   9086:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9087:       /* strcpy(gplotlabel,"("); */
                   9088:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9089:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9090:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9091:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9092:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9093:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9094:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9095:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9096:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9097:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9098:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9099:       /* } */
                   9100:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9101:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9102:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9103:       /* }      */
1.264     brouard  9104:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  9105:       fprintf(ficgp,"\n#\n");
1.264     brouard  9106:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  9107:       fprintf(ficgp,"\nset key outside ");
                   9108:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9109:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  9110:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9111:       if (ng==1){
                   9112:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9113:        fprintf(ficgp,"\nunset log y");
                   9114:       }else if (ng==2){
                   9115:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9116:        fprintf(ficgp,"\nset log y");
                   9117:       }else if (ng==3){
                   9118:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9119:        fprintf(ficgp,"\nset log y");
                   9120:       }else
                   9121:        fprintf(ficgp,"\nunset title ");
                   9122:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9123:       i=1;
                   9124:       for(k2=1; k2<=nlstate; k2++) {
                   9125:        k3=i;
                   9126:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9127:          if (k != k2){
                   9128:            switch( ng) {
                   9129:            case 1:
                   9130:              if(nagesqr==0)
                   9131:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9132:              else /* nagesqr =1 */
                   9133:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9134:              break;
                   9135:            case 2: /* ng=2 */
                   9136:              if(nagesqr==0)
                   9137:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9138:              else /* nagesqr =1 */
                   9139:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9140:              break;
                   9141:            case 3:
                   9142:              if(nagesqr==0)
                   9143:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9144:              else /* nagesqr =1 */
                   9145:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9146:              break;
                   9147:            }
                   9148:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  9149:            ijp=1; /* product no age */
                   9150:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9151:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  9152:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  9153:              switch(Typevar[j]){
                   9154:              case 1:
                   9155:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9156:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9157:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9158:                      if(DummyV[j]==0){/* Bug valgrind */
                   9159:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9160:                      }else{ /* quantitative */
                   9161:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9162:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9163:                      }
                   9164:                      ij++;
1.268     brouard  9165:                    }
1.237     brouard  9166:                  }
1.329     brouard  9167:                }
                   9168:                break;
                   9169:              case 2:
                   9170:                if(cptcovprod >0){
                   9171:                  if(j==Tprod[ijp]) { /* */ 
                   9172:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9173:                    if(ijp <=cptcovprod) { /* Product */
                   9174:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9175:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9176:                          /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
                   9177:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9178:                        }else{ /* Vn is dummy and Vm is quanti */
                   9179:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9180:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9181:                        }
                   9182:                      }else{ /* Vn*Vm Vn is quanti */
                   9183:                        if(DummyV[Tvard[ijp][2]]==0){
                   9184:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9185:                        }else{ /* Both quanti */
                   9186:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9187:                        }
1.268     brouard  9188:                      }
1.329     brouard  9189:                      ijp++;
1.237     brouard  9190:                    }
1.329     brouard  9191:                  } /* end Tprod */
                   9192:                }
                   9193:                break;
                   9194:              case 0:
                   9195:                /* simple covariate */
1.264     brouard  9196:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  9197:                if(Dummy[j]==0){
                   9198:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9199:                }else{ /* quantitative */
                   9200:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  9201:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  9202:                }
1.329     brouard  9203:               /* end simple */
                   9204:                break;
                   9205:              default:
                   9206:                break;
                   9207:              } /* end switch */
1.237     brouard  9208:            } /* end j */
1.329     brouard  9209:          }else{ /* k=k2 */
                   9210:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9211:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9212:            }else
                   9213:              i=i-ncovmodel;
1.223     brouard  9214:          }
1.227     brouard  9215:          
1.223     brouard  9216:          if(ng != 1){
                   9217:            fprintf(ficgp,")/(1");
1.227     brouard  9218:            
1.264     brouard  9219:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  9220:              if(nagesqr==0)
1.264     brouard  9221:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  9222:              else /* nagesqr =1 */
1.264     brouard  9223:                fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1,k3+(cpt-1)*ncovmodel+1+nagesqr);
1.217     brouard  9224:               
1.223     brouard  9225:              ij=1;
1.329     brouard  9226:              ijp=1;
                   9227:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9228:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9229:                switch(Typevar[j]){
                   9230:                case 1:
                   9231:                  if(cptcovage >0){ 
                   9232:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9233:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9234:                        if(DummyV[j]==0){/* Bug valgrind */
                   9235:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9236:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9237:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9238:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9239:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9240:                        }else{ /* quantitative */
                   9241:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9242:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9243:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9244:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9245:                        }
                   9246:                        ij++;
                   9247:                      }
                   9248:                    }
                   9249:                  }
                   9250:                  break;
                   9251:                case 2:
                   9252:                  if(cptcovprod >0){
                   9253:                    if(j==Tprod[ijp]) { /* */ 
                   9254:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9255:                      if(ijp <=cptcovprod) { /* Product */
                   9256:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9257:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9258:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
                   9259:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9260:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9261:                          }else{ /* Vn is dummy and Vm is quanti */
                   9262:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9263:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9264:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9265:                          }
                   9266:                        }else{ /* Vn*Vm Vn is quanti */
                   9267:                          if(DummyV[Tvard[ijp][2]]==0){
                   9268:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9269:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9270:                          }else{ /* Both quanti */
                   9271:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9272:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9273:                          } 
                   9274:                        }
                   9275:                        ijp++;
                   9276:                      }
                   9277:                    } /* end Tprod */
                   9278:                  } /* end if */
                   9279:                  break;
                   9280:                case 0: 
                   9281:                  /* simple covariate */
                   9282:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9283:                  if(Dummy[j]==0){
                   9284:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9285:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9286:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9287:                  }else{ /* quantitative */
                   9288:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9289:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9290:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9291:                  }
                   9292:                  /* end simple */
                   9293:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9294:                  break;
                   9295:                default:
                   9296:                  break;
                   9297:                } /* end switch */
1.223     brouard  9298:              }
                   9299:              fprintf(ficgp,")");
                   9300:            }
                   9301:            fprintf(ficgp,")");
                   9302:            if(ng ==2)
1.276     brouard  9303:              fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"p%d%d\" ", nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
1.223     brouard  9304:            else /* ng= 3 */
1.276     brouard  9305:              fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"i%d%d\" ",  nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
1.329     brouard  9306:           }else{ /* end ng <> 1 */
1.223     brouard  9307:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9308:              fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"logit(p%d%d)\" ",  nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
1.223     brouard  9309:          }
                   9310:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9311:            fprintf(ficgp,",");
                   9312:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9313:            fprintf(ficgp,",");
                   9314:          i=i+ncovmodel;
                   9315:        } /* end k */
                   9316:       } /* end k2 */
1.276     brouard  9317:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9318:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9319:     } /* end resultline */
1.223     brouard  9320:   } /* end ng */
                   9321:   /* avoid: */
                   9322:   fflush(ficgp); 
1.126     brouard  9323: }  /* end gnuplot */
                   9324: 
                   9325: 
                   9326: /*************** Moving average **************/
1.219     brouard  9327: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9328:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9329:    
1.222     brouard  9330:    int i, cpt, cptcod;
                   9331:    int modcovmax =1;
                   9332:    int mobilavrange, mob;
                   9333:    int iage=0;
1.288     brouard  9334:    int firstA1=0, firstA2=0;
1.222     brouard  9335: 
1.266     brouard  9336:    double sum=0., sumr=0.;
1.222     brouard  9337:    double age;
1.266     brouard  9338:    double *sumnewp, *sumnewm, *sumnewmr;
                   9339:    double *agemingood, *agemaxgood; 
                   9340:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9341:   
                   9342:   
1.278     brouard  9343:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9344:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9345: 
                   9346:    sumnewp = vector(1,ncovcombmax);
                   9347:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9348:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9349:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9350:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9351:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9352:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9353: 
                   9354:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9355:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9356:      sumnewp[cptcod]=0.;
1.266     brouard  9357:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9358:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9359:    }
                   9360:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9361:   
1.266     brouard  9362:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9363:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9364:      else mobilavrange=mobilav;
                   9365:      for (age=bage; age<=fage; age++)
                   9366:        for (i=1; i<=nlstate;i++)
                   9367:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9368:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9369:      /* We keep the original values on the extreme ages bage, fage and for 
                   9370:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9371:        we use a 5 terms etc. until the borders are no more concerned. 
                   9372:      */ 
                   9373:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9374:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9375:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9376:           sumnewm[cptcod]=0.;
                   9377:           for (i=1; i<=nlstate;i++){
1.222     brouard  9378:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9379:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9380:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9381:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9382:             }
                   9383:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9384:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9385:           } /* end i */
                   9386:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9387:         } /* end cptcod */
1.222     brouard  9388:        }/* end age */
                   9389:      }/* end mob */
1.266     brouard  9390:    }else{
                   9391:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9392:      return -1;
1.266     brouard  9393:    }
                   9394: 
                   9395:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9396:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9397:      if(invalidvarcomb[cptcod]){
                   9398:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9399:        continue;
                   9400:      }
1.219     brouard  9401: 
1.266     brouard  9402:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9403:        sumnewm[cptcod]=0.;
                   9404:        sumnewmr[cptcod]=0.;
                   9405:        for (i=1; i<=nlstate;i++){
                   9406:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9407:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9408:        }
                   9409:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9410:         agemingoodr[cptcod]=age;
                   9411:        }
                   9412:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9413:           agemingood[cptcod]=age;
                   9414:        }
                   9415:      } /* age */
                   9416:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9417:        sumnewm[cptcod]=0.;
1.266     brouard  9418:        sumnewmr[cptcod]=0.;
1.222     brouard  9419:        for (i=1; i<=nlstate;i++){
                   9420:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9421:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9422:        }
                   9423:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9424:         agemaxgoodr[cptcod]=age;
1.222     brouard  9425:        }
                   9426:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9427:         agemaxgood[cptcod]=age;
                   9428:        }
                   9429:      } /* age */
                   9430:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9431:      /* but they will change */
1.288     brouard  9432:      firstA1=0;firstA2=0;
1.266     brouard  9433:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9434:        sumnewm[cptcod]=0.;
                   9435:        sumnewmr[cptcod]=0.;
                   9436:        for (i=1; i<=nlstate;i++){
                   9437:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9438:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9439:        }
                   9440:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9441:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9442:           agemaxgoodr[cptcod]=age;  /* age min */
                   9443:           for (i=1; i<=nlstate;i++)
                   9444:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9445:         }else{ /* bad we change the value with the values of good ages */
                   9446:           for (i=1; i<=nlstate;i++){
                   9447:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9448:           } /* i */
                   9449:         } /* end bad */
                   9450:        }else{
                   9451:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9452:           agemaxgood[cptcod]=age;
                   9453:         }else{ /* bad we change the value with the values of good ages */
                   9454:           for (i=1; i<=nlstate;i++){
                   9455:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9456:           } /* i */
                   9457:         } /* end bad */
                   9458:        }/* end else */
                   9459:        sum=0.;sumr=0.;
                   9460:        for (i=1; i<=nlstate;i++){
                   9461:         sum+=mobaverage[(int)age][i][cptcod];
                   9462:         sumr+=probs[(int)age][i][cptcod];
                   9463:        }
                   9464:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9465:         if(!firstA1){
                   9466:           firstA1=1;
                   9467:           printf("Moving average A1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you increase bage=%d. Others in log file...\n",cptcod,sumr, (int)age, (int)bage);
                   9468:         }
                   9469:         fprintf(ficlog,"Moving average A1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you increase bage=%d\n",cptcod,sumr, (int)age, (int)bage);
1.266     brouard  9470:        } /* end bad */
                   9471:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9472:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9473:         if(!firstA2){
                   9474:           firstA2=1;
                   9475:           printf("Moving average A2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase bage=%d. Others in log file...\n",cptcod,sumr, (int)age, (int)bage);
                   9476:         }
                   9477:         fprintf(ficlog,"Moving average A2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase bage=%d\n",cptcod,sumr, (int)age, (int)bage);
1.222     brouard  9478:        } /* end bad */
                   9479:      }/* age */
1.266     brouard  9480: 
                   9481:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9482:        sumnewm[cptcod]=0.;
1.266     brouard  9483:        sumnewmr[cptcod]=0.;
1.222     brouard  9484:        for (i=1; i<=nlstate;i++){
                   9485:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9486:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9487:        } 
                   9488:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9489:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9490:           agemingoodr[cptcod]=age;
                   9491:           for (i=1; i<=nlstate;i++)
                   9492:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9493:         }else{ /* bad we change the value with the values of good ages */
                   9494:           for (i=1; i<=nlstate;i++){
                   9495:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9496:           } /* i */
                   9497:         } /* end bad */
                   9498:        }else{
                   9499:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9500:           agemingood[cptcod]=age;
                   9501:         }else{ /* bad */
                   9502:           for (i=1; i<=nlstate;i++){
                   9503:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9504:           } /* i */
                   9505:         } /* end bad */
                   9506:        }/* end else */
                   9507:        sum=0.;sumr=0.;
                   9508:        for (i=1; i<=nlstate;i++){
                   9509:         sum+=mobaverage[(int)age][i][cptcod];
                   9510:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9511:        }
1.266     brouard  9512:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9513:         printf("Moving average B1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you decrease fage=%d?\n",cptcod, sum, (int) age, (int)fage);
1.266     brouard  9514:        } /* end bad */
                   9515:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9516:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9517:         printf("Moving average B2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase fage=%d\n",cptcod,sumr, (int)age, (int)fage);
1.222     brouard  9518:        } /* end bad */
                   9519:      }/* age */
1.266     brouard  9520: 
1.222     brouard  9521:                
                   9522:      for (age=bage; age<=fage; age++){
1.235     brouard  9523:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9524:        sumnewp[cptcod]=0.;
                   9525:        sumnewm[cptcod]=0.;
                   9526:        for (i=1; i<=nlstate;i++){
                   9527:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9528:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9529:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9530:        }
                   9531:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9532:      }
                   9533:      /* printf("\n"); */
                   9534:      /* } */
1.266     brouard  9535: 
1.222     brouard  9536:      /* brutal averaging */
1.266     brouard  9537:      /* for (i=1; i<=nlstate;i++){ */
                   9538:      /*   for (age=1; age<=bage; age++){ */
                   9539:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9540:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9541:      /*   }     */
                   9542:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9543:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9544:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9545:      /*   } */
                   9546:      /* } /\* end i status *\/ */
                   9547:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9548:      /*   for (age=1; age<=AGESUP; age++){ */
                   9549:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9550:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9551:      /*   } */
                   9552:      /* } */
1.222     brouard  9553:    }/* end cptcod */
1.266     brouard  9554:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9555:    free_vector(agemaxgood,1, ncovcombmax);
                   9556:    free_vector(agemingood,1, ncovcombmax);
                   9557:    free_vector(agemingoodr,1, ncovcombmax);
                   9558:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9559:    free_vector(sumnewm,1, ncovcombmax);
                   9560:    free_vector(sumnewp,1, ncovcombmax);
                   9561:    return 0;
                   9562:  }/* End movingaverage */
1.218     brouard  9563:  
1.126     brouard  9564: 
1.296     brouard  9565:  
1.126     brouard  9566: /************** Forecasting ******************/
1.296     brouard  9567: /* void prevforecast(char fileres[], double dateintmean, double anprojd, double mprojd, double jprojd, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double anprojf, double p[], int cptcoveff)*/
                   9568: void prevforecast(char fileres[], double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
                   9569:   /* dateintemean, mean date of interviews
                   9570:      dateprojd, year, month, day of starting projection 
                   9571:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9572:      agemin, agemax range of age
                   9573:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9574:   */
1.296     brouard  9575:   /* double anprojd, mprojd, jprojd; */
                   9576:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9577:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9578:   double agec; /* generic age */
1.296     brouard  9579:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9580:   double *popeffectif,*popcount;
                   9581:   double ***p3mat;
1.218     brouard  9582:   /* double ***mobaverage; */
1.126     brouard  9583:   char fileresf[FILENAMELENGTH];
                   9584: 
                   9585:   agelim=AGESUP;
1.211     brouard  9586:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9587:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9588:      We still use firstpass and lastpass as another selection.
                   9589:   */
1.214     brouard  9590:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9591:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9592:  
1.201     brouard  9593:   strcpy(fileresf,"F_"); 
                   9594:   strcat(fileresf,fileresu);
1.126     brouard  9595:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9596:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9597:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9598:   }
1.235     brouard  9599:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9600:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9601: 
1.225     brouard  9602:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9603: 
                   9604: 
                   9605:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9606:   if (stepm<=12) stepsize=1;
                   9607:   if(estepm < stepm){
                   9608:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9609:   }
1.270     brouard  9610:   else{
                   9611:     hstepm=estepm;   
                   9612:   }
                   9613:   if(estepm > stepm){ /* Yes every two year */
                   9614:     stepsize=2;
                   9615:   }
1.296     brouard  9616:   hstepm=hstepm/stepm;
1.126     brouard  9617: 
1.296     brouard  9618:   
                   9619:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9620:   /*                              fractional in yp1 *\/ */
                   9621:   /* aintmean=yp; */
                   9622:   /* yp2=modf((yp1*12),&yp); */
                   9623:   /* mintmean=yp; */
                   9624:   /* yp1=modf((yp2*30.5),&yp); */
                   9625:   /* jintmean=yp; */
                   9626:   /* if(jintmean==0) jintmean=1; */
                   9627:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9628: 
1.296     brouard  9629: 
                   9630:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9631:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9632:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9633:   i1=pow(2,cptcoveff);
1.126     brouard  9634:   if (cptcovn < 1){i1=1;}
                   9635:   
1.296     brouard  9636:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9637:   
                   9638:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9639:   
1.126     brouard  9640: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9641:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9642:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9643:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9644:       continue;
1.227     brouard  9645:     if(invalidvarcomb[k]){
                   9646:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9647:       continue;
                   9648:     }
                   9649:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9650:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9651:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9652:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9653:     }
1.235     brouard  9654:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9655:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9656:     }
1.227     brouard  9657:     fprintf(ficresf," yearproj age");
                   9658:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9659:       for(i=1; i<=nlstate;i++)               
                   9660:        fprintf(ficresf," p%d%d",i,j);
                   9661:       fprintf(ficresf," wp.%d",j);
                   9662:     }
1.296     brouard  9663:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9664:       fprintf(ficresf,"\n");
1.296     brouard  9665:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9666:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9667:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9668:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9669:        nhstepm = nhstepm/hstepm; 
                   9670:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9671:        oldm=oldms;savm=savms;
1.268     brouard  9672:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9673:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9674:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9675:        for (h=0; h<=nhstepm; h++){
                   9676:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9677:            break;
                   9678:          }
                   9679:        }
                   9680:        fprintf(ficresf,"\n");
                   9681:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9682:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9683:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9684:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9685:        
                   9686:        for(j=1; j<=nlstate+ndeath;j++) {
                   9687:          ppij=0.;
                   9688:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9689:            if (mobilav>=1)
                   9690:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9691:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9692:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9693:            }
1.268     brouard  9694:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9695:          } /* end i */
                   9696:          fprintf(ficresf," %.3f", ppij);
                   9697:        }/* end j */
1.227     brouard  9698:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9699:       } /* end agec */
1.266     brouard  9700:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9701:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9702:     } /* end yearp */
                   9703:   } /* end  k */
1.219     brouard  9704:        
1.126     brouard  9705:   fclose(ficresf);
1.215     brouard  9706:   printf("End of Computing forecasting \n");
                   9707:   fprintf(ficlog,"End of Computing forecasting\n");
                   9708: 
1.126     brouard  9709: }
                   9710: 
1.269     brouard  9711: /************** Back Forecasting ******************/
1.296     brouard  9712:  /* void prevbackforecast(char fileres[], double ***prevacurrent, double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
                   9713:  void prevbackforecast(char fileres[], double ***prevacurrent, double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
                   9714:   /* back1, year, month, day of starting backprojection
1.267     brouard  9715:      agemin, agemax range of age
                   9716:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9717:      anback2 year of end of backprojection (same day and month as back1).
                   9718:      prevacurrent and prev are prevalences.
1.267     brouard  9719:   */
                   9720:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9721:   double agec; /* generic age */
1.302     brouard  9722:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9723:   double *popeffectif,*popcount;
                   9724:   double ***p3mat;
                   9725:   /* double ***mobaverage; */
                   9726:   char fileresfb[FILENAMELENGTH];
                   9727:  
1.268     brouard  9728:   agelim=AGEINF;
1.267     brouard  9729:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9730:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9731:      We still use firstpass and lastpass as another selection.
                   9732:   */
                   9733:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9734:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9735: 
                   9736:   /*Do we need to compute prevalence again?*/
                   9737: 
                   9738:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9739:   
                   9740:   strcpy(fileresfb,"FB_");
                   9741:   strcat(fileresfb,fileresu);
                   9742:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9743:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9744:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9745:   }
                   9746:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9747:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9748:   
                   9749:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9750:   
                   9751:    
                   9752:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9753:   if (stepm<=12) stepsize=1;
                   9754:   if(estepm < stepm){
                   9755:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9756:   }
1.270     brouard  9757:   else{
                   9758:     hstepm=estepm;   
                   9759:   }
                   9760:   if(estepm >= stepm){ /* Yes every two year */
                   9761:     stepsize=2;
                   9762:   }
1.267     brouard  9763:   
                   9764:   hstepm=hstepm/stepm;
1.296     brouard  9765:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9766:   /*                              fractional in yp1 *\/ */
                   9767:   /* aintmean=yp; */
                   9768:   /* yp2=modf((yp1*12),&yp); */
                   9769:   /* mintmean=yp; */
                   9770:   /* yp1=modf((yp2*30.5),&yp); */
                   9771:   /* jintmean=yp; */
                   9772:   /* if(jintmean==0) jintmean=1; */
                   9773:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9774:   
                   9775:   i1=pow(2,cptcoveff);
                   9776:   if (cptcovn < 1){i1=1;}
                   9777:   
1.296     brouard  9778:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9779:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9780:   
                   9781:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9782:   
                   9783:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9784:   for(k=1; k<=i1;k++){
                   9785:     if(i1 != 1 && TKresult[nres]!= k)
                   9786:       continue;
                   9787:     if(invalidvarcomb[k]){
                   9788:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9789:       continue;
                   9790:     }
1.268     brouard  9791:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9792:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9793:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9794:     }
                   9795:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9796:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9797:     }
                   9798:     fprintf(ficresfb," yearbproj age");
                   9799:     for(j=1; j<=nlstate+ndeath;j++){
                   9800:       for(i=1; i<=nlstate;i++)
1.268     brouard  9801:        fprintf(ficresfb," b%d%d",i,j);
                   9802:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9803:     }
1.296     brouard  9804:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9805:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9806:       fprintf(ficresfb,"\n");
1.296     brouard  9807:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9808:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9809:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9810:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9811:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9812:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9813:        nhstepm = nhstepm/hstepm;
                   9814:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9815:        oldm=oldms;savm=savms;
1.268     brouard  9816:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9817:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9818:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9819:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9820:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9821:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9822:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9823:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9824:            break;
                   9825:          }
                   9826:        }
                   9827:        fprintf(ficresfb,"\n");
                   9828:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9829:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9830:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9831:        for(i=1; i<=nlstate+ndeath;i++) {
                   9832:          ppij=0.;ppi=0.;
                   9833:          for(j=1; j<=nlstate;j++) {
                   9834:            /* if (mobilav==1) */
1.269     brouard  9835:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9836:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9837:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9838:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9839:              /* else { */
                   9840:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9841:              /* } */
1.268     brouard  9842:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9843:          } /* end j */
                   9844:          if(ppi <0.99){
                   9845:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9846:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9847:          }
                   9848:          fprintf(ficresfb," %.3f", ppij);
                   9849:        }/* end j */
1.267     brouard  9850:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9851:       } /* end agec */
                   9852:     } /* end yearp */
                   9853:   } /* end k */
1.217     brouard  9854:   
1.267     brouard  9855:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9856:   
1.267     brouard  9857:   fclose(ficresfb);
                   9858:   printf("End of Computing Back forecasting \n");
                   9859:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9860:        
1.267     brouard  9861: }
1.217     brouard  9862: 
1.269     brouard  9863: /* Variance of prevalence limit: varprlim */
                   9864:  void varprlim(char fileresu[], int nresult, double ***prevacurrent, int mobilavproj, double bage, double fage, double **prlim, int *ncvyearp, double ftolpl, double p[], double **matcov, double *delti, int stepm, int cptcoveff){
1.288     brouard  9865:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9866:  
                   9867:    char fileresvpl[FILENAMELENGTH];  
                   9868:    FILE *ficresvpl;
                   9869:    double **oldm, **savm;
                   9870:    double **varpl; /* Variances of prevalence limits by age */   
                   9871:    int i1, k, nres, j ;
                   9872:    
                   9873:     strcpy(fileresvpl,"VPL_");
                   9874:     strcat(fileresvpl,fileresu);
                   9875:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9876:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9877:       exit(0);
                   9878:     }
1.288     brouard  9879:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9880:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9881:     
                   9882:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9883:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9884:     
                   9885:     i1=pow(2,cptcoveff);
                   9886:     if (cptcovn < 1){i1=1;}
                   9887: 
1.337     brouard  9888:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9889:        k=TKresult[nres];
1.338     brouard  9890:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9891:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9892:       if(i1 != 1 && TKresult[nres]!= k)
                   9893:        continue;
                   9894:       fprintf(ficresvpl,"\n#****** ");
                   9895:       printf("\n#****** ");
                   9896:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9897:       for(j=1;j<=cptcovs;j++) {
                   9898:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9899:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9900:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9901:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9902:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9903:       }
1.337     brouard  9904:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9905:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9906:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9907:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9908:       /* }      */
1.269     brouard  9909:       fprintf(ficresvpl,"******\n");
                   9910:       printf("******\n");
                   9911:       fprintf(ficlog,"******\n");
                   9912:       
                   9913:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9914:       oldm=oldms;savm=savms;
                   9915:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9916:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9917:       /*}*/
                   9918:     }
                   9919:     
                   9920:     fclose(ficresvpl);
1.288     brouard  9921:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9922:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9923: 
                   9924:  }
                   9925: /* Variance of back prevalence: varbprlim */
                   9926:  void varbprlim(char fileresu[], int nresult, double ***prevacurrent, int mobilavproj, double bage, double fage, double **bprlim, int *ncvyearp, double ftolpl, double p[], double **matcov, double *delti, int stepm, int cptcoveff){
                   9927:       /*------- Variance of back (stable) prevalence------*/
                   9928: 
                   9929:    char fileresvbl[FILENAMELENGTH];  
                   9930:    FILE  *ficresvbl;
                   9931: 
                   9932:    double **oldm, **savm;
                   9933:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9934:    int i1, k, nres, j ;
                   9935: 
                   9936:    strcpy(fileresvbl,"VBL_");
                   9937:    strcat(fileresvbl,fileresu);
                   9938:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9939:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9940:      exit(0);
                   9941:    }
                   9942:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9943:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9944:    
                   9945:    
                   9946:    i1=pow(2,cptcoveff);
                   9947:    if (cptcovn < 1){i1=1;}
                   9948:    
1.337     brouard  9949:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9950:      k=TKresult[nres];
1.338     brouard  9951:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9952:     /* for(k=1; k<=i1;k++){ */
                   9953:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9954:     /*          continue; */
1.269     brouard  9955:        fprintf(ficresvbl,"\n#****** ");
                   9956:        printf("\n#****** ");
                   9957:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9958:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9959:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9960:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9961:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9962:        /* for(j=1;j<=cptcoveff;j++) { */
                   9963:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9964:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9965:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9966:        /* } */
                   9967:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9968:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9969:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9970:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9971:        }
                   9972:        fprintf(ficresvbl,"******\n");
                   9973:        printf("******\n");
                   9974:        fprintf(ficlog,"******\n");
                   9975:        
                   9976:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9977:        oldm=oldms;savm=savms;
                   9978:        
                   9979:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9980:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9981:        /*}*/
                   9982:      }
                   9983:    
                   9984:    fclose(ficresvbl);
                   9985:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9986:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9987: 
                   9988:  } /* End of varbprlim */
                   9989: 
1.126     brouard  9990: /************** Forecasting *****not tested NB*************/
1.227     brouard  9991: /* void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2s, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){ */
1.126     brouard  9992:   
1.227     brouard  9993: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9994: /*   int *popage; */
                   9995: /*   double calagedatem, agelim, kk1, kk2; */
                   9996: /*   double *popeffectif,*popcount; */
                   9997: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9998: /*   /\* double ***mobaverage; *\/ */
                   9999: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  10000: 
1.227     brouard  10001: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10002: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10003: /*   agelim=AGESUP; */
                   10004: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  10005:   
1.227     brouard  10006: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  10007:   
                   10008:   
1.227     brouard  10009: /*   strcpy(filerespop,"POP_");  */
                   10010: /*   strcat(filerespop,fileresu); */
                   10011: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10012: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10013: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10014: /*   } */
                   10015: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10016: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  10017: 
1.227     brouard  10018: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  10019: 
1.227     brouard  10020: /*   /\* if (mobilav!=0) { *\/ */
                   10021: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10022: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10023: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10024: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10025: /*   /\*   } *\/ */
                   10026: /*   /\* } *\/ */
1.126     brouard  10027: 
1.227     brouard  10028: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10029: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  10030:   
1.227     brouard  10031: /*   agelim=AGESUP; */
1.126     brouard  10032:   
1.227     brouard  10033: /*   hstepm=1; */
                   10034: /*   hstepm=hstepm/stepm;  */
1.218     brouard  10035:        
1.227     brouard  10036: /*   if (popforecast==1) { */
                   10037: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10038: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10039: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10040: /*     }  */
                   10041: /*     popage=ivector(0,AGESUP); */
                   10042: /*     popeffectif=vector(0,AGESUP); */
                   10043: /*     popcount=vector(0,AGESUP); */
1.126     brouard  10044:     
1.227     brouard  10045: /*     i=1;    */
                   10046: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  10047:     
1.227     brouard  10048: /*     imx=i; */
                   10049: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10050: /*   } */
1.218     brouard  10051:   
1.227     brouard  10052: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10053: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10054: /*       k=k+1; */
                   10055: /*       fprintf(ficrespop,"\n#******"); */
                   10056: /*       for(j=1;j<=cptcoveff;j++) { */
                   10057: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10058: /*       } */
                   10059: /*       fprintf(ficrespop,"******\n"); */
                   10060: /*       fprintf(ficrespop,"# Age"); */
                   10061: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10062: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  10063:       
1.227     brouard  10064: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10065: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  10066:        
1.227     brouard  10067: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10068: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10069: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10070:          
1.227     brouard  10071: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10072: /*       oldm=oldms;savm=savms; */
                   10073: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  10074:          
1.227     brouard  10075: /*       for (h=0; h<=nhstepm; h++){ */
                   10076: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10077: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10078: /*         }  */
                   10079: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10080: /*           kk1=0.;kk2=0; */
                   10081: /*           for(i=1; i<=nlstate;i++) {               */
                   10082: /*             if (mobilav==1)  */
                   10083: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10084: /*             else { */
                   10085: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10086: /*             } */
                   10087: /*           } */
                   10088: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10089: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10090: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10091: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10092: /*           } */
                   10093: /*         } */
                   10094: /*         for(i=1; i<=nlstate;i++){ */
                   10095: /*           kk1=0.; */
                   10096: /*           for(j=1; j<=nlstate;j++){ */
                   10097: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10098: /*           } */
                   10099: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10100: /*         } */
1.218     brouard  10101:            
1.227     brouard  10102: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10103: /*           for(j=1; j<=nlstate;j++)  */
                   10104: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10105: /*       } */
                   10106: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10107: /*     } */
                   10108: /*       } */
1.218     brouard  10109:       
1.227     brouard  10110: /*       /\******\/ */
1.218     brouard  10111:       
1.227     brouard  10112: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10113: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10114: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10115: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10116: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  10117:          
1.227     brouard  10118: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10119: /*       oldm=oldms;savm=savms; */
                   10120: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10121: /*       for (h=0; h<=nhstepm; h++){ */
                   10122: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10123: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10124: /*         }  */
                   10125: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10126: /*           kk1=0.;kk2=0; */
                   10127: /*           for(i=1; i<=nlstate;i++) {               */
                   10128: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10129: /*           } */
                   10130: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10131: /*         } */
                   10132: /*       } */
                   10133: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10134: /*     } */
                   10135: /*       } */
                   10136: /*     }  */
                   10137: /*   } */
1.218     brouard  10138:   
1.227     brouard  10139: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  10140:   
1.227     brouard  10141: /*   if (popforecast==1) { */
                   10142: /*     free_ivector(popage,0,AGESUP); */
                   10143: /*     free_vector(popeffectif,0,AGESUP); */
                   10144: /*     free_vector(popcount,0,AGESUP); */
                   10145: /*   } */
                   10146: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10147: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10148: /*   fclose(ficrespop); */
                   10149: /* } /\* End of popforecast *\/ */
1.218     brouard  10150:  
1.126     brouard  10151: int fileappend(FILE *fichier, char *optionfich)
                   10152: {
                   10153:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10154:     printf("Problem with file: %s\n", optionfich);
                   10155:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10156:     return (0);
                   10157:   }
                   10158:   fflush(fichier);
                   10159:   return (1);
                   10160: }
                   10161: 
                   10162: 
                   10163: /**************** function prwizard **********************/
                   10164: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10165: {
                   10166: 
                   10167:   /* Wizard to print covariance matrix template */
                   10168: 
1.164     brouard  10169:   char ca[32], cb[32];
                   10170:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  10171:   int numlinepar;
                   10172: 
                   10173:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10174:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10175:   for(i=1; i <=nlstate; i++){
                   10176:     jj=0;
                   10177:     for(j=1; j <=nlstate+ndeath; j++){
                   10178:       if(j==i) continue;
                   10179:       jj++;
                   10180:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10181:       printf("%1d%1d",i,j);
                   10182:       fprintf(ficparo,"%1d%1d",i,j);
                   10183:       for(k=1; k<=ncovmodel;k++){
                   10184:        /*        printf(" %lf",param[i][j][k]); */
                   10185:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10186:        printf(" 0.");
                   10187:        fprintf(ficparo," 0.");
                   10188:       }
                   10189:       printf("\n");
                   10190:       fprintf(ficparo,"\n");
                   10191:     }
                   10192:   }
                   10193:   printf("# Scales (for hessian or gradient estimation)\n");
                   10194:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10195:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10196:   for(i=1; i <=nlstate; i++){
                   10197:     jj=0;
                   10198:     for(j=1; j <=nlstate+ndeath; j++){
                   10199:       if(j==i) continue;
                   10200:       jj++;
                   10201:       fprintf(ficparo,"%1d%1d",i,j);
                   10202:       printf("%1d%1d",i,j);
                   10203:       fflush(stdout);
                   10204:       for(k=1; k<=ncovmodel;k++){
                   10205:        /*      printf(" %le",delti3[i][j][k]); */
                   10206:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10207:        printf(" 0.");
                   10208:        fprintf(ficparo," 0.");
                   10209:       }
                   10210:       numlinepar++;
                   10211:       printf("\n");
                   10212:       fprintf(ficparo,"\n");
                   10213:     }
                   10214:   }
                   10215:   printf("# Covariance matrix\n");
                   10216: /* # 121 Var(a12)\n\ */
                   10217: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10218: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10219: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10220: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10221: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10222: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10223: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10224:   fflush(stdout);
                   10225:   fprintf(ficparo,"# Covariance matrix\n");
                   10226:   /* # 121 Var(a12)\n\ */
                   10227:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10228:   /* #   ...\n\ */
                   10229:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10230:   
                   10231:   for(itimes=1;itimes<=2;itimes++){
                   10232:     jj=0;
                   10233:     for(i=1; i <=nlstate; i++){
                   10234:       for(j=1; j <=nlstate+ndeath; j++){
                   10235:        if(j==i) continue;
                   10236:        for(k=1; k<=ncovmodel;k++){
                   10237:          jj++;
                   10238:          ca[0]= k+'a'-1;ca[1]='\0';
                   10239:          if(itimes==1){
                   10240:            printf("#%1d%1d%d",i,j,k);
                   10241:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10242:          }else{
                   10243:            printf("%1d%1d%d",i,j,k);
                   10244:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10245:            /*  printf(" %.5le",matcov[i][j]); */
                   10246:          }
                   10247:          ll=0;
                   10248:          for(li=1;li <=nlstate; li++){
                   10249:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10250:              if(lj==li) continue;
                   10251:              for(lk=1;lk<=ncovmodel;lk++){
                   10252:                ll++;
                   10253:                if(ll<=jj){
                   10254:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10255:                  if(ll<jj){
                   10256:                    if(itimes==1){
                   10257:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10258:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10259:                    }else{
                   10260:                      printf(" 0.");
                   10261:                      fprintf(ficparo," 0.");
                   10262:                    }
                   10263:                  }else{
                   10264:                    if(itimes==1){
                   10265:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10266:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10267:                    }else{
                   10268:                      printf(" 0.");
                   10269:                      fprintf(ficparo," 0.");
                   10270:                    }
                   10271:                  }
                   10272:                }
                   10273:              } /* end lk */
                   10274:            } /* end lj */
                   10275:          } /* end li */
                   10276:          printf("\n");
                   10277:          fprintf(ficparo,"\n");
                   10278:          numlinepar++;
                   10279:        } /* end k*/
                   10280:       } /*end j */
                   10281:     } /* end i */
                   10282:   } /* end itimes */
                   10283: 
                   10284: } /* end of prwizard */
                   10285: /******************* Gompertz Likelihood ******************************/
                   10286: double gompertz(double x[])
                   10287: { 
1.302     brouard  10288:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10289:   int i,n=0; /* n is the size of the sample */
                   10290: 
1.220     brouard  10291:   for (i=1;i<=imx ; i++) {
1.126     brouard  10292:     sump=sump+weight[i];
                   10293:     /*    sump=sump+1;*/
                   10294:     num=num+1;
                   10295:   }
1.302     brouard  10296:   L=0.0;
                   10297:   /* agegomp=AGEGOMP; */
1.126     brouard  10298:   /* for (i=0; i<=imx; i++) 
                   10299:      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
                   10300: 
1.302     brouard  10301:   for (i=1;i<=imx ; i++) {
                   10302:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10303:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10304:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10305:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10306:      * +
                   10307:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10308:      */
                   10309:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10310:        if (cens[i] == 1){
                   10311:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10312:        } else if (cens[i] == 0){
1.126     brouard  10313:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10314:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10315:       } else
                   10316:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10317:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10318:        L=L+A*weight[i];
1.126     brouard  10319:        /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
1.302     brouard  10320:      }
                   10321:   }
1.126     brouard  10322: 
1.302     brouard  10323:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10324:  
                   10325:   return -2*L*num/sump;
                   10326: }
                   10327: 
1.136     brouard  10328: #ifdef GSL
                   10329: /******************* Gompertz_f Likelihood ******************************/
                   10330: double gompertz_f(const gsl_vector *v, void *params)
                   10331: { 
1.302     brouard  10332:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10333:   double *x= (double *) v->data;
                   10334:   int i,n=0; /* n is the size of the sample */
                   10335: 
                   10336:   for (i=0;i<=imx-1 ; i++) {
                   10337:     sump=sump+weight[i];
                   10338:     /*    sump=sump+1;*/
                   10339:     num=num+1;
                   10340:   }
                   10341:  
                   10342:  
                   10343:   /* for (i=0; i<=imx; i++) 
                   10344:      if (wav[i]>0) printf("i=%d ageex=%lf agecens=%lf agedc=%lf cens=%d %d\n" ,i,ageexmed[i],agecens[i],agedc[i],cens[i],wav[i]);*/
                   10345:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10346:   for (i=1;i<=imx ; i++)
                   10347:     {
                   10348:       if (cens[i] == 1 && wav[i]>1)
                   10349:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10350:       
                   10351:       if (cens[i] == 0 && wav[i]>1)
                   10352:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10353:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10354:       
                   10355:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10356:       if (wav[i] > 1 ) { /* ??? */
                   10357:        LL=LL+A*weight[i];
                   10358:        /*      printf("\ni=%d A=%f L=%lf x[1]=%lf x[2]=%lf ageex=%lf agecens=%lf cens=%d agedc=%lf weight=%lf\n",i,A,L,x[1],x[2],ageexmed[i]*12,agecens[i]*12,cens[i],agedc[i]*12,weight[i]);*/
                   10359:       }
                   10360:     }
                   10361: 
                   10362:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10363:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10364:  
                   10365:   return -2*LL*num/sump;
                   10366: }
                   10367: #endif
                   10368: 
1.126     brouard  10369: /******************* Printing html file ***********/
1.201     brouard  10370: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10371:                  int lastpass, int stepm, int weightopt, char model[],\
                   10372:                  int imx,  double p[],double **matcov,double agemortsup){
                   10373:   int i,k;
                   10374: 
                   10375:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10376:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10377:   for (i=1;i<=2;i++) 
                   10378:     fprintf(fichtm," p[%d] = %lf [%f ; %f]<br>\n",i,p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.199     brouard  10379:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10380:   fprintf(fichtm,"</ul>");
                   10381: 
                   10382: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10383: 
                   10384:  fprintf(fichtm,"\nAge   l<inf>x</inf>     q<inf>x</inf> d(x,x+1)    L<inf>x</inf>     T<inf>x</inf>     e<infx</inf><br>");
                   10385: 
                   10386:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10387:    fprintf(fichtm,"%d %.0lf %lf %.0lf %.0lf %.0lf %lf<br>\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
                   10388: 
                   10389:  
                   10390:   fflush(fichtm);
                   10391: }
                   10392: 
                   10393: /******************* Gnuplot file **************/
1.201     brouard  10394: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10395: 
                   10396:   char dirfileres[132],optfileres[132];
1.164     brouard  10397: 
1.126     brouard  10398:   int ng;
                   10399: 
                   10400: 
                   10401:   /*#ifdef windows */
                   10402:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10403:     /*#endif */
                   10404: 
                   10405: 
                   10406:   strcpy(dirfileres,optionfilefiname);
                   10407:   strcpy(optfileres,"vpl");
1.199     brouard  10408:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10409:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10410:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10411:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10412:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10413: 
                   10414: } 
                   10415: 
1.136     brouard  10416: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10417: {
1.126     brouard  10418: 
1.136     brouard  10419:   /*-------- data file ----------*/
                   10420:   FILE *fic;
                   10421:   char dummy[]="                         ";
1.240     brouard  10422:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10423:   int lstra;
1.136     brouard  10424:   int linei, month, year,iout;
1.302     brouard  10425:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10426:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10427:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10428:   char *stratrunc;
1.223     brouard  10429: 
1.240     brouard  10430:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10431:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10432:   for(v=1;v<NCOVMAX;v++){
                   10433:     DummyV[v]=0;
                   10434:     FixedV[v]=0;
                   10435:   }
1.126     brouard  10436: 
1.240     brouard  10437:   for(v=1; v <=ncovcol;v++){
                   10438:     DummyV[v]=0;
                   10439:     FixedV[v]=0;
                   10440:   }
                   10441:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10442:     DummyV[v]=1;
                   10443:     FixedV[v]=0;
                   10444:   }
                   10445:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10446:     DummyV[v]=0;
                   10447:     FixedV[v]=1;
                   10448:   }
                   10449:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10450:     DummyV[v]=1;
                   10451:     FixedV[v]=1;
                   10452:   }
                   10453:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10454:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10455:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10456:   }
1.339     brouard  10457:   
                   10458:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   10459:   
1.136     brouard  10460:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10461:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10462:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10463:   }
1.126     brouard  10464: 
1.302     brouard  10465:     /* Is it a BOM UTF-8 Windows file? */
                   10466:   /* First data line */
                   10467:   linei=0;
                   10468:   while(fgets(line, MAXLINE, fic)) {
                   10469:     noffset=0;
                   10470:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10471:     {
                   10472:       noffset=noffset+3;
                   10473:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10474:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10475:       fflush(ficlog); return 1;
                   10476:     }
                   10477:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10478:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10479:     {
                   10480:       noffset=noffset+2;
1.304     brouard  10481:       printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
                   10482:       fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
1.302     brouard  10483:       fflush(ficlog); return 1;
                   10484:     }
                   10485:     else if( line[0] == 0 && line[1] == 0)
                   10486:     {
                   10487:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10488:        noffset=noffset+4;
1.304     brouard  10489:        printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
                   10490:        fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
1.302     brouard  10491:        fflush(ficlog); return 1;
                   10492:       }
                   10493:     } else{
                   10494:       ;/*printf(" Not a BOM file\n");*/
                   10495:     }
                   10496:         /* If line starts with a # it is a comment */
                   10497:     if (line[noffset] == '#') {
                   10498:       linei=linei+1;
                   10499:       break;
                   10500:     }else{
                   10501:       break;
                   10502:     }
                   10503:   }
                   10504:   fclose(fic);
                   10505:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10506:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10507:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10508:   }
                   10509:   /* Not a Bom file */
                   10510:   
1.136     brouard  10511:   i=1;
                   10512:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10513:     linei=linei+1;
                   10514:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10515:       if(line[j] == '\t')
                   10516:        line[j] = ' ';
                   10517:     }
                   10518:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10519:       ;
                   10520:     };
                   10521:     line[j+1]=0;  /* Trims blanks at end of line */
                   10522:     if(line[0]=='#'){
                   10523:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10524:       printf("Comment line\n%s\n",line);
                   10525:       continue;
                   10526:     }
                   10527:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10528:     strcpy(line, linetmp);
1.223     brouard  10529:     
                   10530:     /* Loops on waves */
                   10531:     for (j=maxwav;j>=1;j--){
                   10532:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10533:        cutv(stra, strb, line, ' '); 
                   10534:        if(strb[0]=='.') { /* Missing value */
                   10535:          lval=-1;
                   10536:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  10537:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  10538:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10539:            printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);
                   10540:            fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
                   10541:            return 1;
                   10542:          }
                   10543:        }else{
                   10544:          errno=0;
                   10545:          /* what_kind_of_number(strb); */
                   10546:          dval=strtod(strb,&endptr); 
                   10547:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10548:          /* if(strb != endptr && *endptr == '\0') */
                   10549:          /*    dval=dlval; */
                   10550:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10551:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10552:            printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
                   10553:            fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
                   10554:            return 1;
                   10555:          }
                   10556:          cotqvar[j][iv][i]=dval; 
1.341     brouard  10557:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  10558:        }
                   10559:        strcpy(line,stra);
1.223     brouard  10560:       }/* end loop ntqv */
1.225     brouard  10561:       
1.223     brouard  10562:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10563:        cutv(stra, strb, line, ' '); 
                   10564:        if(strb[0]=='.') { /* Missing value */
                   10565:          lval=-1;
                   10566:        }else{
                   10567:          errno=0;
                   10568:          lval=strtol(strb,&endptr,10); 
                   10569:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10570:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10571:            printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th dummy covariate out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv, j,maxwav);
                   10572:            fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d dummy covariate out of %d measured wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv,j,maxwav);fflush(ficlog);
                   10573:            return 1;
                   10574:          }
                   10575:        }
                   10576:        if(lval <-1 || lval >1){
                   10577:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10578:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
1.223     brouard  10579:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10580:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10581:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10582:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10583:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10584:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10585:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10586:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10587:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
1.223     brouard  10588:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10589:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10590:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10591:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10592:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10593:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10594:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10595:          return 1;
                   10596:        }
1.341     brouard  10597:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  10598:        strcpy(line,stra);
1.223     brouard  10599:       }/* end loop ntv */
1.225     brouard  10600:       
1.223     brouard  10601:       /* Statuses  at wave */
1.137     brouard  10602:       cutv(stra, strb, line, ' '); 
1.223     brouard  10603:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10604:        lval=-1;
1.136     brouard  10605:       }else{
1.238     brouard  10606:        errno=0;
                   10607:        lval=strtol(strb,&endptr,10); 
                   10608:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10609:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10610:          printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);
                   10611:          fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);fflush(ficlog);
                   10612:          return 1;
                   10613:        }
1.136     brouard  10614:       }
1.225     brouard  10615:       
1.136     brouard  10616:       s[j][i]=lval;
1.225     brouard  10617:       
1.223     brouard  10618:       /* Date of Interview */
1.136     brouard  10619:       strcpy(line,stra);
                   10620:       cutv(stra, strb,line,' ');
1.169     brouard  10621:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10622:       }
1.169     brouard  10623:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10624:        month=99;
                   10625:        year=9999;
1.136     brouard  10626:       }else{
1.225     brouard  10627:        printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
                   10628:        fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);fflush(ficlog);
                   10629:        return 1;
1.136     brouard  10630:       }
                   10631:       anint[j][i]= (double) year; 
1.302     brouard  10632:       mint[j][i]= (double)month;
                   10633:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10634:       /*       printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
                   10635:       /*       fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
                   10636:       /* } */
1.136     brouard  10637:       strcpy(line,stra);
1.223     brouard  10638:     } /* End loop on waves */
1.225     brouard  10639:     
1.223     brouard  10640:     /* Date of death */
1.136     brouard  10641:     cutv(stra, strb,line,' '); 
1.169     brouard  10642:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10643:     }
1.169     brouard  10644:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10645:       month=99;
                   10646:       year=9999;
                   10647:     }else{
1.141     brouard  10648:       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
1.225     brouard  10649:       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
                   10650:       return 1;
1.136     brouard  10651:     }
                   10652:     andc[i]=(double) year; 
                   10653:     moisdc[i]=(double) month; 
                   10654:     strcpy(line,stra);
                   10655:     
1.223     brouard  10656:     /* Date of birth */
1.136     brouard  10657:     cutv(stra, strb,line,' '); 
1.169     brouard  10658:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10659:     }
1.169     brouard  10660:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10661:       month=99;
                   10662:       year=9999;
                   10663:     }else{
1.141     brouard  10664:       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
                   10665:       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
1.225     brouard  10666:       return 1;
1.136     brouard  10667:     }
                   10668:     if (year==9999) {
1.141     brouard  10669:       printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given.  Exiting.\n",strb, linei,i,line);
                   10670:       fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);
1.225     brouard  10671:       return 1;
                   10672:       
1.136     brouard  10673:     }
                   10674:     annais[i]=(double)(year);
1.302     brouard  10675:     moisnais[i]=(double)(month);
                   10676:     for (j=1;j<=maxwav;j++){
                   10677:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10678:        printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j,(int)moisnais[i],(int)annais[i]);
                   10679:        fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j, (int)moisnais[i],(int)annais[i]);
                   10680:       }
                   10681:     }
                   10682: 
1.136     brouard  10683:     strcpy(line,stra);
1.225     brouard  10684:     
1.223     brouard  10685:     /* Sample weight */
1.136     brouard  10686:     cutv(stra, strb,line,' '); 
                   10687:     errno=0;
                   10688:     dval=strtod(strb,&endptr); 
                   10689:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10690:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10691:       fprintf(ficlog,"Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
1.136     brouard  10692:       fflush(ficlog);
                   10693:       return 1;
                   10694:     }
                   10695:     weight[i]=dval; 
                   10696:     strcpy(line,stra);
1.225     brouard  10697:     
1.223     brouard  10698:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10699:       cutv(stra, strb, line, ' '); 
                   10700:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10701:        lval=-1;
1.311     brouard  10702:        coqvar[iv][i]=NAN; 
                   10703:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10704:       }else{
1.225     brouard  10705:        errno=0;
                   10706:        /* what_kind_of_number(strb); */
                   10707:        dval=strtod(strb,&endptr);
                   10708:        /* if(strb != endptr && *endptr == '\0') */
                   10709:        /*   dval=dlval; */
                   10710:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10711:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10712:          printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);
                   10713:          fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);fflush(ficlog);
                   10714:          return 1;
                   10715:        }
                   10716:        coqvar[iv][i]=dval; 
1.226     brouard  10717:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10718:       }
                   10719:       strcpy(line,stra);
                   10720:     }/* end loop nqv */
1.136     brouard  10721:     
1.223     brouard  10722:     /* Covariate values */
1.136     brouard  10723:     for (j=ncovcol;j>=1;j--){
                   10724:       cutv(stra, strb,line,' '); 
1.223     brouard  10725:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10726:        lval=-1;
1.136     brouard  10727:       }else{
1.225     brouard  10728:        errno=0;
                   10729:        lval=strtol(strb,&endptr,10); 
                   10730:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10731:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);
                   10732:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);fflush(ficlog);
                   10733:          return 1;
                   10734:        }
1.136     brouard  10735:       }
                   10736:       if(lval <-1 || lval >1){
1.225     brouard  10737:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10738:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10739:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10740:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10741:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10742:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10743:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10744:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10745:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10746:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10747:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10748:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10749:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10750:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10751:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10752:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10753:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10754:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10755:        return 1;
1.136     brouard  10756:       }
                   10757:       covar[j][i]=(double)(lval);
                   10758:       strcpy(line,stra);
                   10759:     }  
                   10760:     lstra=strlen(stra);
1.225     brouard  10761:     
1.136     brouard  10762:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10763:       stratrunc = &(stra[lstra-9]);
                   10764:       num[i]=atol(stratrunc);
                   10765:     }
                   10766:     else
                   10767:       num[i]=atol(stra);
                   10768:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10769:       printf("%ld %.lf %.lf %.lf %.lf/%.lf %.lf/%.lf %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d %.lf/%.lf %d\n",num[i],(covar[1][i]), (covar[2][i]),weight[i], (moisnais[i]), (annais[i]), (moisdc[i]), (andc[i]), (mint[1][i]), (anint[1][i]), (s[1][i]),  (mint[2][i]), (anint[2][i]), (s[2][i]),  (mint[3][i]), (anint[3][i]), (s[3][i]),  (mint[4][i]), (anint[4][i]), (s[4][i])); ij=ij+1;}*/
                   10770:     
                   10771:     i=i+1;
                   10772:   } /* End loop reading  data */
1.225     brouard  10773:   
1.136     brouard  10774:   *imax=i-1; /* Number of individuals */
                   10775:   fclose(fic);
1.225     brouard  10776:   
1.136     brouard  10777:   return (0);
1.164     brouard  10778:   /* endread: */
1.225     brouard  10779:   printf("Exiting readdata: ");
                   10780:   fclose(fic);
                   10781:   return (1);
1.223     brouard  10782: }
1.126     brouard  10783: 
1.234     brouard  10784: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10785:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10786:   while (*p2 == ' ')
1.234     brouard  10787:     p2++; 
                   10788:   /* while ((*p1++ = *p2++) !=0) */
                   10789:   /*   ; */
                   10790:   /* do */
                   10791:   /*   while (*p2 == ' ') */
                   10792:   /*     p2++; */
                   10793:   /* while (*p1++ == *p2++); */
                   10794:   *stri=p2; 
1.145     brouard  10795: }
                   10796: 
1.330     brouard  10797: int decoderesult( char resultline[], int nres)
1.230     brouard  10798: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10799: {
1.235     brouard  10800:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10801:   char resultsav[MAXLINE];
1.330     brouard  10802:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10803:   /* int modelresult[MAXLINE]; */
1.230     brouard  10804:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10805: 
1.234     brouard  10806:   removefirstspace(&resultline);
1.332     brouard  10807:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10808: 
1.332     brouard  10809:   strcpy(resultsav,resultline);
1.342     brouard  10810:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  10811:   if (strlen(resultsav) >1){
1.334     brouard  10812:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10813:   }
1.253     brouard  10814:   if(j == 0){ /* Resultline but no = */
                   10815:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10816:     return (0);
                   10817:   }
1.234     brouard  10818:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10819:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
                   10820:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
1.332     brouard  10821:     /* return 1;*/
1.234     brouard  10822:   }
1.334     brouard  10823:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10824:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10825:       cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' (stra is the rest of the resultline to be analyzed in the next loop *//*     resultsav= "V4=1 V5=25.1 V3=0" stra= "V5=25.1 V3=0" strb= "V4=1" */
1.332     brouard  10826:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
1.318     brouard  10827:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10828:       /* If a blank, then strc="V4=" and strd='\0' */
                   10829:       if(strc[0]=='\0'){
                   10830:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10831:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10832:        return 1;
                   10833:       }
1.234     brouard  10834:     }else
                   10835:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10836:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10837:     
1.230     brouard  10838:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10839:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
1.230     brouard  10840:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10841:     /* cptcovsel++;     */
                   10842:     if (nbocc(stra,'=') >0)
                   10843:       strcpy(resultsav,stra); /* and analyzes it */
                   10844:   }
1.235     brouard  10845:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10846:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
1.334     brouard  10847:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332     brouard  10848:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10849:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10850:       match=0;
1.318     brouard  10851:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10852:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10853:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10854:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10855:          break;
                   10856:        }
                   10857:       }
                   10858:       if(match == 0){
1.338     brouard  10859:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
                   10860:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s\n",Tvar[k1], resultline, model);
1.310     brouard  10861:        return 1;
1.234     brouard  10862:       }
1.332     brouard  10863:     }else if(Typevar[k1]==1){ /* Product with age We want to get the position k2 in the resultline of the product k1 in the model line*/
                   10864:       /* We feed resultmodel[k1]=k2; */
                   10865:       match=0;
                   10866:       for(k2=1; k2 <=j;k2++){/* Loop on resultline.  jth occurence of = signs in the result line. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10867:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10868:          modelresult[nres][k2]=k1;/* we found a Vn=1 corrresponding to Vn*age in the model modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.332     brouard  10869:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  10870:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  10871:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10872:          break;
                   10873:        }
                   10874:       }
                   10875:       if(match == 0){
1.338     brouard  10876:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
                   10877:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.332     brouard  10878:       return 1;
                   10879:       }
                   10880:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10881:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10882:       match=0;
1.342     brouard  10883:       /* printf("Decoderesult very first Product Tvardk[k1=%d][1]=%d Tvardk[k1=%d][2]=%d V%d * V%d\n",k1,Tvardk[k1][1],k1,Tvardk[k1][2],Tvardk[k1][1],Tvardk[k1][2]); */
1.332     brouard  10884:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10885:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10886:          /* modelresult[k2]=k1; */
1.342     brouard  10887:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  10888:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10889:        }
                   10890:       }
                   10891:       if(match == 0){
1.338     brouard  10892:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   10893:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10894:        return 1;
                   10895:       }
                   10896:       match=0;
                   10897:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10898:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10899:          /* modelresult[k2]=k1;*/
1.342     brouard  10900:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  10901:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10902:          break;
                   10903:        }
                   10904:       }
                   10905:       if(match == 0){
1.338     brouard  10906:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   10907:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10908:        return 1;
                   10909:       }
                   10910:     }/* End of testing */
1.333     brouard  10911:   }/* End loop cptcovt */
1.235     brouard  10912:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10913:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10914:   for(k2=1; k2 <=j;k2++){ /* j or cptcovs is the number of single covariates used either in the model line as well as in the result line (dummy or quantitative)
                   10915:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10916:     match=0;
1.318     brouard  10917:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332     brouard  10918:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10919:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10920:          resultmodel[nres][k1]=k2;  /* k1th position in the model equation corresponds to k2th position in the result line. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.334     brouard  10921:          modelresult[nres][k2]=k1; /* k1th position in the model equation corresponds to k2th position in the result line. modelresult[1]=2 modelresult[2]=1  modelresult[3]=3  remodelresult[4]=6 modelresult[5]=9 */
1.234     brouard  10922:          ++match;
                   10923:        }
                   10924:       }
                   10925:     }
                   10926:     if(match == 0){
1.338     brouard  10927:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10928:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10929:       return 1;
1.234     brouard  10930:     }else if(match > 1){
1.338     brouard  10931:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10932:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10933:       return 1;
1.234     brouard  10934:     }
                   10935:   }
1.334     brouard  10936:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10937:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10938:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10939:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10940:   /* should correspond to the combination 6 of dummy: V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 1*1 + 0*2 + 1*4 = 5 + (1offset) = 6*/
                   10941:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10942:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10943:   /*    1 0 0 0 */
                   10944:   /*    2 1 0 0 */
                   10945:   /*    3 0 1 0 */ 
1.330     brouard  10946:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10947:   /*    5 0 0 1 */
1.330     brouard  10948:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10949:   /*    7 0 1 1 */
                   10950:   /*    8 1 1 1 */
1.237     brouard  10951:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10952:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10953:   /* V5*age V5 known which value for nres?  */
                   10954:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10955:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* cptcovt number of covariates (excluding 1 and age or age*age) in the MODEL equation.
                   10956:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10957:     /* k counting number of combination of single dummies in the equation model */
                   10958:     /* k4 counting single dummies in the equation model */
                   10959:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10960:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10961:        /* k4+1= (not always if quant in model) position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
1.332     brouard  10962:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
1.330     brouard  10963:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10964:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10965:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10966:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10967:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10968:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10969:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10970:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10971:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10972:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10973:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10974:       k2=(int)Tvarsel[k3]; /* from position k3 in resultline get name k2: nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.330     brouard  10975:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
1.334     brouard  10976:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10977:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10978:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10979:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10980:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10981:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10982:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10983:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  10984:       /* printf("Decoderesult Dummy k=%d, k1=%d precov[nres=%d][k1=%d]=%.f V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k1, nres, k1,precov[nres][k1], k2, k3, (int)Tvalsel[k3], k4); */
1.235     brouard  10985:       k4++;;
1.331     brouard  10986:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10987:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10988:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10989:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10990:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10991:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10992:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10993:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10994:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10995:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10996:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10997:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10998:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10999:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  11000:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  11001:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11002:       /* printf("Decoderesult Quantitative nres=%d,precov[nres=%d][k1=%d]=%.f V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, nres, k1,precov[nres][k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]); */
1.235     brouard  11003:       k4q++;;
1.331     brouard  11004:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   11005:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  11006:       /* Wrong we want the value of variable name Tvar[k1] */
                   11007:       
                   11008:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  11009:       k2=(int)Tvarsel[k3]; /* nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.334     brouard  11010:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  11011:       precov[nres][k1]=Tvalsel[k3];
1.342     brouard  11012:       /* printf("Decoderesult Dummy with age k=%d, k1=%d precov[nres=%d][k1=%d]=%.f Tvar[%d]=V%d k2=Tvarsel[%d]=%d Tvalsel[%d]=%d\n",k, k1, nres, k1,precov[nres][k1], k1, Tvar[k1], k3,(int)Tvarsel[k3], k3, (int)Tvalsel[k3]); */
1.331     brouard  11013:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  11014:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  11015:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  11016:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  11017:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  11018:       /* printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]); */
1.331     brouard  11019:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  11020:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  11021:       /* printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]); */
1.330     brouard  11022:     }else{
1.332     brouard  11023:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11024:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  11025:     }
                   11026:   }
1.234     brouard  11027:   
1.334     brouard  11028:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  11029:   return (0);
                   11030: }
1.235     brouard  11031: 
1.230     brouard  11032: int decodemodel( char model[], int lastobs)
                   11033:  /**< This routine decodes the model and returns:
1.224     brouard  11034:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11035:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11036:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11037:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11038:        * - cptcovage number of covariates with age*products =2
                   11039:        * - cptcovs number of simple covariates
1.339     brouard  11040:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  11041:        * - Tvar[k] is the id of the kth covariate Tvar[1]@12 {1, 2, 3, 8, 10, 11, 8, 3, 7, 8, 5, 6}, thus Tvar[5=V7*V8]=10
1.339     brouard  11042:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  11043:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  11044:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11045:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11046:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11047:        */
1.319     brouard  11048: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.136     brouard  11049: {
1.238     brouard  11050:   int i, j, k, ks, v;
1.227     brouard  11051:   int  j1, k1, k2, k3, k4;
1.136     brouard  11052:   char modelsav[80];
1.145     brouard  11053:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  11054:   char *strpt;
1.136     brouard  11055: 
1.145     brouard  11056:   /*removespace(model);*/
1.136     brouard  11057:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  11058:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  11059:     if (strstr(model,"AGE") !=0){
1.192     brouard  11060:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11061:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  11062:       return 1;
                   11063:     }
1.141     brouard  11064:     if (strstr(model,"v") !=0){
1.338     brouard  11065:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11066:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  11067:       return 1;
                   11068:     }
1.187     brouard  11069:     strcpy(modelsav,model); 
                   11070:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  11071:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  11072:       if(strpt != model){
1.338     brouard  11073:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11074:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11075:  corresponding column of parameters.\n",model);
1.338     brouard  11076:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  11077:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  11078:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  11079:        return 1;
1.225     brouard  11080:       }
1.187     brouard  11081:       nagesqr=1;
                   11082:       if (strstr(model,"+age*age") !=0)
1.234     brouard  11083:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  11084:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  11085:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  11086:       else 
1.234     brouard  11087:        substrchaine(modelsav, model, "age*age");
1.187     brouard  11088:     }else
                   11089:       nagesqr=0;
                   11090:     if (strlen(modelsav) >1){
                   11091:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11092:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  11093:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  11094:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  11095:                     * cst, age and age*age 
                   11096:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11097:       /* including age products which are counted in cptcovage.
                   11098:        * but the covariates which are products must be treated 
                   11099:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  11100:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   11101:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  11102:       
                   11103:       
1.187     brouard  11104:       /*   Design
                   11105:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11106:        *  <          ncovcol=8                >
                   11107:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11108:        *   k=  1    2      3       4     5       6      7        8
                   11109:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   11110:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  11111:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11112:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  11113:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11114:        *  Tage[++cptcovage]=k
                   11115:        *       if products, new covar are created after ncovcol with k1
                   11116:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11117:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11118:        *  Tvard[k1][1]=m Tvard[k1][2]=m; Tvard[1][1]=5 (V5) Tvard[1][2]=6 Tvard[2][1]=7 (V7) Tvard[2][2]=8
                   11119:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11120:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11121:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   11122:        *  <          ncovcol=8                >
                   11123:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11124:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   11125:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  11126:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  11127:        * p Tprod[1]@2={                         6, 5}
                   11128:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11129:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11130:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  11131:        *How to reorganize? Tvars(orted)
1.187     brouard  11132:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11133:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11134:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11135:        * Struct []
                   11136:        */
1.225     brouard  11137:       
1.187     brouard  11138:       /* This loop fills the array Tvar from the string 'model'.*/
                   11139:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11140:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11141:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11142:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11143:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11144:       /*       k=1 Tvar[1]=2 (from V2) */
                   11145:       /*       k=5 Tvar[5] */
                   11146:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  11147:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  11148:       /*       } */
1.198     brouard  11149:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  11150:       /*
                   11151:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  11152:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11153:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11154:       }
1.187     brouard  11155:       cptcovage=0;
1.319     brouard  11156:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11157:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11158:                                         modelsav==V2+V1+V5*age+V4+V3*age strb=V3*age stra=V2+V1V5*age+V4 */    /* <model> "V5+V4+V3+V4*V3+V5*age+V1*age+V1" strb="V5" stra="V4+V3+V4*V3+V5*age+V1*age+V1" */
                   11159:        if (nbocc(modelsav,'+')==0)
                   11160:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  11161:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11162:        /*scanf("%d",i);*/
1.319     brouard  11163:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   11164:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
1.234     brouard  11165:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   11166:            /* covar is not filled and then is empty */
                   11167:            cptcovprod--;
                   11168:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  11169:            Tvar[k]=atoi(stre);  /* V2+V1+V5*age+V4+V3*age Tvar[5]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
1.234     brouard  11170:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  11171:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11172:            Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.234     brouard  11173:            /*printf("stre=%s ", stre);*/
                   11174:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   11175:            cptcovprod--;
                   11176:            cutl(stre,strb,strc,'V');
                   11177:            Tvar[k]=atoi(stre);
                   11178:            Typevar[k]=1;  /* 1 for age product */
                   11179:            cptcovage++;
                   11180:            Tage[cptcovage]=k;
                   11181:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   11182:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   11183:            cptcovn++;
                   11184:            cptcovprodnoage++;k1++;
                   11185:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339     brouard  11186:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  11187:                                                because this model-covariate is a construction we invent a new column
                   11188:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  11189:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  11190:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339     brouard  11191:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  11192:            /* Please remark that the new variables are model dependent */
                   11193:            /* If we have 4 variable but the model uses only 3, like in
                   11194:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11195:             *  k=     1     2       3   4     5        6        7       8
                   11196:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11197:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11198:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11199:             */
1.339     brouard  11200:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  11201:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11202:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  11203:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  11204:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  11205:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  11206:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  11207:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  11208:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11209:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11210:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  11211:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  11212:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339     brouard  11213:            if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
                   11214:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  11215:              /* Computes the new covariate which is a product of
                   11216:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339     brouard  11217:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11218:              }
                   11219:            } /*End of FixedV */
1.234     brouard  11220:          } /* End age is not in the model */
                   11221:        } /* End if model includes a product */
1.319     brouard  11222:        else { /* not a product */
1.234     brouard  11223:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11224:          /*  scanf("%d",i);*/
                   11225:          cutl(strd,strc,strb,'V');
                   11226:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11227:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11228:          Tvar[k]=atoi(strd);
                   11229:          Typevar[k]=0;  /* 0 for simple covariates */
                   11230:        }
                   11231:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11232:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11233:                                  scanf("%d",i);*/
1.187     brouard  11234:       } /* end of loop + on total covariates */
                   11235:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11236:   } /* end if strlen(model == 0) */
1.136     brouard  11237:   
                   11238:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11239:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11240:   
1.136     brouard  11241:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11242:      printf("cptcovprod=%d ", cptcovprod);
                   11243:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11244:      scanf("%d ",i);*/
                   11245: 
                   11246: 
1.230     brouard  11247: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11248:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11249: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11250:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11251:    k =           1    2   3     4       5       6      7      8        9
                   11252:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11253:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11254:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11255:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11256:          Tmodelind[combination of covar]=k;
1.225     brouard  11257: */  
                   11258: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11259:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11260:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
1.226     brouard  11261:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11262:   printf("Model=1+age+%s\n\
1.227     brouard  11263: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11264: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11265: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
1.318     brouard  11266:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11267: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11268: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11269: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
1.342     brouard  11270:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   11271:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.343   ! brouard  11272:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt loop on k from model */
1.234     brouard  11273:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11274:       Fixed[k]= 0;
                   11275:       Dummy[k]= 0;
1.225     brouard  11276:       ncoveff++;
1.232     brouard  11277:       ncovf++;
1.234     brouard  11278:       nsd++;
                   11279:       modell[k].maintype= FTYPE;
                   11280:       TvarsD[nsd]=Tvar[k];
                   11281:       TvarsDind[nsd]=k;
1.330     brouard  11282:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11283:       TvarF[ncovf]=Tvar[k];
                   11284:       TvarFind[ncovf]=k;
                   11285:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11286:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  11287:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   11288:     }else if( Tposprod[k]>0  &&  Typevar[k]==2 && FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* Needs a fixed product Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol */
1.234     brouard  11289:       Fixed[k]= 0;
                   11290:       Dummy[k]= 0;
                   11291:       ncoveff++;
                   11292:       ncovf++;
                   11293:       modell[k].maintype= FTYPE;
                   11294:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11295:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11296:       TvarFind[ncovf]=k;
1.230     brouard  11297:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11298:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11299:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
1.227     brouard  11300:       Fixed[k]= 0;
                   11301:       Dummy[k]= 1;
1.230     brouard  11302:       nqfveff++;
1.234     brouard  11303:       modell[k].maintype= FTYPE;
                   11304:       modell[k].subtype= FQ;
                   11305:       nsq++;
1.334     brouard  11306:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11307:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11308:       ncovf++;
1.234     brouard  11309:       TvarF[ncovf]=Tvar[k];
                   11310:       TvarFind[ncovf]=k;
1.231     brouard  11311:       TvarFQ[nqfveff]=Tvar[k]-ncovcol; /* TvarFQ[1]=V2-1=1st in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.230     brouard  11312:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.242     brouard  11313:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  11314:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11315:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11316:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11317:       ncovvt++;
                   11318:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11319:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   11320: 
1.227     brouard  11321:       Fixed[k]= 1;
                   11322:       Dummy[k]= 0;
1.225     brouard  11323:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11324:       modell[k].maintype= VTYPE;
                   11325:       modell[k].subtype= VD;
                   11326:       nsd++;
                   11327:       TvarsD[nsd]=Tvar[k];
                   11328:       TvarsDind[nsd]=k;
1.330     brouard  11329:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11330:       ncovv++; /* Only simple time varying variables */
                   11331:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11332:       TvarVind[ncovv]=k; /* TvarVind[2]=2  TvarVind[3]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  11333:       TvarVD[ntveff]=Tvar[k]; /* TvarVD[1]=V4  TvarVD[2]=V3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
                   11334:       TvarVDind[ntveff]=k; /* TvarVDind[1]=2 TvarVDind[2]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
1.228     brouard  11335:       printf("Quasi Tmodelind[%d]=%d,Tvar[Tmodelind[%d]]=V%d, ncovcol=%d, nqv=%d,Tvar[k]- ncovcol-nqv=%d\n",ntveff,k,ntveff,Tvar[k], ncovcol, nqv,Tvar[k]- ncovcol-nqv);
                   11336:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11337:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  11338:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11339:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11340:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11341:       ncovvt++;
                   11342:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11343:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   11344:       
1.234     brouard  11345:       Fixed[k]= 1;
                   11346:       Dummy[k]= 1;
                   11347:       nqtveff++;
                   11348:       modell[k].maintype= VTYPE;
                   11349:       modell[k].subtype= VQ;
                   11350:       ncovv++; /* Only simple time varying variables */
                   11351:       nsq++;
1.334     brouard  11352:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */ /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary here) */
                   11353:       TvarsQind[nsq]=k; /* For single quantitative covariate gives the model position of each single quantitative covariate *//* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.234     brouard  11354:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11355:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  11356:       TvarVQ[nqtveff]=Tvar[k]; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   11357:       TvarVQind[nqtveff]=k; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
1.234     brouard  11358:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11359:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.342     brouard  11360:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
                   11361:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  11362:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11363:       ncova++;
                   11364:       TvarA[ncova]=Tvar[k];
                   11365:       TvarAind[ncova]=k;
1.231     brouard  11366:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11367:        Fixed[k]= 2;
                   11368:        Dummy[k]= 2;
                   11369:        modell[k].maintype= ATYPE;
                   11370:        modell[k].subtype= APFD;
                   11371:        /* ncoveff++; */
1.227     brouard  11372:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11373:        Fixed[k]= 2;
                   11374:        Dummy[k]= 3;
                   11375:        modell[k].maintype= ATYPE;
                   11376:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11377:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11378:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11379:        Fixed[k]= 3;
                   11380:        Dummy[k]= 2;
                   11381:        modell[k].maintype= ATYPE;
                   11382:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11383:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11384:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11385:        Fixed[k]= 3;
                   11386:        Dummy[k]= 3;
                   11387:        modell[k].maintype= ATYPE;
                   11388:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11389:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11390:       }
1.339     brouard  11391:     }else if (Typevar[k] == 2) {  /* product Vn * Vm without age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
                   11392:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   11393:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   11394:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   11395:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1} k1=1 first product but second time varying because of V3 */
                   11396:       ncovvt++;
                   11397:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   11398:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11399:       ncovvt++;
                   11400:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   11401:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   11402: 
                   11403: 
                   11404:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   11405:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11406:          Fixed[k]= 1;
                   11407:          Dummy[k]= 0;
                   11408:          modell[k].maintype= FTYPE;
                   11409:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11410:          ncovf++; /* Fixed variables without age */
                   11411:          TvarF[ncovf]=Tvar[k];
                   11412:          TvarFind[ncovf]=k;
1.339     brouard  11413:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   11414:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11415:          Dummy[k]= 1;
                   11416:          modell[k].maintype= FTYPE;
                   11417:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11418:          ncovf++; /* Varying variables without age */
                   11419:          TvarF[ncovf]=Tvar[k];
                   11420:          TvarFind[ncovf]=k;
1.339     brouard  11421:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11422:          Fixed[k]= 1;
                   11423:          Dummy[k]= 0;
                   11424:          modell[k].maintype= VTYPE;
                   11425:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11426:          ncovv++; /* Varying variables without age */
1.339     brouard  11427:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   11428:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   11429:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11430:          Fixed[k]= 1;
                   11431:          Dummy[k]= 1;
                   11432:          modell[k].maintype= VTYPE;
                   11433:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11434:          ncovv++; /* Varying variables without age */
                   11435:          TvarV[ncovv]=Tvar[k];
                   11436:          TvarVind[ncovv]=k;
                   11437:        }
1.339     brouard  11438:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   11439:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   11440:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11441:          Dummy[k]= 1;
                   11442:          modell[k].maintype= FTYPE;
                   11443:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11444:          ncovf++; /* Fixed variables without age */
                   11445:          TvarF[ncovf]=Tvar[k];
                   11446:          TvarFind[ncovf]=k;
1.339     brouard  11447:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11448:          Fixed[k]= 1;
                   11449:          Dummy[k]= 1;
                   11450:          modell[k].maintype= VTYPE;
                   11451:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11452:          ncovv++; /* Varying variables without age */
                   11453:          TvarV[ncovv]=Tvar[k];
                   11454:          TvarVind[ncovv]=k;
1.339     brouard  11455:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11456:          Fixed[k]= 1;
                   11457:          Dummy[k]= 1;
                   11458:          modell[k].maintype= VTYPE;
                   11459:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11460:          ncovv++; /* Varying variables without age */
                   11461:          TvarV[ncovv]=Tvar[k];
                   11462:          TvarVind[ncovv]=k;
                   11463:          ncovv++; /* Varying variables without age */
                   11464:          TvarV[ncovv]=Tvar[k];
                   11465:          TvarVind[ncovv]=k;
                   11466:        }
1.339     brouard  11467:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11468:        if(Tvard[k1][2] <=ncovcol){
                   11469:          Fixed[k]= 1;
                   11470:          Dummy[k]= 1;
                   11471:          modell[k].maintype= VTYPE;
                   11472:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11473:          ncovv++; /* Varying variables without age */
                   11474:          TvarV[ncovv]=Tvar[k];
                   11475:          TvarVind[ncovv]=k;
                   11476:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11477:          Fixed[k]= 1;
                   11478:          Dummy[k]= 1;
                   11479:          modell[k].maintype= VTYPE;
                   11480:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11481:          ncovv++; /* Varying variables without age */
                   11482:          TvarV[ncovv]=Tvar[k];
                   11483:          TvarVind[ncovv]=k;
                   11484:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11485:          Fixed[k]= 1;
                   11486:          Dummy[k]= 0;
                   11487:          modell[k].maintype= VTYPE;
                   11488:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11489:          ncovv++; /* Varying variables without age */
                   11490:          TvarV[ncovv]=Tvar[k];
                   11491:          TvarVind[ncovv]=k;
                   11492:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11493:          Fixed[k]= 1;
                   11494:          Dummy[k]= 1;
                   11495:          modell[k].maintype= VTYPE;
                   11496:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11497:          ncovv++; /* Varying variables without age */
                   11498:          TvarV[ncovv]=Tvar[k];
                   11499:          TvarVind[ncovv]=k;
                   11500:        }
1.339     brouard  11501:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11502:        if(Tvard[k1][2] <=ncovcol){
                   11503:          Fixed[k]= 1;
                   11504:          Dummy[k]= 1;
                   11505:          modell[k].maintype= VTYPE;
                   11506:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11507:          ncovv++; /* Varying variables without age */
                   11508:          TvarV[ncovv]=Tvar[k];
                   11509:          TvarVind[ncovv]=k;
                   11510:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11511:          Fixed[k]= 1;
                   11512:          Dummy[k]= 1;
                   11513:          modell[k].maintype= VTYPE;
                   11514:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11515:          ncovv++; /* Varying variables without age */
                   11516:          TvarV[ncovv]=Tvar[k];
                   11517:          TvarVind[ncovv]=k;
                   11518:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11519:          Fixed[k]= 1;
                   11520:          Dummy[k]= 1;
                   11521:          modell[k].maintype= VTYPE;
                   11522:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11523:          ncovv++; /* Varying variables without age */
                   11524:          TvarV[ncovv]=Tvar[k];
                   11525:          TvarVind[ncovv]=k;
                   11526:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11527:          Fixed[k]= 1;
                   11528:          Dummy[k]= 1;
                   11529:          modell[k].maintype= VTYPE;
                   11530:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11531:          ncovv++; /* Varying variables without age */
                   11532:          TvarV[ncovv]=Tvar[k];
                   11533:          TvarVind[ncovv]=k;
                   11534:        }
1.227     brouard  11535:       }else{
1.240     brouard  11536:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11537:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11538:       } /*end k1*/
1.225     brouard  11539:     }else{
1.226     brouard  11540:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11541:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
1.225     brouard  11542:     }
1.342     brouard  11543:     /* printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]); */
                   11544:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  11545:     fprintf(ficlog,"Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
                   11546:   }
                   11547:   /* Searching for doublons in the model */
                   11548:   for(k1=1; k1<= cptcovt;k1++){
                   11549:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11550:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11551:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11552:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11553:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11554:            printf("Error duplication in the model=1+age+%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[k1],Dummy[k1]);
                   11555:            fprintf(ficlog,"Error duplication in the model=1+age+%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[k1],Dummy[k1]); fflush(ficlog);
1.234     brouard  11556:            return(1);
                   11557:          }
                   11558:        }else if (Typevar[k1] ==2){
                   11559:          k3=Tposprod[k1];
                   11560:          k4=Tposprod[k2];
                   11561:          if( ((Tvard[k3][1]== Tvard[k4][1])&&(Tvard[k3][2]== Tvard[k4][2])) || ((Tvard[k3][1]== Tvard[k4][2])&&(Tvard[k3][2]== Tvard[k4][1])) ){
1.338     brouard  11562:            printf("Error duplication in the model=1+age+%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
                   11563:            fprintf(ficlog,"Error duplication in the model=1+age+%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
1.234     brouard  11564:            return(1);
                   11565:          }
                   11566:        }
1.227     brouard  11567:       }
                   11568:     }
1.225     brouard  11569:   }
                   11570:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11571:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11572:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11573:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11574:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11575:   /*endread:*/
1.225     brouard  11576:   printf("Exiting decodemodel: ");
                   11577:   return (1);
1.136     brouard  11578: }
                   11579: 
1.169     brouard  11580: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11581: {/* Check ages at death */
1.136     brouard  11582:   int i, m;
1.218     brouard  11583:   int firstone=0;
                   11584:   
1.136     brouard  11585:   for (i=1; i<=imx; i++) {
                   11586:     for(m=2; (m<= maxwav); m++) {
                   11587:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11588:        anint[m][i]=9999;
1.216     brouard  11589:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11590:          s[m][i]=-1;
1.136     brouard  11591:       }
                   11592:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11593:        *nberr = *nberr + 1;
1.218     brouard  11594:        if(firstone == 0){
                   11595:          firstone=1;
1.260     brouard  11596:        printf("Warning (#%d)! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown but status is a death state %d at wave %d. If you don't know the vital status, please enter -2. If he/she is still alive but don't know the state, please code with '-1 or '.'. Here, we do not believe in a death, skipped.\nOther similar cases in log file\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
1.218     brouard  11597:        }
1.262     brouard  11598:        fprintf(ficlog,"Warning (#%d)! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown but status is a death state %d at wave %d. If you don't know the vital status, please enter -2. If he/she is still alive but don't know the state, please code with '-1 or '.'. Here, we do not believe in a death, skipped.\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
1.260     brouard  11599:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11600:       }
                   11601:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11602:        (*nberr)++;
1.259     brouard  11603:        printf("Error (#%d)! Month of death of individual %ld on line %d was unknown (%2d) (year of death is %4d) and status is a death state %d at wave %d. Please impute an arbitrary (or not) month and rerun. Currently this transition to death will be skipped (status is set to -2).\nOther similar cases in log file\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
1.262     brouard  11604:        fprintf(ficlog,"Error (#%d)! Month of death of individual %ld on line %d was unknown (%2d) (year of death is %4d) and status is a death state %d at wave %d. Please impute an arbitrary (or not) month and rerun. Currently this transition to death will be skipped (status is set to -2).\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
1.259     brouard  11605:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11606:       }
                   11607:     }
                   11608:   }
                   11609: 
                   11610:   for (i=1; i<=imx; i++)  {
                   11611:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11612:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11613:       if(s[m][i] >0  || s[m][i]==-1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ /* What if s[m][i]=-1 */
1.136     brouard  11614:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11615:          if(agedc[i]>0){
                   11616:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11617:              agev[m][i]=agedc[i];
1.214     brouard  11618:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11619:            }else {
1.136     brouard  11620:              if ((int)andc[i]!=9999){
                   11621:                nbwarn++;
                   11622:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11623:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11624:                agev[m][i]=-1;
                   11625:              }
                   11626:            }
1.169     brouard  11627:          } /* agedc > 0 */
1.214     brouard  11628:        } /* end if */
1.136     brouard  11629:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11630:                                 years but with the precision of a month */
                   11631:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11632:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11633:            agev[m][i]=1;
                   11634:          else if(agev[m][i] < *agemin){ 
                   11635:            *agemin=agev[m][i];
                   11636:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11637:          }
                   11638:          else if(agev[m][i] >*agemax){
                   11639:            *agemax=agev[m][i];
1.156     brouard  11640:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11641:          }
                   11642:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11643:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11644:        } /* en if 9*/
1.136     brouard  11645:        else { /* =9 */
1.214     brouard  11646:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11647:          agev[m][i]=1;
                   11648:          s[m][i]=-1;
                   11649:        }
                   11650:       }
1.214     brouard  11651:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11652:        agev[m][i]=1;
1.214     brouard  11653:       else{
                   11654:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11655:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11656:        agev[m][i]=0;
                   11657:       }
                   11658:     } /* End for lastpass */
                   11659:   }
1.136     brouard  11660:     
                   11661:   for (i=1; i<=imx; i++)  {
                   11662:     for(m=firstpass; (m<=lastpass); m++){
                   11663:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11664:        (*nberr)++;
1.136     brouard  11665:        printf("Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);     
                   11666:        fprintf(ficlog,"Error: on wave %d of individual %d status %d > (nlstate+ndeath)=(%d+%d)=%d\n",m,i,s[m][i],nlstate, ndeath, nlstate+ndeath);     
                   11667:        return 1;
                   11668:       }
                   11669:     }
                   11670:   }
                   11671: 
                   11672:   /*for (i=1; i<=imx; i++){
                   11673:   for (m=firstpass; (m<lastpass); m++){
                   11674:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11675: }
                   11676: 
                   11677: }*/
                   11678: 
                   11679: 
1.139     brouard  11680:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11681:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11682: 
                   11683:   return (0);
1.164     brouard  11684:  /* endread:*/
1.136     brouard  11685:     printf("Exiting calandcheckages: ");
                   11686:     return (1);
                   11687: }
                   11688: 
1.172     brouard  11689: #if defined(_MSC_VER)
                   11690: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11691: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11692: //#include "stdafx.h"
                   11693: //#include <stdio.h>
                   11694: //#include <tchar.h>
                   11695: //#include <windows.h>
                   11696: //#include <iostream>
                   11697: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11698: 
                   11699: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11700: 
                   11701: BOOL IsWow64()
                   11702: {
                   11703:        BOOL bIsWow64 = FALSE;
                   11704: 
                   11705:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11706:        //  (HANDLE, PBOOL);
                   11707: 
                   11708:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11709: 
                   11710:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11711:        const char funcName[] = "IsWow64Process";
                   11712:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11713:                GetProcAddress(module, funcName);
                   11714: 
                   11715:        if (NULL != fnIsWow64Process)
                   11716:        {
                   11717:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11718:                        &bIsWow64))
                   11719:                        //throw std::exception("Unknown error");
                   11720:                        printf("Unknown error\n");
                   11721:        }
                   11722:        return bIsWow64 != FALSE;
                   11723: }
                   11724: #endif
1.177     brouard  11725: 
1.191     brouard  11726: void syscompilerinfo(int logged)
1.292     brouard  11727: {
                   11728: #include <stdint.h>
                   11729: 
                   11730:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11731:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11732:    /* /GS /W3 /Gy
                   11733:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11734:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11735:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11736:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11737:    */ 
                   11738:    /* 64 bits */
1.185     brouard  11739:    /*
                   11740:      /GS /W3 /Gy
                   11741:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11742:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11743:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11744:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11745:    /* Optimization are useless and O3 is slower than O2 */
                   11746:    /*
                   11747:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11748:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11749:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11750:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11751:    */
1.186     brouard  11752:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11753:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11754:       /PDB:"visual studio
                   11755:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11756:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11757:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11758:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11759:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11760:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11761:       uiAccess='false'"
                   11762:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11763:       /NOLOGO /TLBID:1
                   11764:    */
1.292     brouard  11765: 
                   11766: 
1.177     brouard  11767: #if defined __INTEL_COMPILER
1.178     brouard  11768: #if defined(__GNUC__)
                   11769:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11770: #endif
1.177     brouard  11771: #elif defined(__GNUC__) 
1.179     brouard  11772: #ifndef  __APPLE__
1.174     brouard  11773: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11774: #endif
1.177     brouard  11775:    struct utsname sysInfo;
1.178     brouard  11776:    int cross = CROSS;
                   11777:    if (cross){
                   11778:           printf("Cross-");
1.191     brouard  11779:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11780:    }
1.174     brouard  11781: #endif
                   11782: 
1.191     brouard  11783:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11784: #if defined(__clang__)
1.191     brouard  11785:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11786: #endif
                   11787: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11788:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11789: #endif
                   11790: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11791:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11792: #endif
                   11793: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11794:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11795: #endif
                   11796: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11797:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11798: #endif
                   11799: #if defined(_MSC_VER)
1.191     brouard  11800:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11801: #endif
                   11802: #if defined(__PGI)
1.191     brouard  11803:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11804: #endif
                   11805: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11806:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11807: #endif
1.191     brouard  11808:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11809:    
1.167     brouard  11810: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11811: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11812:     // Windows (x64 and x86)
1.191     brouard  11813:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11814: #elif __unix__ // all unices, not all compilers
                   11815:     // Unix
1.191     brouard  11816:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11817: #elif __linux__
                   11818:     // linux
1.191     brouard  11819:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11820: #elif __APPLE__
1.174     brouard  11821:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11822:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11823: #endif
                   11824: 
                   11825: /*  __MINGW32__          */
                   11826: /*  __CYGWIN__  */
                   11827: /* __MINGW64__  */
                   11828: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11829: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11830: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11831: /* _WIN64  // Defined for applications for Win64. */
                   11832: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11833: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11834: 
1.167     brouard  11835: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11836:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11837: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11838:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11839: #else
1.191     brouard  11840:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11841: #endif
                   11842: 
1.169     brouard  11843: #if defined(__GNUC__)
                   11844: # if defined(__GNUC_PATCHLEVEL__)
                   11845: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11846:                             + __GNUC_MINOR__ * 100 \
                   11847:                             + __GNUC_PATCHLEVEL__)
                   11848: # else
                   11849: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11850:                             + __GNUC_MINOR__ * 100)
                   11851: # endif
1.174     brouard  11852:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11853:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11854: 
                   11855:    if (uname(&sysInfo) != -1) {
                   11856:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11857:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.176     brouard  11858:    }
                   11859:    else
                   11860:       perror("uname() error");
1.179     brouard  11861:    //#ifndef __INTEL_COMPILER 
                   11862: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11863:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11864:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11865: #endif
1.169     brouard  11866: #endif
1.172     brouard  11867: 
1.286     brouard  11868:    //   void main ()
1.172     brouard  11869:    //   {
1.169     brouard  11870: #if defined(_MSC_VER)
1.174     brouard  11871:    if (IsWow64()){
1.191     brouard  11872:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11873:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11874:    }
                   11875:    else{
1.191     brouard  11876:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11877:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11878:    }
1.172     brouard  11879:    //     printf("\nPress Enter to continue...");
                   11880:    //     getchar();
                   11881:    //   }
                   11882: 
1.169     brouard  11883: #endif
                   11884:    
1.167     brouard  11885: 
1.219     brouard  11886: }
1.136     brouard  11887: 
1.219     brouard  11888: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11889:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11890:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11891:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11892:   /* double ftolpl = 1.e-10; */
1.180     brouard  11893:   double age, agebase, agelim;
1.203     brouard  11894:   double tot;
1.180     brouard  11895: 
1.202     brouard  11896:   strcpy(filerespl,"PL_");
                   11897:   strcat(filerespl,fileresu);
                   11898:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11899:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11900:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11901:   }
1.288     brouard  11902:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11903:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11904:   pstamp(ficrespl);
1.288     brouard  11905:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11906:   fprintf(ficrespl,"#Age ");
                   11907:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11908:   fprintf(ficrespl,"\n");
1.180     brouard  11909:   
1.219     brouard  11910:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11911: 
1.219     brouard  11912:   agebase=ageminpar;
                   11913:   agelim=agemaxpar;
1.180     brouard  11914: 
1.227     brouard  11915:   /* i1=pow(2,ncoveff); */
1.234     brouard  11916:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11917:   if (cptcovn < 1){i1=1;}
1.180     brouard  11918: 
1.337     brouard  11919:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11920:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11921:       k=TKresult[nres];
1.338     brouard  11922:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11923:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11924:       /*       continue; */
1.235     brouard  11925: 
1.238     brouard  11926:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11927:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11928:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11929:       /* k=k+1; */
                   11930:       /* to clean */
1.332     brouard  11931:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11932:       fprintf(ficrespl,"#******");
                   11933:       printf("#******");
                   11934:       fprintf(ficlog,"#******");
1.337     brouard  11935:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
1.332     brouard  11936:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11937:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11938:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11939:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11940:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11941:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11942:       }
                   11943:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11944:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11945:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11946:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11947:       /* } */
1.238     brouard  11948:       fprintf(ficrespl,"******\n");
                   11949:       printf("******\n");
                   11950:       fprintf(ficlog,"******\n");
                   11951:       if(invalidvarcomb[k]){
                   11952:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11953:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11954:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11955:        continue;
                   11956:       }
1.219     brouard  11957: 
1.238     brouard  11958:       fprintf(ficrespl,"#Age ");
1.337     brouard  11959:       /* for(j=1;j<=cptcoveff;j++) { */
                   11960:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11961:       /* } */
                   11962:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11963:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11964:       }
                   11965:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11966:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11967:     
1.238     brouard  11968:       for (age=agebase; age<=agelim; age++){
                   11969:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  11970:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   11971:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11972:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  11973:        /* for(j=1;j<=cptcoveff;j++) */
                   11974:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11975:        for(j=1;j<=cptcovs;j++)
                   11976:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11977:        tot=0.;
                   11978:        for(i=1; i<=nlstate;i++){
                   11979:          tot +=  prlim[i][i];
                   11980:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11981:        }
                   11982:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11983:       } /* Age */
                   11984:       /* was end of cptcod */
1.337     brouard  11985:     } /* nres */
                   11986:   /* } /\* for each combination *\/ */
1.219     brouard  11987:   return 0;
1.180     brouard  11988: }
                   11989: 
1.218     brouard  11990: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
1.288     brouard  11991:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11992:        
                   11993:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11994:    * at any age between ageminpar and agemaxpar
                   11995:         */
1.235     brouard  11996:   int i, j, k, i1, nres=0 ;
1.217     brouard  11997:   /* double ftolpl = 1.e-10; */
                   11998:   double age, agebase, agelim;
                   11999:   double tot;
1.218     brouard  12000:   /* double ***mobaverage; */
                   12001:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  12002: 
                   12003:   strcpy(fileresplb,"PLB_");
                   12004:   strcat(fileresplb,fileresu);
                   12005:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  12006:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12007:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  12008:   }
1.288     brouard  12009:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12010:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  12011:   pstamp(ficresplb);
1.288     brouard  12012:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  12013:   fprintf(ficresplb,"#Age ");
                   12014:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12015:   fprintf(ficresplb,"\n");
                   12016:   
1.218     brouard  12017:   
                   12018:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12019:   
                   12020:   agebase=ageminpar;
                   12021:   agelim=agemaxpar;
                   12022:   
                   12023:   
1.227     brouard  12024:   i1=pow(2,cptcoveff);
1.218     brouard  12025:   if (cptcovn < 1){i1=1;}
1.227     brouard  12026:   
1.238     brouard  12027:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  12028:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12029:       k=TKresult[nres];
                   12030:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12031:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12032:      /*        continue; */
                   12033:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  12034:       fprintf(ficresplb,"#******");
                   12035:       printf("#******");
                   12036:       fprintf(ficlog,"#******");
1.338     brouard  12037:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
                   12038:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12039:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12040:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12041:       }
1.338     brouard  12042:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   12043:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12044:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12045:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12046:       /* } */
                   12047:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12048:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12049:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12050:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12051:       /* } */
1.238     brouard  12052:       fprintf(ficresplb,"******\n");
                   12053:       printf("******\n");
                   12054:       fprintf(ficlog,"******\n");
                   12055:       if(invalidvarcomb[k]){
                   12056:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   12057:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   12058:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   12059:        continue;
                   12060:       }
1.218     brouard  12061:     
1.238     brouard  12062:       fprintf(ficresplb,"#Age ");
1.338     brouard  12063:       for(j=1;j<=cptcovs;j++) {
                   12064:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12065:       }
                   12066:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   12067:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  12068:     
                   12069:     
1.238     brouard  12070:       for (age=agebase; age<=agelim; age++){
                   12071:        /* for (age=agebase; age<=agebase; age++){ */
                   12072:        if(mobilavproj > 0){
                   12073:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   12074:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12075:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  12076:        }else if (mobilavproj == 0){
                   12077:          printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   12078:          fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   12079:          exit(1);
                   12080:        }else{
                   12081:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  12082:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  12083:          /* printf("TOTOT\n"); */
                   12084:           /* exit(1); */
1.238     brouard  12085:        }
                   12086:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  12087:        for(j=1;j<=cptcovs;j++)
                   12088:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  12089:        tot=0.;
                   12090:        for(i=1; i<=nlstate;i++){
                   12091:          tot +=  bprlim[i][i];
                   12092:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   12093:        }
                   12094:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   12095:       } /* Age */
                   12096:       /* was end of cptcod */
1.255     brouard  12097:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  12098:     /* } /\* end of any combination *\/ */
1.238     brouard  12099:   } /* end of nres */  
1.218     brouard  12100:   /* hBijx(p, bage, fage); */
                   12101:   /* fclose(ficrespijb); */
                   12102:   
                   12103:   return 0;
1.217     brouard  12104: }
1.218     brouard  12105:  
1.180     brouard  12106: int hPijx(double *p, int bage, int fage){
                   12107:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  12108:   /* to be optimized with precov */
1.180     brouard  12109:   int stepsize;
                   12110:   int agelim;
                   12111:   int hstepm;
                   12112:   int nhstepm;
1.235     brouard  12113:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  12114: 
                   12115:   double agedeb;
                   12116:   double ***p3mat;
                   12117: 
1.337     brouard  12118:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   12119:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   12120:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12121:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   12122:   }
                   12123:   printf("Computing pij: result on file '%s' \n", filerespij);
                   12124:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   12125:   
                   12126:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12127:   /*if (stepm<=24) stepsize=2;*/
                   12128:   
                   12129:   agelim=AGESUP;
                   12130:   hstepm=stepsize*YEARM; /* Every year of age */
                   12131:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   12132:   
                   12133:   /* hstepm=1;   aff par mois*/
                   12134:   pstamp(ficrespij);
                   12135:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   12136:   i1= pow(2,cptcoveff);
                   12137:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12138:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12139:   /*   k=k+1;  */
                   12140:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12141:     k=TKresult[nres];
1.338     brouard  12142:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12143:     /* for(k=1; k<=i1;k++){ */
                   12144:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   12145:     /*         continue; */
                   12146:     fprintf(ficrespij,"\n#****** ");
                   12147:     for(j=1;j<=cptcovs;j++){
                   12148:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12149:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12150:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12151:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12152:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12153:     }
                   12154:     fprintf(ficrespij,"******\n");
                   12155:     
                   12156:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   12157:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   12158:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   12159:       
                   12160:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12161:       
                   12162:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12163:       oldm=oldms;savm=savms;
                   12164:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   12165:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   12166:       for(i=1; i<=nlstate;i++)
                   12167:        for(j=1; j<=nlstate+ndeath;j++)
                   12168:          fprintf(ficrespij," %1d-%1d",i,j);
                   12169:       fprintf(ficrespij,"\n");
                   12170:       for (h=0; h<=nhstepm; h++){
                   12171:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12172:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  12173:        for(i=1; i<=nlstate;i++)
                   12174:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12175:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  12176:        fprintf(ficrespij,"\n");
                   12177:       }
1.337     brouard  12178:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12179:       fprintf(ficrespij,"\n");
1.180     brouard  12180:     }
1.337     brouard  12181:   }
                   12182:   /*}*/
                   12183:   return 0;
1.180     brouard  12184: }
1.218     brouard  12185:  
                   12186:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  12187:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  12188:     /* To be optimized with precov */
1.217     brouard  12189:   int stepsize;
1.218     brouard  12190:   /* int agelim; */
                   12191:        int ageminl;
1.217     brouard  12192:   int hstepm;
                   12193:   int nhstepm;
1.238     brouard  12194:   int h, i, i1, j, k, nres;
1.218     brouard  12195:        
1.217     brouard  12196:   double agedeb;
                   12197:   double ***p3mat;
1.218     brouard  12198:        
                   12199:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   12200:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   12201:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12202:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   12203:   }
                   12204:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   12205:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   12206:   
                   12207:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   12208:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  12209:   
1.218     brouard  12210:   /* agelim=AGESUP; */
1.289     brouard  12211:   ageminl=AGEINF; /* was 30 */
1.218     brouard  12212:   hstepm=stepsize*YEARM; /* Every year of age */
                   12213:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   12214:   
                   12215:   /* hstepm=1;   aff par mois*/
                   12216:   pstamp(ficrespijb);
1.255     brouard  12217:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
1.227     brouard  12218:   i1= pow(2,cptcoveff);
1.218     brouard  12219:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12220:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   12221:   /*   k=k+1;  */
1.238     brouard  12222:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  12223:     k=TKresult[nres];
1.338     brouard  12224:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12225:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12226:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12227:     /*         continue; */
                   12228:     fprintf(ficrespijb,"\n#****** ");
                   12229:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12230:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12231:       /* for(j=1;j<=cptcoveff;j++) */
                   12232:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12233:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12234:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12235:     }
                   12236:     fprintf(ficrespijb,"******\n");
                   12237:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12238:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12239:       continue;
                   12240:     }
                   12241:     
                   12242:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12243:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12244:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12245:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm+0.1)-1; /* Typically 20 years = 20*12/6=40 or 55*12/24=27.5-1.1=>27 */
                   12246:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12247:       
                   12248:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12249:       
                   12250:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12251:       /* and memory limitations if stepm is small */
                   12252:       
                   12253:       /* oldm=oldms;savm=savms; */
                   12254:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12255:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12256:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12257:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12258:       for(i=1; i<=nlstate;i++)
                   12259:        for(j=1; j<=nlstate+ndeath;j++)
                   12260:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12261:       fprintf(ficrespijb,"\n");
                   12262:       for (h=0; h<=nhstepm; h++){
                   12263:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12264:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12265:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12266:        for(i=1; i<=nlstate;i++)
                   12267:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12268:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12269:        fprintf(ficrespijb,"\n");
1.337     brouard  12270:       }
                   12271:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12272:       fprintf(ficrespijb,"\n");
                   12273:     } /* end age deb */
                   12274:     /* } /\* end combination *\/ */
1.238     brouard  12275:   } /* end nres */
1.218     brouard  12276:   return 0;
                   12277:  } /*  hBijx */
1.217     brouard  12278: 
1.180     brouard  12279: 
1.136     brouard  12280: /***********************************************/
                   12281: /**************** Main Program *****************/
                   12282: /***********************************************/
                   12283: 
                   12284: int main(int argc, char *argv[])
                   12285: {
                   12286: #ifdef GSL
                   12287:   const gsl_multimin_fminimizer_type *T;
                   12288:   size_t iteri = 0, it;
                   12289:   int rval = GSL_CONTINUE;
                   12290:   int status = GSL_SUCCESS;
                   12291:   double ssval;
                   12292: #endif
                   12293:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12294:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12295:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12296:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12297:   int jj, ll, li, lj, lk;
1.136     brouard  12298:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12299:   int num_filled;
1.136     brouard  12300:   int itimes;
                   12301:   int NDIM=2;
                   12302:   int vpopbased=0;
1.235     brouard  12303:   int nres=0;
1.258     brouard  12304:   int endishere=0;
1.277     brouard  12305:   int noffset=0;
1.274     brouard  12306:   int ncurrv=0; /* Temporary variable */
                   12307:   
1.164     brouard  12308:   char ca[32], cb[32];
1.136     brouard  12309:   /*  FILE *fichtm; *//* Html File */
                   12310:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12311:   struct stat info;
1.191     brouard  12312:   double agedeb=0.;
1.194     brouard  12313: 
                   12314:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12315:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12316: 
1.165     brouard  12317:   double fret;
1.191     brouard  12318:   double dum=0.; /* Dummy variable */
1.136     brouard  12319:   double ***p3mat;
1.218     brouard  12320:   /* double ***mobaverage; */
1.319     brouard  12321:   double wald;
1.164     brouard  12322: 
                   12323:   char line[MAXLINE];
1.197     brouard  12324:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12325: 
1.234     brouard  12326:   char  modeltemp[MAXLINE];
1.332     brouard  12327:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12328:   
1.136     brouard  12329:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12330:   char *tok, *val; /* pathtot */
1.334     brouard  12331:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12332:   int c,  h , cpt, c2;
1.191     brouard  12333:   int jl=0;
                   12334:   int i1, j1, jk, stepsize=0;
1.194     brouard  12335:   int count=0;
                   12336: 
1.164     brouard  12337:   int *tab; 
1.136     brouard  12338:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12339:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12340:   /* double anprojf, mprojf, jprojf; */
                   12341:   /* double jintmean,mintmean,aintmean;   */
                   12342:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12343:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12344:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12345:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12346:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12347:   int mobilav=0,popforecast=0;
1.191     brouard  12348:   int hstepm=0, nhstepm=0;
1.136     brouard  12349:   int agemortsup;
                   12350:   float  sumlpop=0.;
                   12351:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12352:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12353: 
1.191     brouard  12354:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12355:   double ftolpl=FTOL;
                   12356:   double **prlim;
1.217     brouard  12357:   double **bprlim;
1.317     brouard  12358:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12359:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12360:   double ***paramstart; /* Matrix of starting parameter values */
                   12361:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12362:   double **matcov; /* Matrix of covariance */
1.203     brouard  12363:   double **hess; /* Hessian matrix */
1.136     brouard  12364:   double ***delti3; /* Scale */
                   12365:   double *delti; /* Scale */
                   12366:   double ***eij, ***vareij;
                   12367:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12368: 
1.136     brouard  12369:   double *epj, vepp;
1.164     brouard  12370: 
1.273     brouard  12371:   double dateprev1, dateprev2;
1.296     brouard  12372:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12373:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12374: 
1.217     brouard  12375: 
1.136     brouard  12376:   double **ximort;
1.145     brouard  12377:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12378:   int *dcwave;
                   12379: 
1.164     brouard  12380:   char z[1]="c";
1.136     brouard  12381: 
                   12382:   /*char  *strt;*/
                   12383:   char strtend[80];
1.126     brouard  12384: 
1.164     brouard  12385: 
1.126     brouard  12386: /*   setlocale (LC_ALL, ""); */
                   12387: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12388: /*   textdomain (PACKAGE); */
                   12389: /*   setlocale (LC_CTYPE, ""); */
                   12390: /*   setlocale (LC_MESSAGES, ""); */
                   12391: 
                   12392:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12393:   rstart_time = time(NULL);  
                   12394:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12395:   start_time = *localtime(&rstart_time);
1.126     brouard  12396:   curr_time=start_time;
1.157     brouard  12397:   /*tml = *localtime(&start_time.tm_sec);*/
                   12398:   /* strcpy(strstart,asctime(&tml)); */
                   12399:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12400: 
                   12401: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12402: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12403: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12404: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12405: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12406: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12407: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12408: /*   strt=asctime(&tmg); */
                   12409: /*   printf("Time(after) =%s",strstart);  */
                   12410: /*  (void) time (&time_value);
                   12411: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12412: *  tm = *localtime(&time_value);
                   12413: *  strstart=asctime(&tm);
                   12414: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12415: */
                   12416: 
                   12417:   nberr=0; /* Number of errors and warnings */
                   12418:   nbwarn=0;
1.184     brouard  12419: #ifdef WIN32
                   12420:   _getcwd(pathcd, size);
                   12421: #else
1.126     brouard  12422:   getcwd(pathcd, size);
1.184     brouard  12423: #endif
1.191     brouard  12424:   syscompilerinfo(0);
1.196     brouard  12425:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12426:   if(argc <=1){
                   12427:     printf("\nEnter the parameter file name: ");
1.205     brouard  12428:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12429:       printf("ERROR Empty parameter file name\n");
                   12430:       goto end;
                   12431:     }
1.126     brouard  12432:     i=strlen(pathr);
                   12433:     if(pathr[i-1]=='\n')
                   12434:       pathr[i-1]='\0';
1.156     brouard  12435:     i=strlen(pathr);
1.205     brouard  12436:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12437:       pathr[i-1]='\0';
1.205     brouard  12438:     }
                   12439:     i=strlen(pathr);
                   12440:     if( i==0 ){
                   12441:       printf("ERROR Empty parameter file name\n");
                   12442:       goto end;
                   12443:     }
                   12444:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12445:       printf("Pathr |%s|\n",pathr);
                   12446:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12447:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12448:       strcpy (pathtot, val);
                   12449:       if(pathr[0] == '\0') break; /* Dirty */
                   12450:     }
                   12451:   }
1.281     brouard  12452:   else if (argc<=2){
                   12453:     strcpy(pathtot,argv[1]);
                   12454:   }
1.126     brouard  12455:   else{
                   12456:     strcpy(pathtot,argv[1]);
1.281     brouard  12457:     strcpy(z,argv[2]);
                   12458:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12459:   }
                   12460:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12461:   /*cygwin_split_path(pathtot,path,optionfile);
                   12462:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12463:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12464: 
                   12465:   /* Split argv[0], imach program to get pathimach */
                   12466:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12467:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12468:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12469:  /*   strcpy(pathimach,argv[0]); */
                   12470:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12471:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12472:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12473: #ifdef WIN32
                   12474:   _chdir(path); /* Can be a relative path */
                   12475:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12476: #else
1.126     brouard  12477:   chdir(path); /* Can be a relative path */
1.184     brouard  12478:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12479: #endif
                   12480:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12481:   strcpy(command,"mkdir ");
                   12482:   strcat(command,optionfilefiname);
                   12483:   if((outcmd=system(command)) != 0){
1.169     brouard  12484:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12485:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12486:     /* fclose(ficlog); */
                   12487: /*     exit(1); */
                   12488:   }
                   12489: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12490: /*     perror("mkdir"); */
                   12491: /*   } */
                   12492: 
                   12493:   /*-------- arguments in the command line --------*/
                   12494: 
1.186     brouard  12495:   /* Main Log file */
1.126     brouard  12496:   strcat(filelog, optionfilefiname);
                   12497:   strcat(filelog,".log");    /* */
                   12498:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12499:     printf("Problem with logfile %s\n",filelog);
                   12500:     goto end;
                   12501:   }
                   12502:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12503:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12504:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12505:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12506:  path=%s \n\
                   12507:  optionfile=%s\n\
                   12508:  optionfilext=%s\n\
1.156     brouard  12509:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12510: 
1.197     brouard  12511:   syscompilerinfo(1);
1.167     brouard  12512: 
1.126     brouard  12513:   printf("Local time (at start):%s",strstart);
                   12514:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12515:   fflush(ficlog);
                   12516: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12517: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12518: 
                   12519:   /* */
                   12520:   strcpy(fileres,"r");
                   12521:   strcat(fileres, optionfilefiname);
1.201     brouard  12522:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12523:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12524:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12525: 
1.186     brouard  12526:   /* Main ---------arguments file --------*/
1.126     brouard  12527: 
                   12528:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12529:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12530:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12531:     fflush(ficlog);
1.149     brouard  12532:     /* goto end; */
                   12533:     exit(70); 
1.126     brouard  12534:   }
                   12535: 
                   12536:   strcpy(filereso,"o");
1.201     brouard  12537:   strcat(filereso,fileresu);
1.126     brouard  12538:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12539:     printf("Problem with Output resultfile: %s\n", filereso);
                   12540:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12541:     fflush(ficlog);
                   12542:     goto end;
                   12543:   }
1.278     brouard  12544:       /*-------- Rewriting parameter file ----------*/
                   12545:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12546:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12547:   strcat(rfileres,".");    /* */
                   12548:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12549:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12550:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12551:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12552:     fflush(ficlog);
                   12553:     goto end;
                   12554:   }
                   12555:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12556: 
1.278     brouard  12557:                                      
1.126     brouard  12558:   /* Reads comments: lines beginning with '#' */
                   12559:   numlinepar=0;
1.277     brouard  12560:   /* Is it a BOM UTF-8 Windows file? */
                   12561:   /* First parameter line */
1.197     brouard  12562:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12563:     noffset=0;
                   12564:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12565:     {
                   12566:       noffset=noffset+3;
                   12567:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12568:     }
1.302     brouard  12569: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12570:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12571:     {
                   12572:       noffset=noffset+2;
                   12573:       printf("# File is an UTF16BE BOM file\n");
                   12574:     }
                   12575:     else if( line[0] == 0 && line[1] == 0)
                   12576:     {
                   12577:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12578:        noffset=noffset+4;
                   12579:        printf("# File is an UTF16BE BOM file\n");
                   12580:       }
                   12581:     } else{
                   12582:       ;/*printf(" Not a BOM file\n");*/
                   12583:     }
                   12584:   
1.197     brouard  12585:     /* If line starts with a # it is a comment */
1.277     brouard  12586:     if (line[noffset] == '#') {
1.197     brouard  12587:       numlinepar++;
                   12588:       fputs(line,stdout);
                   12589:       fputs(line,ficparo);
1.278     brouard  12590:       fputs(line,ficres);
1.197     brouard  12591:       fputs(line,ficlog);
                   12592:       continue;
                   12593:     }else
                   12594:       break;
                   12595:   }
                   12596:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12597:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12598:     if (num_filled != 5) {
                   12599:       printf("Should be 5 parameters\n");
1.283     brouard  12600:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12601:     }
1.126     brouard  12602:     numlinepar++;
1.197     brouard  12603:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12604:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12605:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12606:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12607:   }
                   12608:   /* Second parameter line */
                   12609:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12610:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12611:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12612:     if (line[0] == '#') {
                   12613:       numlinepar++;
1.283     brouard  12614:       printf("%s",line);
                   12615:       fprintf(ficres,"%s",line);
                   12616:       fprintf(ficparo,"%s",line);
                   12617:       fprintf(ficlog,"%s",line);
1.197     brouard  12618:       continue;
                   12619:     }else
                   12620:       break;
                   12621:   }
1.223     brouard  12622:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   12623:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12624:     if (num_filled != 11) {
                   12625:       printf("Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1  nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
1.209     brouard  12626:       printf("but line=%s\n",line);
1.283     brouard  12627:       fprintf(ficlog,"Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1  nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
                   12628:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12629:     }
1.286     brouard  12630:     if( lastpass > maxwav){
                   12631:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12632:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12633:       fflush(ficlog);
                   12634:       goto end;
                   12635:     }
                   12636:       printf("ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
1.283     brouard  12637:     fprintf(ficparo,"ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
1.286     brouard  12638:     fprintf(ficres,"ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, 0, weightopt);
1.283     brouard  12639:     fprintf(ficlog,"ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
1.126     brouard  12640:   }
1.203     brouard  12641:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12642:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12643:   /* Third parameter line */
                   12644:   while(fgets(line, MAXLINE, ficpar)) {
                   12645:     /* If line starts with a # it is a comment */
                   12646:     if (line[0] == '#') {
                   12647:       numlinepar++;
1.283     brouard  12648:       printf("%s",line);
                   12649:       fprintf(ficres,"%s",line);
                   12650:       fprintf(ficparo,"%s",line);
                   12651:       fprintf(ficlog,"%s",line);
1.197     brouard  12652:       continue;
                   12653:     }else
                   12654:       break;
                   12655:   }
1.201     brouard  12656:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12657:     if (num_filled != 1){
1.302     brouard  12658:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12659:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12660:       model[0]='\0';
                   12661:       goto end;
                   12662:     }
                   12663:     else{
                   12664:       if (model[0]=='+'){
                   12665:        for(i=1; i<=strlen(model);i++)
                   12666:          modeltemp[i-1]=model[i];
1.201     brouard  12667:        strcpy(model,modeltemp); 
1.197     brouard  12668:       }
                   12669:     }
1.338     brouard  12670:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12671:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12672:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12673:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12674:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12675:   }
                   12676:   /* fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */
                   12677:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12678:   /* printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
1.283     brouard  12679:   /* fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model); */
                   12680:   /* fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model); */
1.126     brouard  12681:   fflush(ficlog);
1.190     brouard  12682:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12683:   if(model[0]=='#'){
1.279     brouard  12684:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12685:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12686:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12687:     if(mle != -1){
1.279     brouard  12688:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter vectors and subdiagonal covariance matrix.\n");
1.187     brouard  12689:       exit(1);
                   12690:     }
                   12691:   }
1.126     brouard  12692:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12693:     ungetc(c,ficpar);
                   12694:     fgets(line, MAXLINE, ficpar);
                   12695:     numlinepar++;
1.195     brouard  12696:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12697:       z[0]=line[1];
1.342     brouard  12698:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343   ! brouard  12699:       debugILK=1;printf("DebugILK\n");
1.195     brouard  12700:     }
                   12701:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12702:     fputs(line, stdout);
                   12703:     //puts(line);
1.126     brouard  12704:     fputs(line,ficparo);
                   12705:     fputs(line,ficlog);
                   12706:   }
                   12707:   ungetc(c,ficpar);
                   12708: 
                   12709:    
1.290     brouard  12710:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12711:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12712:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  12713:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   12714:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  12715:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12716:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12717:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12718:   */
                   12719:   if (strlen(model)>1) 
1.187     brouard  12720:     ncovmodel=2+nbocc(model,'+')+1; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7,age*age makes 3*/
1.145     brouard  12721:   else
1.187     brouard  12722:     ncovmodel=2; /* Constant and age */
1.133     brouard  12723:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12724:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12725:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12726:     printf("Too complex model for current IMaCh: npar=(nlstate+ndeath-1)*nlstate*ncovmodel=%d >= %d(MAXPARM) or nlstate=%d >= %d(NLSTATEMAX) or ndeath=%d >= %d(NDEATHMAX) or ncovmodel=(k+age+#of+signs)=%d(NCOVMAX) >= %d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
                   12727:     fprintf(ficlog,"Too complex model for current IMaCh: %d >=%d(MAXPARM) or %d >=%d(NLSTATEMAX) or %d >=%d(NDEATHMAX) or %d(NCOVMAX) >=%d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
                   12728:     fflush(stdout);
                   12729:     fclose (ficlog);
                   12730:     goto end;
                   12731:   }
1.126     brouard  12732:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12733:   delti=delti3[1][1];
                   12734:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12735:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12736: /* We could also provide initial parameters values giving by simple logistic regression 
                   12737:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12738:       /* for(i=1;i<nlstate;i++){ */
                   12739:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12740:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12741:       /* } */
1.126     brouard  12742:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12743:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12744:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12745:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12746:     fclose (ficparo);
                   12747:     fclose (ficlog);
                   12748:     goto end;
                   12749:     exit(0);
1.220     brouard  12750:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12751:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12752:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12753:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12754:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12755:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12756:     hess=matrix(1,npar,1,npar);
1.220     brouard  12757:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12758:     /* Read guessed parameters */
1.126     brouard  12759:     /* Reads comments: lines beginning with '#' */
                   12760:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12761:       ungetc(c,ficpar);
                   12762:       fgets(line, MAXLINE, ficpar);
                   12763:       numlinepar++;
1.141     brouard  12764:       fputs(line,stdout);
1.126     brouard  12765:       fputs(line,ficparo);
                   12766:       fputs(line,ficlog);
                   12767:     }
                   12768:     ungetc(c,ficpar);
                   12769:     
                   12770:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12771:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12772:     for(i=1; i <=nlstate; i++){
1.234     brouard  12773:       j=0;
1.126     brouard  12774:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12775:        if(jj==i) continue;
                   12776:        j++;
1.292     brouard  12777:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12778:          ungetc(c,ficpar);
                   12779:          fgets(line, MAXLINE, ficpar);
                   12780:          numlinepar++;
                   12781:          fputs(line,stdout);
                   12782:          fputs(line,ficparo);
                   12783:          fputs(line,ficlog);
                   12784:        }
                   12785:        ungetc(c,ficpar);
1.234     brouard  12786:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12787:        if ((i1 != i) || (j1 != jj)){
                   12788:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12789: It might be a problem of design; if ncovcol and the model are correct\n \
                   12790: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12791:          exit(1);
                   12792:        }
                   12793:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12794:        if(mle==1)
                   12795:          printf("%1d%1d",i,jj);
                   12796:        fprintf(ficlog,"%1d%1d",i,jj);
                   12797:        for(k=1; k<=ncovmodel;k++){
                   12798:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12799:          if(mle==1){
                   12800:            printf(" %lf",param[i][j][k]);
                   12801:            fprintf(ficlog," %lf",param[i][j][k]);
                   12802:          }
                   12803:          else
                   12804:            fprintf(ficlog," %lf",param[i][j][k]);
                   12805:          fprintf(ficparo," %lf",param[i][j][k]);
                   12806:        }
                   12807:        fscanf(ficpar,"\n");
                   12808:        numlinepar++;
                   12809:        if(mle==1)
                   12810:          printf("\n");
                   12811:        fprintf(ficlog,"\n");
                   12812:        fprintf(ficparo,"\n");
1.126     brouard  12813:       }
                   12814:     }  
                   12815:     fflush(ficlog);
1.234     brouard  12816:     
1.251     brouard  12817:     /* Reads parameters values */
1.126     brouard  12818:     p=param[1][1];
1.251     brouard  12819:     pstart=paramstart[1][1];
1.126     brouard  12820:     
                   12821:     /* Reads comments: lines beginning with '#' */
                   12822:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12823:       ungetc(c,ficpar);
                   12824:       fgets(line, MAXLINE, ficpar);
                   12825:       numlinepar++;
1.141     brouard  12826:       fputs(line,stdout);
1.126     brouard  12827:       fputs(line,ficparo);
                   12828:       fputs(line,ficlog);
                   12829:     }
                   12830:     ungetc(c,ficpar);
                   12831: 
                   12832:     for(i=1; i <=nlstate; i++){
                   12833:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12834:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12835:        if ( (i1-i) * (j1-j) != 0){
                   12836:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12837:          exit(1);
                   12838:        }
                   12839:        printf("%1d%1d",i,j);
                   12840:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12841:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12842:        for(k=1; k<=ncovmodel;k++){
                   12843:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12844:          printf(" %le",delti3[i][j][k]);
                   12845:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12846:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12847:        }
                   12848:        fscanf(ficpar,"\n");
                   12849:        numlinepar++;
                   12850:        printf("\n");
                   12851:        fprintf(ficparo,"\n");
                   12852:        fprintf(ficlog,"\n");
1.126     brouard  12853:       }
                   12854:     }
                   12855:     fflush(ficlog);
1.234     brouard  12856:     
1.145     brouard  12857:     /* Reads covariance matrix */
1.126     brouard  12858:     delti=delti3[1][1];
1.220     brouard  12859:                
                   12860:                
1.126     brouard  12861:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
1.220     brouard  12862:                
1.126     brouard  12863:     /* Reads comments: lines beginning with '#' */
                   12864:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12865:       ungetc(c,ficpar);
                   12866:       fgets(line, MAXLINE, ficpar);
                   12867:       numlinepar++;
1.141     brouard  12868:       fputs(line,stdout);
1.126     brouard  12869:       fputs(line,ficparo);
                   12870:       fputs(line,ficlog);
                   12871:     }
                   12872:     ungetc(c,ficpar);
1.220     brouard  12873:                
1.126     brouard  12874:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12875:     hess=matrix(1,npar,1,npar);
1.131     brouard  12876:     for(i=1; i <=npar; i++)
                   12877:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12878:                
1.194     brouard  12879:     /* Scans npar lines */
1.126     brouard  12880:     for(i=1; i <=npar; i++){
1.226     brouard  12881:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12882:       if(count != 3){
1.226     brouard  12883:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12884: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12885: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12886:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12887: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12888: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12889:        exit(1);
1.220     brouard  12890:       }else{
1.226     brouard  12891:        if(mle==1)
                   12892:          printf("%1d%1d%d",i1,j1,jk);
                   12893:       }
                   12894:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12895:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12896:       for(j=1; j <=i; j++){
1.226     brouard  12897:        fscanf(ficpar," %le",&matcov[i][j]);
                   12898:        if(mle==1){
                   12899:          printf(" %.5le",matcov[i][j]);
                   12900:        }
                   12901:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12902:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12903:       }
                   12904:       fscanf(ficpar,"\n");
                   12905:       numlinepar++;
                   12906:       if(mle==1)
1.220     brouard  12907:                                printf("\n");
1.126     brouard  12908:       fprintf(ficlog,"\n");
                   12909:       fprintf(ficparo,"\n");
                   12910:     }
1.194     brouard  12911:     /* End of read covariance matrix npar lines */
1.126     brouard  12912:     for(i=1; i <=npar; i++)
                   12913:       for(j=i+1;j<=npar;j++)
1.226     brouard  12914:        matcov[i][j]=matcov[j][i];
1.126     brouard  12915:     
                   12916:     if(mle==1)
                   12917:       printf("\n");
                   12918:     fprintf(ficlog,"\n");
                   12919:     
                   12920:     fflush(ficlog);
                   12921:     
                   12922:   }    /* End of mle != -3 */
1.218     brouard  12923:   
1.186     brouard  12924:   /*  Main data
                   12925:    */
1.290     brouard  12926:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12927:   /* num=lvector(1,n); */
                   12928:   /* moisnais=vector(1,n); */
                   12929:   /* annais=vector(1,n); */
                   12930:   /* moisdc=vector(1,n); */
                   12931:   /* andc=vector(1,n); */
                   12932:   /* weight=vector(1,n); */
                   12933:   /* agedc=vector(1,n); */
                   12934:   /* cod=ivector(1,n); */
                   12935:   /* for(i=1;i<=n;i++){ */
                   12936:   num=lvector(firstobs,lastobs);
                   12937:   moisnais=vector(firstobs,lastobs);
                   12938:   annais=vector(firstobs,lastobs);
                   12939:   moisdc=vector(firstobs,lastobs);
                   12940:   andc=vector(firstobs,lastobs);
                   12941:   weight=vector(firstobs,lastobs);
                   12942:   agedc=vector(firstobs,lastobs);
                   12943:   cod=ivector(firstobs,lastobs);
                   12944:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12945:     num[i]=0;
                   12946:     moisnais[i]=0;
                   12947:     annais[i]=0;
                   12948:     moisdc[i]=0;
                   12949:     andc[i]=0;
                   12950:     agedc[i]=0;
                   12951:     cod[i]=0;
                   12952:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12953:   }
1.290     brouard  12954:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12955:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12956:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12957:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12958:   tab=ivector(1,NCOVMAX);
1.144     brouard  12959:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12960:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  12961: 
1.136     brouard  12962:   /* Reads data from file datafile */
                   12963:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12964:     goto end;
                   12965: 
                   12966:   /* Calculation of the number of parameters from char model */
1.234     brouard  12967:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12968:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12969:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12970:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12971:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12972:   */
                   12973:   
                   12974:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12975:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12976:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12977:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12978:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12979:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12980:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12981:   TvarF=ivector(1,NCOVMAX); /*  */
                   12982:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12983:   TvarV=ivector(1,NCOVMAX); /*  */
                   12984:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12985:   TvarA=ivector(1,NCOVMAX); /*  */
                   12986:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12987:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12988:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12989:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12990:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12991:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12992:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12993:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12994:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  12995:   TvarVV=ivector(1,NCOVMAX); /*  */
                   12996:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12997: 
1.230     brouard  12998:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12999:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  13000:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13001:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13002:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  13003:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13004:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13005:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13006:   */
                   13007:   /* For model-covariate k tells which data-covariate to use but
                   13008:     because this model-covariate is a construction we invent a new column
                   13009:     ncovcol + k1
                   13010:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13011:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  13012:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13013:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  13014:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13015:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  13016:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  13017:   */
1.145     brouard  13018:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   13019:   Tvard=imatrix(1,NCOVMAX,1,2); /* n=Tvard[k1][1]  and m=Tvard[k1][2] gives the couple n,m of the k1 th product Vn*Vm
1.141     brouard  13020:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   13021:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  13022:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  13023:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  13024:                         4 covariates (3 plus signs)
                   13025:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  13026:                           */  
                   13027:   for(i=1;i<NCOVMAX;i++)
                   13028:     Tage[i]=0;
1.230     brouard  13029:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  13030:                                * individual dummy, fixed or varying:
                   13031:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   13032:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  13033:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   13034:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   13035:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   13036:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   13037:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  13038:                                * individual quantitative, fixed or varying:
                   13039:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   13040:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   13041:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  13042: /* Main decodemodel */
                   13043: 
1.187     brouard  13044: 
1.223     brouard  13045:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  13046:     goto end;
                   13047: 
1.137     brouard  13048:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   13049:     nbwarn++;
                   13050:     printf("Warning: The value of parameter lastobs=%d is big compared to the \n  effective number of cases imx=%d, please adjust, \n  otherwise you are allocating more memory than necessary.\n",lastobs, imx); 
                   13051:     fprintf(ficlog,"Warning: The value of parameter lastobs=%d is big compared to the \n  effective number of cases imx=%d, please adjust, \n  otherwise you are allocating more memory than necessary.\n",lastobs, imx); 
                   13052:   }
1.136     brouard  13053:     /*  if(mle==1){*/
1.137     brouard  13054:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   13055:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  13056:   }
                   13057: 
                   13058:     /*-calculation of age at interview from date of interview and age at death -*/
                   13059:   agev=matrix(1,maxwav,1,imx);
                   13060: 
                   13061:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   13062:     goto end;
                   13063: 
1.126     brouard  13064: 
1.136     brouard  13065:   agegomp=(int)agemin;
1.290     brouard  13066:   free_vector(moisnais,firstobs,lastobs);
                   13067:   free_vector(annais,firstobs,lastobs);
1.126     brouard  13068:   /* free_matrix(mint,1,maxwav,1,n);
                   13069:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  13070:   /* free_vector(moisdc,1,n); */
                   13071:   /* free_vector(andc,1,n); */
1.145     brouard  13072:   /* */
                   13073:   
1.126     brouard  13074:   wav=ivector(1,imx);
1.214     brouard  13075:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13076:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13077:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   13078:   dh=imatrix(1,lastpass-firstpass+2,1,imx); /* We are adding a wave if status is unknown at last wave but death occurs after last wave.*/
                   13079:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   13080:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  13081:    
                   13082:   /* Concatenates waves */
1.214     brouard  13083:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   13084:      Death is a valid wave (if date is known).
                   13085:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   13086:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   13087:      and mw[mi+1][i]. dh depends on stepm.
                   13088:   */
                   13089: 
1.126     brouard  13090:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  13091:   /* Concatenates waves */
1.145     brouard  13092:  
1.290     brouard  13093:   free_vector(moisdc,firstobs,lastobs);
                   13094:   free_vector(andc,firstobs,lastobs);
1.215     brouard  13095: 
1.126     brouard  13096:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   13097:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   13098:   ncodemax[1]=1;
1.145     brouard  13099:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  13100:   cptcoveff=0;
1.220     brouard  13101:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  13102:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
1.227     brouard  13103:   }
                   13104:   
                   13105:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  13106:   invalidvarcomb=ivector(0, ncovcombmax); 
                   13107:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  13108:     invalidvarcomb[i]=0;
                   13109:   
1.211     brouard  13110:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  13111:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  13112:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  13113:   
1.200     brouard  13114:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  13115:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  13116:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  13117:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   13118:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   13119:    * (currently 0 or 1) in the data.
                   13120:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   13121:    * corresponding modality (h,j).
                   13122:    */
                   13123: 
1.145     brouard  13124:   h=0;
                   13125:   /*if (cptcovn > 0) */
1.126     brouard  13126:   m=pow(2,cptcoveff);
                   13127:  
1.144     brouard  13128:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  13129:           * For k=4 covariates, h goes from 1 to m=2**k
                   13130:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   13131:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  13132:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   13133:           *______________________________   *______________________
                   13134:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   13135:           *     2     2     1     1     1   *     1     0  0  0  1 
                   13136:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   13137:           *     4     2     2     1     1   *     3     0  0  1  1 
                   13138:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   13139:           *     6     2     1     2     1   *     5     0  1  0  1 
                   13140:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   13141:           *     8     2     2     2     1   *     7     0  1  1  1 
                   13142:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   13143:           *    10     2     1     1     2   *     9     1  0  0  1 
                   13144:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   13145:           *    12     2     2     1     2   *    11     1  0  1  1 
                   13146:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   13147:           *    14     2     1     2     2   *    13     1  1  0  1 
                   13148:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   13149:           *    16     2     2     2     2   *    15     1  1  1  1          
                   13150:           */                                     
1.212     brouard  13151:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  13152:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   13153:      * and the value of each covariate?
                   13154:      * V1=1, V2=1, V3=2, V4=1 ?
                   13155:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   13156:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   13157:      * In order to get the real value in the data, we use nbcode
                   13158:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   13159:      * We are keeping this crazy system in order to be able (in the future?) 
                   13160:      * to have more than 2 values (0 or 1) for a covariate.
                   13161:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   13162:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   13163:      *              bbbbbbbb
                   13164:      *              76543210     
                   13165:      *   h-1        00000101 (6-1=5)
1.219     brouard  13166:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  13167:      *           &
                   13168:      *     1        00000001 (1)
1.219     brouard  13169:      *              00000000        = 1 & ((h-1) >> (k-1))
                   13170:      *          +1= 00000001 =1 
1.211     brouard  13171:      *
                   13172:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   13173:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   13174:      *    >>k'            11
                   13175:      *          &   00000001
                   13176:      *            = 00000001
                   13177:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   13178:      * Reverse h=6 and m=16?
                   13179:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   13180:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   13181:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   13182:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   13183:      * V3=decodtabm(14,3,2**4)=2
                   13184:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   13185:      *(h-1) >> (j-1)    0011 =13 >> 2
                   13186:      *          &1 000000001
                   13187:      *           = 000000001
                   13188:      *         +1= 000000010 =2
                   13189:      *                  2211
                   13190:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   13191:      *                  V3=2
1.220     brouard  13192:                 * codtabm and decodtabm are identical
1.211     brouard  13193:      */
                   13194: 
1.145     brouard  13195: 
                   13196:  free_ivector(Ndum,-1,NCOVMAX);
                   13197: 
                   13198: 
1.126     brouard  13199:     
1.186     brouard  13200:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  13201:   strcpy(optionfilegnuplot,optionfilefiname);
                   13202:   if(mle==-3)
1.201     brouard  13203:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  13204:   strcat(optionfilegnuplot,".gp");
                   13205: 
                   13206:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   13207:     printf("Problem with file %s",optionfilegnuplot);
                   13208:   }
                   13209:   else{
1.204     brouard  13210:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  13211:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  13212:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   13213:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  13214:   }
                   13215:   /*  fclose(ficgp);*/
1.186     brouard  13216: 
                   13217: 
                   13218:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  13219: 
                   13220:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   13221:   if(mle==-3)
1.201     brouard  13222:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  13223:   strcat(optionfilehtm,".htm");
                   13224:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  13225:     printf("Problem with %s \n",optionfilehtm);
                   13226:     exit(0);
1.126     brouard  13227:   }
                   13228: 
                   13229:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13230:   strcat(optionfilehtmcov,"-cov.htm");
                   13231:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13232:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13233:   }
                   13234:   else{
                   13235:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13236: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13237: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13238:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13239:   }
                   13240: 
1.335     brouard  13241:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13242: <title>IMaCh %s</title></head>\n\
                   13243:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13244: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13245: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13246: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13247: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13248:   
                   13249:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13250: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13251: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13252: This file: <a href=\"%s\">%s</a></br>Title=%s <br>Datafile=<a href=\"%s\">%s</a> Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  13253: \n\
                   13254: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13255:  <ul><li><h4>Parameter files</h4>\n\
                   13256:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13257:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13258:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13259:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13260:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13261:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13262:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13263:          fileres,fileres,\
                   13264:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13265:   fflush(fichtm);
                   13266: 
                   13267:   strcpy(pathr,path);
                   13268:   strcat(pathr,optionfilefiname);
1.184     brouard  13269: #ifdef WIN32
                   13270:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13271: #else
1.126     brouard  13272:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13273: #endif
                   13274:          
1.126     brouard  13275:   
1.220     brouard  13276:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13277:                 and for any valid combination of covariates
1.126     brouard  13278:      and prints on file fileres'p'. */
1.251     brouard  13279:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13280:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13281: 
                   13282:   fprintf(fichtm,"\n");
1.286     brouard  13283:   fprintf(fichtm,"<h4>Parameter line 2</h4><ul><li>Tolerance for the convergence of the likelihood: ftol=%g \n<li>Interval for the elementary matrix (in month): stepm=%d",\
1.274     brouard  13284:          ftol, stepm);
                   13285:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13286:   ncurrv=1;
                   13287:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13288:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13289:   ncurrv=i;
                   13290:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13291:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13292:   ncurrv=i;
                   13293:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13294:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13295:   ncurrv=i;
                   13296:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13297:   fprintf(fichtm,"\n<li>Weights column \n<br>Number of alive states: nlstate=%d <br>Number of death states (not really implemented): ndeath=%d \n<li>Number of waves: maxwav=%d \n<li>Parameter for maximization (1), using parameter values (0), for design of parameters and variance-covariance matrix: mle=%d \n<li>Does the weight column be taken into account (1), or not (0): weight=%d</ul>\n", \
                   13298:           nlstate, ndeath, maxwav, mle, weightopt);
                   13299: 
                   13300:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13301: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13302: 
                   13303:   
1.317     brouard  13304:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13305: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13306: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13307:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13308:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13309:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13310:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13311:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13312:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13313: 
1.126     brouard  13314:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13315:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13316:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13317: 
                   13318:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13319:   /* For mortality only */
1.126     brouard  13320:   if (mle==-3){
1.136     brouard  13321:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13322:     for(i=1;i<=NDIM;i++)
                   13323:       for(j=1;j<=NDIM;j++)
                   13324:        ximort[i][j]=0.;
1.186     brouard  13325:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13326:     cens=ivector(firstobs,lastobs);
                   13327:     ageexmed=vector(firstobs,lastobs);
                   13328:     agecens=vector(firstobs,lastobs);
                   13329:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13330:                
1.126     brouard  13331:     for (i=1; i<=imx; i++){
                   13332:       dcwave[i]=-1;
                   13333:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13334:        if (s[m][i]>nlstate) {
                   13335:          dcwave[i]=m;
                   13336:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13337:          break;
                   13338:        }
1.126     brouard  13339:     }
1.226     brouard  13340:     
1.126     brouard  13341:     for (i=1; i<=imx; i++) {
                   13342:       if (wav[i]>0){
1.226     brouard  13343:        ageexmed[i]=agev[mw[1][i]][i];
                   13344:        j=wav[i];
                   13345:        agecens[i]=1.; 
                   13346:        
                   13347:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13348:          agecens[i]=agev[mw[j][i]][i];
                   13349:          cens[i]= 1;
                   13350:        }else if (ageexmed[i]< 1) 
                   13351:          cens[i]= -1;
                   13352:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13353:          cens[i]=0 ;
1.126     brouard  13354:       }
                   13355:       else cens[i]=-1;
                   13356:     }
                   13357:     
                   13358:     for (i=1;i<=NDIM;i++) {
                   13359:       for (j=1;j<=NDIM;j++)
1.226     brouard  13360:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13361:     }
                   13362:     
1.302     brouard  13363:     p[1]=0.0268; p[NDIM]=0.083;
                   13364:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13365:     
                   13366:     
1.136     brouard  13367: #ifdef GSL
                   13368:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13369: #else
1.126     brouard  13370:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13371: #endif
1.201     brouard  13372:     strcpy(filerespow,"POW-MORT_"); 
                   13373:     strcat(filerespow,fileresu);
1.126     brouard  13374:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13375:       printf("Problem with resultfile: %s\n", filerespow);
                   13376:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13377:     }
1.136     brouard  13378: #ifdef GSL
                   13379:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13380: #else
1.126     brouard  13381:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13382: #endif
1.126     brouard  13383:     /*  for (i=1;i<=nlstate;i++)
                   13384:        for(j=1;j<=nlstate+ndeath;j++)
                   13385:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13386:     */
                   13387:     fprintf(ficrespow,"\n");
1.136     brouard  13388: #ifdef GSL
                   13389:     /* gsl starts here */ 
                   13390:     T = gsl_multimin_fminimizer_nmsimplex;
                   13391:     gsl_multimin_fminimizer *sfm = NULL;
                   13392:     gsl_vector *ss, *x;
                   13393:     gsl_multimin_function minex_func;
                   13394: 
                   13395:     /* Initial vertex size vector */
                   13396:     ss = gsl_vector_alloc (NDIM);
                   13397:     
                   13398:     if (ss == NULL){
                   13399:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13400:     }
                   13401:     /* Set all step sizes to 1 */
                   13402:     gsl_vector_set_all (ss, 0.001);
                   13403: 
                   13404:     /* Starting point */
1.126     brouard  13405:     
1.136     brouard  13406:     x = gsl_vector_alloc (NDIM);
                   13407:     
                   13408:     if (x == NULL){
                   13409:       gsl_vector_free(ss);
                   13410:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13411:     }
                   13412:   
                   13413:     /* Initialize method and iterate */
                   13414:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13415:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13416:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13417:     gsl_vector_set(x, 0, p[1]);
                   13418:     gsl_vector_set(x, 1, p[2]);
                   13419: 
                   13420:     minex_func.f = &gompertz_f;
                   13421:     minex_func.n = NDIM;
                   13422:     minex_func.params = (void *)&p; /* ??? */
                   13423:     
                   13424:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13425:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13426:     
                   13427:     printf("Iterations beginning .....\n\n");
                   13428:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13429: 
                   13430:     iteri=0;
                   13431:     while (rval == GSL_CONTINUE){
                   13432:       iteri++;
                   13433:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13434:       
                   13435:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13436:       fflush(0);
                   13437:       
                   13438:       if (status) 
                   13439:         break;
                   13440:       
                   13441:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13442:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13443:       
                   13444:       if (rval == GSL_SUCCESS)
                   13445:         printf ("converged to a local maximum at\n");
                   13446:       
                   13447:       printf("%5d ", iteri);
                   13448:       for (it = 0; it < NDIM; it++){
                   13449:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13450:       }
                   13451:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13452:     }
                   13453:     
                   13454:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13455:     
                   13456:     gsl_vector_free(x); /* initial values */
                   13457:     gsl_vector_free(ss); /* inital step size */
                   13458:     for (it=0; it<NDIM; it++){
                   13459:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13460:       fprintf(ficrespow," %.12lf", p[it]);
                   13461:     }
                   13462:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13463: #endif
                   13464: #ifdef POWELL
                   13465:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13466: #endif  
1.126     brouard  13467:     fclose(ficrespow);
                   13468:     
1.203     brouard  13469:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13470: 
                   13471:     for(i=1; i <=NDIM; i++)
                   13472:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13473:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13474:     
                   13475:     printf("\nCovariance matrix\n ");
1.203     brouard  13476:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13477:     for(i=1; i <=NDIM; i++) {
                   13478:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13479:                                printf("%f ",matcov[i][j]);
                   13480:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13481:       }
1.203     brouard  13482:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13483:     }
                   13484:     
                   13485:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13486:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13487:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13488:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13489:     }
1.302     brouard  13490:     lsurv=vector(agegomp,AGESUP);
                   13491:     lpop=vector(agegomp,AGESUP);
                   13492:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13493:     lsurv[agegomp]=100000;
                   13494:     
                   13495:     for (k=agegomp;k<=AGESUP;k++) {
                   13496:       agemortsup=k;
                   13497:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13498:     }
                   13499:     
                   13500:     for (k=agegomp;k<agemortsup;k++)
                   13501:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13502:     
                   13503:     for (k=agegomp;k<agemortsup;k++){
                   13504:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13505:       sumlpop=sumlpop+lpop[k];
                   13506:     }
                   13507:     
                   13508:     tpop[agegomp]=sumlpop;
                   13509:     for (k=agegomp;k<(agemortsup-3);k++){
                   13510:       /*  tpop[k+1]=2;*/
                   13511:       tpop[k+1]=tpop[k]-lpop[k];
                   13512:     }
                   13513:     
                   13514:     
                   13515:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13516:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13517:       printf("%d %.0lf %lf %.0lf %.0lf %.0lf %lf\n",k,lsurv[k],p[1]*exp(p[2]*(k-agegomp)),(p[1]*exp(p[2]*(k-agegomp)))*lsurv[k],lpop[k],tpop[k],tpop[k]/lsurv[k]);
                   13518:     
                   13519:     
                   13520:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13521:                ageminpar=50;
                   13522:                agemaxpar=100;
1.194     brouard  13523:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13524:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13525: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13526: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13527:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13528: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13529: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13530:     }else{
                   13531:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13532:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
1.201     brouard  13533:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13534:                }
1.201     brouard  13535:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13536:                     stepm, weightopt,\
                   13537:                     model,imx,p,matcov,agemortsup);
                   13538:     
1.302     brouard  13539:     free_vector(lsurv,agegomp,AGESUP);
                   13540:     free_vector(lpop,agegomp,AGESUP);
                   13541:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13542:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13543:     free_ivector(dcwave,firstobs,lastobs);
                   13544:     free_vector(agecens,firstobs,lastobs);
                   13545:     free_vector(ageexmed,firstobs,lastobs);
                   13546:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13547: #ifdef GSL
1.136     brouard  13548: #endif
1.186     brouard  13549:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13550:   /* Standard  */
                   13551:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13552:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13553:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13554:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13555:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13556:     for (k=1; k<=npar;k++)
                   13557:       printf(" %d %8.5f",k,p[k]);
                   13558:     printf("\n");
1.205     brouard  13559:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13560:       /* mlikeli uses func not funcone */
1.247     brouard  13561:       /* for(i=1;i<nlstate;i++){ */
                   13562:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13563:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13564:       /* } */
1.205     brouard  13565:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13566:     }
                   13567:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13568:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13569:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13570:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13571:     }
                   13572:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13573:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13574:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13575:           /* exit(0); */
1.126     brouard  13576:     for (k=1; k<=npar;k++)
                   13577:       printf(" %d %8.5f",k,p[k]);
                   13578:     printf("\n");
                   13579:     
                   13580:     /*--------- results files --------------*/
1.283     brouard  13581:     /* fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, weightopt,model); */
1.126     brouard  13582:     
                   13583:     
                   13584:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13585:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13586:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13587: 
                   13588:     printf("#model=  1      +     age ");
                   13589:     fprintf(ficres,"#model=  1      +     age ");
                   13590:     fprintf(ficlog,"#model=  1      +     age ");
                   13591:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13592: </ul>", model);
                   13593: 
                   13594:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13595:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13596:     if(nagesqr==1){
                   13597:       printf("  + age*age  ");
                   13598:       fprintf(ficres,"  + age*age  ");
                   13599:       fprintf(ficlog,"  + age*age  ");
                   13600:       fprintf(fichtm, "<th>+ age*age</th>");
                   13601:     }
                   13602:     for(j=1;j <=ncovmodel-2;j++){
                   13603:       if(Typevar[j]==0) {
                   13604:        printf("  +      V%d  ",Tvar[j]);
                   13605:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13606:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13607:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13608:       }else if(Typevar[j]==1) {
                   13609:        printf("  +    V%d*age ",Tvar[j]);
                   13610:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13611:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13612:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13613:       }else if(Typevar[j]==2) {
                   13614:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13615:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13616:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13617:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13618:       }
                   13619:     }
                   13620:     printf("\n");
                   13621:     fprintf(ficres,"\n");
                   13622:     fprintf(ficlog,"\n");
                   13623:     fprintf(fichtm, "</tr>");
                   13624:     fprintf(fichtm, "\n");
                   13625:     
                   13626:     
1.126     brouard  13627:     for(i=1,jk=1; i <=nlstate; i++){
                   13628:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13629:        if (k != i) {
1.319     brouard  13630:          fprintf(fichtm, "<tr>");
1.225     brouard  13631:          printf("%d%d ",i,k);
                   13632:          fprintf(ficlog,"%d%d ",i,k);
                   13633:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13634:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13635:          for(j=1; j <=ncovmodel; j++){
                   13636:            printf("%12.7f ",p[jk]);
                   13637:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13638:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13639:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13640:            jk++; 
                   13641:          }
                   13642:          printf("\n");
                   13643:          fprintf(ficlog,"\n");
                   13644:          fprintf(ficres,"\n");
1.319     brouard  13645:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13646:        }
1.126     brouard  13647:       }
                   13648:     }
1.319     brouard  13649:     /* fprintf(fichtm,"</tr>\n"); */
                   13650:     fprintf(fichtm,"</table>\n");
                   13651:     fprintf(fichtm, "\n");
                   13652: 
1.203     brouard  13653:     if(mle != 0){
                   13654:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13655:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13656:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13657:       printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
                   13658:       fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
1.322     brouard  13659:       fprintf(fichtm, "\n<p>The Wald test results are output only if the maximimzation of the Likelihood is performed (mle=1)\n</br>Parameters, Wald tests and Wald-based confidence intervals\n</br> W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n</br> And Wald-based confidence intervals plus and minus 1.96 * W \n </br> It might be better to visualize the covariance matrix. See the page '<a href=\"%s\">Matrix of variance-covariance of one-step probabilities and its graphs</a>'.\n</br>",optionfilehtmcov);
1.319     brouard  13660:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13661:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13662:       if(nagesqr==1){
                   13663:        printf("  + age*age  ");
                   13664:        fprintf(ficres,"  + age*age  ");
                   13665:        fprintf(ficlog,"  + age*age  ");
                   13666:        fprintf(fichtm, "<th>+ age*age</th>");
                   13667:       }
                   13668:       for(j=1;j <=ncovmodel-2;j++){
                   13669:        if(Typevar[j]==0) {
                   13670:          printf("  +      V%d  ",Tvar[j]);
                   13671:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13672:        }else if(Typevar[j]==1) {
                   13673:          printf("  +    V%d*age ",Tvar[j]);
                   13674:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13675:        }else if(Typevar[j]==2) {
                   13676:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13677:        }
                   13678:       }
                   13679:       fprintf(fichtm, "</tr>\n");
                   13680:  
1.203     brouard  13681:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13682:        for(k=1; k <=(nlstate+ndeath); k++){
                   13683:          if (k != i) {
1.319     brouard  13684:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13685:            printf("%d%d ",i,k);
                   13686:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13687:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13688:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13689:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13690:              printf("%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   13691:              fprintf(ficlog,"%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.319     brouard  13692:              if(fabs(wald) > 1.96){
1.321     brouard  13693:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13694:              }else{
                   13695:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13696:              }
1.324     brouard  13697:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13698:              fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.225     brouard  13699:              jk++; 
                   13700:            }
                   13701:            printf("\n");
                   13702:            fprintf(ficlog,"\n");
1.319     brouard  13703:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13704:          }
                   13705:        }
1.193     brouard  13706:       }
1.203     brouard  13707:     } /* end of hesscov and Wald tests */
1.319     brouard  13708:     fprintf(fichtm,"</table>\n");
1.225     brouard  13709:     
1.203     brouard  13710:     /*  */
1.126     brouard  13711:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13712:     printf("# Scales (for hessian or gradient estimation)\n");
                   13713:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13714:     for(i=1,jk=1; i <=nlstate; i++){
                   13715:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13716:        if (j!=i) {
                   13717:          fprintf(ficres,"%1d%1d",i,j);
                   13718:          printf("%1d%1d",i,j);
                   13719:          fprintf(ficlog,"%1d%1d",i,j);
                   13720:          for(k=1; k<=ncovmodel;k++){
                   13721:            printf(" %.5e",delti[jk]);
                   13722:            fprintf(ficlog," %.5e",delti[jk]);
                   13723:            fprintf(ficres," %.5e",delti[jk]);
                   13724:            jk++;
                   13725:          }
                   13726:          printf("\n");
                   13727:          fprintf(ficlog,"\n");
                   13728:          fprintf(ficres,"\n");
                   13729:        }
1.126     brouard  13730:       }
                   13731:     }
                   13732:     
                   13733:     fprintf(ficres,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
1.203     brouard  13734:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13735:       printf("# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                   13736:     fprintf(ficlog,"# Covariance matrix \n# 121 Var(a12)\n# 122 Cov(b12,a12) Var(b12)\n#   ...\n# 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n");
                   13737:     /* # 121 Var(a12)\n\ */
                   13738:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13739:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13740:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13741:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13742:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13743:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13744:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13745:     
                   13746:     
                   13747:     /* Just to have a covariance matrix which will be more understandable
                   13748:        even is we still don't want to manage dictionary of variables
                   13749:     */
                   13750:     for(itimes=1;itimes<=2;itimes++){
                   13751:       jj=0;
                   13752:       for(i=1; i <=nlstate; i++){
1.225     brouard  13753:        for(j=1; j <=nlstate+ndeath; j++){
                   13754:          if(j==i) continue;
                   13755:          for(k=1; k<=ncovmodel;k++){
                   13756:            jj++;
                   13757:            ca[0]= k+'a'-1;ca[1]='\0';
                   13758:            if(itimes==1){
                   13759:              if(mle>=1)
                   13760:                printf("#%1d%1d%d",i,j,k);
                   13761:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13762:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13763:            }else{
                   13764:              if(mle>=1)
                   13765:                printf("%1d%1d%d",i,j,k);
                   13766:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13767:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13768:            }
                   13769:            ll=0;
                   13770:            for(li=1;li <=nlstate; li++){
                   13771:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13772:                if(lj==li) continue;
                   13773:                for(lk=1;lk<=ncovmodel;lk++){
                   13774:                  ll++;
                   13775:                  if(ll<=jj){
                   13776:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13777:                    if(ll<jj){
                   13778:                      if(itimes==1){
                   13779:                        if(mle>=1)
                   13780:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13781:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13782:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13783:                      }else{
                   13784:                        if(mle>=1)
                   13785:                          printf(" %.5e",matcov[jj][ll]); 
                   13786:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13787:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13788:                      }
                   13789:                    }else{
                   13790:                      if(itimes==1){
                   13791:                        if(mle>=1)
                   13792:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13793:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13794:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13795:                      }else{
                   13796:                        if(mle>=1)
                   13797:                          printf(" %.7e",matcov[jj][ll]); 
                   13798:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13799:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13800:                      }
                   13801:                    }
                   13802:                  }
                   13803:                } /* end lk */
                   13804:              } /* end lj */
                   13805:            } /* end li */
                   13806:            if(mle>=1)
                   13807:              printf("\n");
                   13808:            fprintf(ficlog,"\n");
                   13809:            fprintf(ficres,"\n");
                   13810:            numlinepar++;
                   13811:          } /* end k*/
                   13812:        } /*end j */
1.126     brouard  13813:       } /* end i */
                   13814:     } /* end itimes */
                   13815:     
                   13816:     fflush(ficlog);
                   13817:     fflush(ficres);
1.225     brouard  13818:     while(fgets(line, MAXLINE, ficpar)) {
                   13819:       /* If line starts with a # it is a comment */
                   13820:       if (line[0] == '#') {
                   13821:        numlinepar++;
                   13822:        fputs(line,stdout);
                   13823:        fputs(line,ficparo);
                   13824:        fputs(line,ficlog);
1.299     brouard  13825:        fputs(line,ficres);
1.225     brouard  13826:        continue;
                   13827:       }else
                   13828:        break;
                   13829:     }
                   13830:     
1.209     brouard  13831:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13832:     /*   ungetc(c,ficpar); */
                   13833:     /*   fgets(line, MAXLINE, ficpar); */
                   13834:     /*   fputs(line,stdout); */
                   13835:     /*   fputs(line,ficparo); */
                   13836:     /* } */
                   13837:     /* ungetc(c,ficpar); */
1.126     brouard  13838:     
                   13839:     estepm=0;
1.209     brouard  13840:     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
1.225     brouard  13841:       
                   13842:       if (num_filled != 6) {
                   13843:        printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   13844:        fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   13845:        goto end;
                   13846:       }
                   13847:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13848:     }
                   13849:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13850:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13851:     
1.209     brouard  13852:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13853:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13854:     if (fage <= 2) {
                   13855:       bage = ageminpar;
                   13856:       fage = agemaxpar;
                   13857:     }
                   13858:     
                   13859:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13860:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13861:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13862:                
1.186     brouard  13863:     /* Other stuffs, more or less useful */    
1.254     brouard  13864:     while(fgets(line, MAXLINE, ficpar)) {
                   13865:       /* If line starts with a # it is a comment */
                   13866:       if (line[0] == '#') {
                   13867:        numlinepar++;
                   13868:        fputs(line,stdout);
                   13869:        fputs(line,ficparo);
                   13870:        fputs(line,ficlog);
1.299     brouard  13871:        fputs(line,ficres);
1.254     brouard  13872:        continue;
                   13873:       }else
                   13874:        break;
                   13875:     }
                   13876: 
                   13877:     if((num_filled=sscanf(line,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav)) !=EOF){
                   13878:       
                   13879:       if (num_filled != 7) {
                   13880:        printf("Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   13881:        fprintf(ficlog,"Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   13882:        goto end;
                   13883:       }
                   13884:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13885:       fprintf(ficparo,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13886:       fprintf(ficres,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13887:       fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
1.126     brouard  13888:     }
1.254     brouard  13889: 
                   13890:     while(fgets(line, MAXLINE, ficpar)) {
                   13891:       /* If line starts with a # it is a comment */
                   13892:       if (line[0] == '#') {
                   13893:        numlinepar++;
                   13894:        fputs(line,stdout);
                   13895:        fputs(line,ficparo);
                   13896:        fputs(line,ficlog);
1.299     brouard  13897:        fputs(line,ficres);
1.254     brouard  13898:        continue;
                   13899:       }else
                   13900:        break;
1.126     brouard  13901:     }
                   13902:     
                   13903:     
                   13904:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13905:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13906:     
1.254     brouard  13907:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13908:       if (num_filled != 1) {
                   13909:        printf("Error: Not 1 (data)parameters in line but %d, for example:pop_based=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   13910:        fprintf(ficlog,"Error: Not 1 (data)parameters in line but %d, for example: pop_based=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   13911:        goto end;
                   13912:       }
                   13913:       printf("pop_based=%d\n",popbased);
                   13914:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13915:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13916:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13917:     }
                   13918:      
1.258     brouard  13919:     /* Results */
1.332     brouard  13920:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13921:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13922:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13923:     endishere=0;
1.258     brouard  13924:     nresult=0;
1.308     brouard  13925:     parameterline=0;
1.258     brouard  13926:     do{
                   13927:       if(!fgets(line, MAXLINE, ficpar)){
                   13928:        endishere=1;
1.308     brouard  13929:        parameterline=15;
1.258     brouard  13930:       }else if (line[0] == '#') {
                   13931:        /* If line starts with a # it is a comment */
1.254     brouard  13932:        numlinepar++;
                   13933:        fputs(line,stdout);
                   13934:        fputs(line,ficparo);
                   13935:        fputs(line,ficlog);
1.299     brouard  13936:        fputs(line,ficres);
1.254     brouard  13937:        continue;
1.258     brouard  13938:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13939:        parameterline=11;
1.296     brouard  13940:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13941:        parameterline=12;
1.307     brouard  13942:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13943:        parameterline=13;
1.307     brouard  13944:       }
1.258     brouard  13945:       else{
                   13946:        parameterline=14;
1.254     brouard  13947:       }
1.308     brouard  13948:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13949:       case 11:
1.296     brouard  13950:        if((num_filled=sscanf(line,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj)) !=EOF && (num_filled == 8)){
                   13951:                  fprintf(ficparo,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
1.258     brouard  13952:          printf("prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
                   13953:          fprintf(ficlog,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
                   13954:          fprintf(ficres,"prevforecast=%d starting-proj-date=%.lf/%.lf/%.lf final-proj-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevfcast,jproj1,mproj1,anproj1,jproj2,mproj2,anproj2,mobilavproj);
                   13955:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13956:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13957:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13958:           prvforecast = 1;
                   13959:        } 
                   13960:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13961:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13962:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13963:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13964:           prvforecast = 2;
                   13965:        }
                   13966:        else {
                   13967:          printf("Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearsfproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13968:          fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13969:          goto end;
1.258     brouard  13970:        }
1.254     brouard  13971:        break;
1.258     brouard  13972:       case 12:
1.296     brouard  13973:        if((num_filled=sscanf(line,"prevbackcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&prevbcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj)) !=EOF && (num_filled == 8)){
                   13974:           fprintf(ficparo,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13975:          printf("prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13976:          fprintf(ficlog,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13977:          fprintf(ficres,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13978:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13979:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13980:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13981:           prvbackcast = 1;
                   13982:        } 
                   13983:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13984:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13985:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13986:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13987:           prvbackcast = 2;
                   13988:        }
                   13989:        else {
                   13990:          printf("Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearsbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13991:          fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13992:          goto end;
1.258     brouard  13993:        }
1.230     brouard  13994:        break;
1.258     brouard  13995:       case 13:
1.332     brouard  13996:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13997:        nresult++; /* Sum of resultlines */
1.342     brouard  13998:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  13999:        /* removefirstspace(&resultlineori); */
                   14000:        
                   14001:        if(strstr(resultlineori,"v") !=0){
                   14002:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   14003:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   14004:          return 1;
                   14005:        }
                   14006:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  14007:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  14008:        if(nresult > MAXRESULTLINESPONE-1){
                   14009:          printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
                   14010:          fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
1.307     brouard  14011:          goto end;
                   14012:        }
1.332     brouard  14013:        
1.310     brouard  14014:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  14015:          fprintf(ficparo,"result: %s\n",resultline);
                   14016:          fprintf(ficres,"result: %s\n",resultline);
                   14017:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  14018:        } else
                   14019:          goto end;
1.307     brouard  14020:        break;
                   14021:       case 14:
                   14022:        printf("Error: Unknown command '%s'\n",line);
                   14023:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  14024:        if(line[0] == ' ' || line[0] == '\n'){
                   14025:          printf("It should not be an empty line '%s'\n",line);
                   14026:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   14027:        }         
1.307     brouard  14028:        if(ncovmodel >=2 && nresult==0 ){
                   14029:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   14030:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  14031:        }
1.307     brouard  14032:        /* goto end; */
                   14033:        break;
1.308     brouard  14034:       case 15:
                   14035:        printf("End of resultlines.\n");
                   14036:        fprintf(ficlog,"End of resultlines.\n");
                   14037:        break;
                   14038:       default: /* parameterline =0 */
1.307     brouard  14039:        nresult=1;
                   14040:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  14041:       } /* End switch parameterline */
                   14042:     }while(endishere==0); /* End do */
1.126     brouard  14043:     
1.230     brouard  14044:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  14045:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  14046:     
                   14047:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  14048:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  14049:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14050: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14051: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  14052:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  14053: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14054: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  14055:     }else{
1.270     brouard  14056:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  14057:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   14058:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   14059:       if(prvforecast==1){
                   14060:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   14061:         jprojd=jproj1;
                   14062:         mprojd=mproj1;
                   14063:         anprojd=anproj1;
                   14064:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   14065:         jprojf=jproj2;
                   14066:         mprojf=mproj2;
                   14067:         anprojf=anproj2;
                   14068:       } else if(prvforecast == 2){
                   14069:         dateprojd=dateintmean;
                   14070:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   14071:         dateprojf=dateintmean+yrfproj;
                   14072:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   14073:       }
                   14074:       if(prvbackcast==1){
                   14075:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   14076:         jbackd=jback1;
                   14077:         mbackd=mback1;
                   14078:         anbackd=anback1;
                   14079:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   14080:         jbackf=jback2;
                   14081:         mbackf=mback2;
                   14082:         anbackf=anback2;
                   14083:       } else if(prvbackcast == 2){
                   14084:         datebackd=dateintmean;
                   14085:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   14086:         datebackf=dateintmean-yrbproj;
                   14087:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   14088:       }
                   14089:       
                   14090:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  14091:     }
                   14092:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  14093:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   14094:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  14095:                
1.225     brouard  14096:     /*------------ free_vector  -------------*/
                   14097:     /*  chdir(path); */
1.220     brouard  14098:                
1.215     brouard  14099:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   14100:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   14101:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   14102:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  14103:     free_lvector(num,firstobs,lastobs);
                   14104:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  14105:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   14106:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   14107:     fclose(ficparo);
                   14108:     fclose(ficres);
1.220     brouard  14109:                
                   14110:                
1.186     brouard  14111:     /* Other results (useful)*/
1.220     brouard  14112:                
                   14113:                
1.126     brouard  14114:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  14115:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   14116:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  14117:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  14118:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  14119:     fclose(ficrespl);
                   14120: 
                   14121:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  14122:     /*#include "hpijx.h"*/
1.332     brouard  14123:     /** h Pij x Probability to be in state j at age x+h being in i at x, for each combination k of dummies in the model line or to nres?*/
                   14124:     /* calls hpxij with combination k */
1.180     brouard  14125:     hPijx(p, bage, fage);
1.145     brouard  14126:     fclose(ficrespij);
1.227     brouard  14127:     
1.220     brouard  14128:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  14129:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  14130:     k=1;
1.126     brouard  14131:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  14132:     
1.269     brouard  14133:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   14134:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14135:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  14136:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  14137:        for(k=1;k<=ncovcombmax;k++)
                   14138:          probs[i][j][k]=0.;
1.269     brouard  14139:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   14140:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  14141:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  14142:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   14143:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  14144:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  14145:          for(k=1;k<=ncovcombmax;k++)
                   14146:            mobaverages[i][j][k]=0.;
1.219     brouard  14147:       mobaverage=mobaverages;
                   14148:       if (mobilav!=0) {
1.235     brouard  14149:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  14150:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  14151:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   14152:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   14153:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   14154:        }
1.269     brouard  14155:       } else if (mobilavproj !=0) {
1.235     brouard  14156:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  14157:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  14158:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   14159:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14160:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   14161:        }
1.269     brouard  14162:       }else{
                   14163:        printf("Internal error moving average\n");
                   14164:        fflush(stdout);
                   14165:        exit(1);
1.219     brouard  14166:       }
                   14167:     }/* end if moving average */
1.227     brouard  14168:     
1.126     brouard  14169:     /*---------- Forecasting ------------------*/
1.296     brouard  14170:     if(prevfcast==1){ 
                   14171:       /*   /\*    if(stepm ==1){*\/ */
                   14172:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14173:       /*This done previously after freqsummary.*/
                   14174:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   14175:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   14176:       
                   14177:       /* } else if (prvforecast==2){ */
                   14178:       /*   /\*    if(stepm ==1){*\/ */
                   14179:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   14180:       /* } */
                   14181:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   14182:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  14183:     }
1.269     brouard  14184: 
1.296     brouard  14185:     /* Prevbcasting */
                   14186:     if(prevbcast==1){
1.219     brouard  14187:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14188:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   14189:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   14190: 
                   14191:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   14192: 
                   14193:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  14194: 
1.219     brouard  14195:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   14196:       fclose(ficresplb);
                   14197: 
1.222     brouard  14198:       hBijx(p, bage, fage, mobaverage);
                   14199:       fclose(ficrespijb);
1.219     brouard  14200: 
1.296     brouard  14201:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   14202:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   14203:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   14204:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   14205:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   14206:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   14207: 
                   14208:       
1.269     brouard  14209:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14210: 
                   14211:       
1.269     brouard  14212:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  14213:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14214:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   14215:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  14216:     }    /* end  Prevbcasting */
1.268     brouard  14217:  
1.186     brouard  14218:  
                   14219:     /* ------ Other prevalence ratios------------ */
1.126     brouard  14220: 
1.215     brouard  14221:     free_ivector(wav,1,imx);
                   14222:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   14223:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   14224:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  14225:                
                   14226:                
1.127     brouard  14227:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14228:                
1.201     brouard  14229:     strcpy(filerese,"E_");
                   14230:     strcat(filerese,fileresu);
1.126     brouard  14231:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14232:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14233:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14234:     }
1.208     brouard  14235:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14236:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14237: 
                   14238:     pstamp(ficreseij);
1.219     brouard  14239:                
1.235     brouard  14240:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14241:     if (cptcovn < 1){i1=1;}
                   14242:     
                   14243:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14244:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14245:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14246:        continue;
1.219     brouard  14247:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14248:       printf("\n#****** ");
1.225     brouard  14249:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14250:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14251:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14252:       }
                   14253:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14254:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14255:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14256:       }
                   14257:       fprintf(ficreseij,"******\n");
1.235     brouard  14258:       printf("******\n");
1.219     brouard  14259:       
                   14260:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14261:       oldm=oldms;savm=savms;
1.330     brouard  14262:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
1.235     brouard  14263:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14264:       
1.219     brouard  14265:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14266:     }
                   14267:     fclose(ficreseij);
1.208     brouard  14268:     printf("done evsij\n");fflush(stdout);
                   14269:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14270: 
1.218     brouard  14271:                
1.227     brouard  14272:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14273:     /* Should be moved in a function */                
1.201     brouard  14274:     strcpy(filerest,"T_");
                   14275:     strcat(filerest,fileresu);
1.127     brouard  14276:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14277:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14278:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14279:     }
1.208     brouard  14280:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14281:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14282:     strcpy(fileresstde,"STDE_");
                   14283:     strcat(fileresstde,fileresu);
1.126     brouard  14284:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14285:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14286:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14287:     }
1.227     brouard  14288:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14289:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14290: 
1.201     brouard  14291:     strcpy(filerescve,"CVE_");
                   14292:     strcat(filerescve,fileresu);
1.126     brouard  14293:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14294:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14295:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14296:     }
1.227     brouard  14297:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14298:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14299: 
1.201     brouard  14300:     strcpy(fileresv,"V_");
                   14301:     strcat(fileresv,fileresu);
1.126     brouard  14302:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14303:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14304:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14305:     }
1.227     brouard  14306:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14307:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14308: 
1.235     brouard  14309:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14310:     if (cptcovn < 1){i1=1;}
                   14311:     
1.334     brouard  14312:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14313:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14314:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14315:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14316:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14317:       /* */
                   14318:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
1.235     brouard  14319:        continue;
1.321     brouard  14320:       printf("\n# model %s \n#****** Result for:", model);
                   14321:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14322:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14323:       /* It might not be a good idea to mix dummies and quantitative */
                   14324:       /* for(j=1;j<=cptcoveff;j++){ /\* j=resultpos. Could be a loop on cptcovs: number of single dummy covariate in the result line as well as in the model *\/ */
                   14325:       for(j=1;j<=cptcovs;j++){ /* j=resultpos. Could be a loop on cptcovs: number of single covariate (dummy or quantitative) in the result line as well as in the model */
                   14326:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14327:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14328:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14329:         * (V5 is quanti) V4 and V3 are dummies
                   14330:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14331:         *                                                              l=1 l=2
                   14332:         *                                                           k=1  1   1   0   0
                   14333:         *                                                           k=2  2   1   1   0
                   14334:         *                                                           k=3 [1] [2]  0   1
                   14335:         *                                                           k=4  2   2   1   1
                   14336:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14337:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14338:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14339:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14340:         */
                   14341:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14342:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14343: /* We give up with the combinations!! */
1.342     brouard  14344:        /* if(debugILK) */
                   14345:        /*   printf("\n j=%d In computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d Fixed[modelresult[nres][j]]=%d\n", j, nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff,Fixed[modelresult[nres][j]]);  /\* end if dummy  or quanti *\/ */
1.334     brouard  14346: 
                   14347:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.337     brouard  14348:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14349:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14350:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  14351:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14352:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14353:          }else{
                   14354:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14355:          }
                   14356:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14357:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14358:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14359:          /* For each selected (single) quantitative value */
1.337     brouard  14360:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14361:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14362:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14363:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14364:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14365:          }else{
                   14366:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14367:          }
                   14368:        }else{
                   14369:          printf("Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   14370:          fprintf(ficlog,"Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   14371:          exit(1);
                   14372:        }
1.335     brouard  14373:       } /* End loop for each variable in the resultline */
1.334     brouard  14374:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14375:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14376:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14377:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14378:       /* }      */
1.208     brouard  14379:       fprintf(ficrest,"******\n");
1.227     brouard  14380:       fprintf(ficlog,"******\n");
                   14381:       printf("******\n");
1.208     brouard  14382:       
                   14383:       fprintf(ficresstdeij,"\n#****** ");
                   14384:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14385:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14386:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14387:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14388:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14389:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14390:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14391:       }
                   14392:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
1.337     brouard  14393:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14394:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14395:       }        
1.208     brouard  14396:       fprintf(ficresstdeij,"******\n");
                   14397:       fprintf(ficrescveij,"******\n");
                   14398:       
                   14399:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14400:       /* pstamp(ficresvij); */
1.225     brouard  14401:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14402:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14403:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14404:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14405:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14406:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14407:       }        
1.208     brouard  14408:       fprintf(ficresvij,"******\n");
                   14409:       
                   14410:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14411:       oldm=oldms;savm=savms;
1.235     brouard  14412:       printf(" cvevsij ");
                   14413:       fprintf(ficlog, " cvevsij ");
                   14414:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14415:       printf(" end cvevsij \n ");
                   14416:       fprintf(ficlog, " end cvevsij \n ");
                   14417:       
                   14418:       /*
                   14419:        */
                   14420:       /* goto endfree; */
                   14421:       
                   14422:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14423:       pstamp(ficrest);
                   14424:       
1.269     brouard  14425:       epj=vector(1,nlstate+1);
1.208     brouard  14426:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14427:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14428:        cptcod= 0; /* To be deleted */
                   14429:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14430:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14431:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
1.227     brouard  14432:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
                   14433:        if(vpopbased==1)
                   14434:          fprintf(ficrest,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d)\n",mobilav);
                   14435:        else
1.288     brouard  14436:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14437:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14438:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14439:        fprintf(ficrest,"\n");
                   14440:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14441:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14442:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14443:        for(age=bage; age <=fage ;age++){
1.235     brouard  14444:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14445:          if (vpopbased==1) {
                   14446:            if(mobilav ==0){
                   14447:              for(i=1; i<=nlstate;i++)
                   14448:                prlim[i][i]=probs[(int)age][i][k];
                   14449:            }else{ /* mobilav */ 
                   14450:              for(i=1; i<=nlstate;i++)
                   14451:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14452:            }
                   14453:          }
1.219     brouard  14454:          
1.227     brouard  14455:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14456:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14457:          /* printf(" age %4.0f ",age); */
                   14458:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14459:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14460:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14461:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14462:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14463:            }
                   14464:            epj[nlstate+1] +=epj[j];
                   14465:          }
                   14466:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14467:          
1.227     brouard  14468:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14469:            for(j=1;j <=nlstate;j++)
                   14470:              vepp += vareij[i][j][(int)age];
                   14471:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14472:          for(j=1;j <=nlstate;j++){
                   14473:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14474:          }
                   14475:          fprintf(ficrest,"\n");
                   14476:        }
1.208     brouard  14477:       } /* End vpopbased */
1.269     brouard  14478:       free_vector(epj,1,nlstate+1);
1.208     brouard  14479:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14480:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14481:       printf("done selection\n");fflush(stdout);
                   14482:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14483:       
1.335     brouard  14484:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14485: 
                   14486:     printf("done State-specific expectancies\n");fflush(stdout);
                   14487:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14488: 
1.335     brouard  14489:     /* variance-covariance of forward period prevalence */
1.269     brouard  14490:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14491: 
1.227     brouard  14492:     
1.290     brouard  14493:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14494:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14495:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14496:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14497:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14498:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14499:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14500:     free_ivector(tab,1,NCOVMAX);
                   14501:     fclose(ficresstdeij);
                   14502:     fclose(ficrescveij);
                   14503:     fclose(ficresvij);
                   14504:     fclose(ficrest);
                   14505:     fclose(ficpar);
                   14506:     
                   14507:     
1.126     brouard  14508:     /*---------- End : free ----------------*/
1.219     brouard  14509:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14510:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14511:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14512:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14513:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14514:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14515:   /* endfree:*/
                   14516:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14517:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14518:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  14519:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   14520:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  14521:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14522:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14523:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14524:   free_matrix(matcov,1,npar,1,npar);
                   14525:   free_matrix(hess,1,npar,1,npar);
                   14526:   /*free_vector(delti,1,npar);*/
                   14527:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14528:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14529:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14530:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14531:   
                   14532:   free_ivector(ncodemax,1,NCOVMAX);
                   14533:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14534:   free_ivector(Dummy,-1,NCOVMAX);
                   14535:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14536:   free_ivector(DummyV,1,NCOVMAX);
                   14537:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14538:   free_ivector(Typevar,-1,NCOVMAX);
                   14539:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14540:   free_ivector(TvarsQ,1,NCOVMAX);
                   14541:   free_ivector(TvarsQind,1,NCOVMAX);
                   14542:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14543:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14544:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14545:   free_ivector(TvarFD,1,NCOVMAX);
                   14546:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14547:   free_ivector(TvarF,1,NCOVMAX);
                   14548:   free_ivector(TvarFind,1,NCOVMAX);
                   14549:   free_ivector(TvarV,1,NCOVMAX);
                   14550:   free_ivector(TvarVind,1,NCOVMAX);
                   14551:   free_ivector(TvarA,1,NCOVMAX);
                   14552:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14553:   free_ivector(TvarFQ,1,NCOVMAX);
                   14554:   free_ivector(TvarFQind,1,NCOVMAX);
                   14555:   free_ivector(TvarVD,1,NCOVMAX);
                   14556:   free_ivector(TvarVDind,1,NCOVMAX);
                   14557:   free_ivector(TvarVQ,1,NCOVMAX);
                   14558:   free_ivector(TvarVQind,1,NCOVMAX);
1.339     brouard  14559:   free_ivector(TvarVV,1,NCOVMAX);
                   14560:   free_ivector(TvarVVind,1,NCOVMAX);
                   14561:   
1.230     brouard  14562:   free_ivector(Tvarsel,1,NCOVMAX);
                   14563:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14564:   free_ivector(Tposprod,1,NCOVMAX);
                   14565:   free_ivector(Tprod,1,NCOVMAX);
                   14566:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14567:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14568:   free_ivector(Tage,1,NCOVMAX);
                   14569:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14570:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14571:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14572: 
                   14573:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14574: 
1.227     brouard  14575:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14576:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14577:   fflush(fichtm);
                   14578:   fflush(ficgp);
                   14579:   
1.227     brouard  14580:   
1.126     brouard  14581:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14582:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14583:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
1.126     brouard  14584:   }else{
                   14585:     printf("End of Imach\n");
                   14586:     fprintf(ficlog,"End of Imach\n");
                   14587:   }
                   14588:   printf("See log file on %s\n",filelog);
                   14589:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14590:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14591:   rend_time = time(NULL);  
                   14592:   end_time = *localtime(&rend_time);
                   14593:   /* tml = *localtime(&end_time.tm_sec); */
                   14594:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14595:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14596:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14597:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14598:   
1.157     brouard  14599:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14600:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14601:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14602:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14603: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14604:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14605:   fclose(fichtm);
                   14606:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14607:   fclose(fichtmcov);
                   14608:   fclose(ficgp);
                   14609:   fclose(ficlog);
                   14610:   /*------ End -----------*/
1.227     brouard  14611:   
1.281     brouard  14612: 
                   14613: /* Executes gnuplot */
1.227     brouard  14614:   
                   14615:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14616: #ifdef WIN32
1.227     brouard  14617:   if (_chdir(pathcd) != 0)
                   14618:     printf("Can't move to directory %s!\n",path);
                   14619:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14620: #else
1.227     brouard  14621:     if(chdir(pathcd) != 0)
                   14622:       printf("Can't move to directory %s!\n", path);
                   14623:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14624: #endif 
1.126     brouard  14625:     printf("Current directory %s!\n",pathcd);
                   14626:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14627:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14628: #ifdef _WIN32
1.126     brouard  14629:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14630: #endif
                   14631:   if(!stat(plotcmd,&info)){
1.158     brouard  14632:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14633:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14634:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14635:     }else
                   14636:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14637: #ifdef __unix
1.126     brouard  14638:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14639:     if(!stat(plotcmd,&info)){
1.158     brouard  14640:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14641:     }else
                   14642:       strcpy(pplotcmd,plotcmd);
                   14643: #endif
                   14644:   }else
                   14645:     strcpy(pplotcmd,plotcmd);
                   14646:   
                   14647:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14648:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14649:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14650:   
1.126     brouard  14651:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14652:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14653:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14654:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14655:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14656:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14657:       strcpy(plotcmd,pplotcmd);
                   14658:     }
1.126     brouard  14659:   }
1.158     brouard  14660:   printf(" Successful, please wait...");
1.126     brouard  14661:   while (z[0] != 'q') {
                   14662:     /* chdir(path); */
1.154     brouard  14663:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14664:     scanf("%s",z);
                   14665: /*     if (z[0] == 'c') system("./imach"); */
                   14666:     if (z[0] == 'e') {
1.158     brouard  14667: #ifdef __APPLE__
1.152     brouard  14668:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14669: #elif __linux
                   14670:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14671: #else
1.152     brouard  14672:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14673: #endif
                   14674:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14675:       system(pplotcmd);
1.126     brouard  14676:     }
                   14677:     else if (z[0] == 'g') system(plotcmd);
                   14678:     else if (z[0] == 'q') exit(0);
                   14679:   }
1.227     brouard  14680: end:
1.126     brouard  14681:   while (z[0] != 'q') {
1.195     brouard  14682:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14683:     scanf("%s",z);
                   14684:   }
1.283     brouard  14685:   printf("End\n");
1.282     brouard  14686:   exit(0);
1.126     brouard  14687: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>